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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
alexames/flatbuffers | swift/Sources/FlatBuffers/NativeObject.swift | 4 | 2138 | /*
* Copyright 2021 Google Inc. 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.
*/
#if !os(WASI)
import Foundation
#else
import SwiftOverlayShims
#endif
/// NativeObject is a protocol that all of the `Object-API` generated code should be
/// conforming to since it allows developers the ease of use to pack and unpack their
/// Flatbuffers objects
public protocol NativeObject {}
extension NativeObject {
/// Serialize is a helper function that serailizes the data from the Object API to a bytebuffer directly th
/// - Parameter type: Type of the Flatbuffer object
/// - Returns: returns the encoded sized ByteBuffer
public func serialize<T: ObjectAPIPacker>(type: T.Type) -> ByteBuffer
where T.T == Self
{
var builder = FlatBufferBuilder(initialSize: 1024)
return serialize(builder: &builder, type: type.self)
}
/// Serialize is a helper function that serailizes the data from the Object API to a bytebuffer directly.
///
/// - Parameters:
/// - builder: A FlatBufferBuilder
/// - type: Type of the Flatbuffer object
/// - Returns: returns the encoded sized ByteBuffer
/// - Note: The `serialize(builder:type)` can be considered as a function that allows you to create smaller builder instead of the default `1024`.
/// It can be considered less expensive in terms of memory allocation
public func serialize<T: ObjectAPIPacker>(
builder: inout FlatBufferBuilder,
type: T.Type) -> ByteBuffer where T.T == Self
{
var s = self
let root = type.pack(&builder, obj: &s)
builder.finish(offset: root)
return builder.sizedBuffer
}
}
| apache-2.0 | 5d922f9e316ce1ea6fcb0d6c5c106a09 | 36.508772 | 148 | 0.723573 | 4.284569 | false | false | false | false |
zapdroid/RXWeather | Pods/RxSwift/RxSwift/Observables/Implementations/Debounce.swift | 1 | 2748 | //
// Debounce.swift
// RxSwift
//
// Created by Krunoslav Zaher on 9/11/16.
// Copyright © 2016 Krunoslav Zaher. All rights reserved.
//
final class DebounceSink<O: ObserverType>
: Sink<O>
, ObserverType
, LockOwnerType
, SynchronizedOnType {
typealias Element = O.E
typealias ParentType = Debounce<Element>
private let _parent: ParentType
let _lock = RecursiveLock()
// state
private var _id = 0 as UInt64
private var _value: Element?
let cancellable = SerialDisposable()
init(parent: ParentType, observer: O, cancel: Cancelable) {
_parent = parent
super.init(observer: observer, cancel: cancel)
}
func run() -> Disposable {
let subscription = _parent._source.subscribe(self)
return Disposables.create(subscription, cancellable)
}
func on(_ event: Event<Element>) {
synchronizedOn(event)
}
func _synchronized_on(_ event: Event<Element>) {
switch event {
case let .next(element):
_id = _id &+ 1
let currentId = _id
_value = element
let scheduler = _parent._scheduler
let dueTime = _parent._dueTime
let d = SingleAssignmentDisposable()
cancellable.disposable = d
d.setDisposable(scheduler.scheduleRelative(currentId, dueTime: dueTime, action: propagate))
case .error:
_value = nil
forwardOn(event)
dispose()
case .completed:
if let value = _value {
_value = nil
forwardOn(.next(value))
}
forwardOn(.completed)
dispose()
}
}
func propagate(_ currentId: UInt64) -> Disposable {
_lock.lock(); defer { _lock.unlock() } // {
let originalValue = _value
if let value = originalValue, _id == currentId {
_value = nil
forwardOn(.next(value))
}
// }
return Disposables.create()
}
}
final class Debounce<Element>: Producer<Element> {
fileprivate let _source: Observable<Element>
fileprivate let _dueTime: RxTimeInterval
fileprivate let _scheduler: SchedulerType
init(source: Observable<Element>, dueTime: RxTimeInterval, scheduler: SchedulerType) {
_source = source
_dueTime = dueTime
_scheduler = scheduler
}
override func run<O: ObserverType>(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == Element {
let sink = DebounceSink(parent: self, observer: observer, cancel: cancel)
let subscription = sink.run()
return (sink: sink, subscription: subscription)
}
}
| mit | 48221d2f7b9ccdb9c24d21987e817b2d | 26.47 | 144 | 0.593375 | 4.736207 | false | false | false | false |
VincentPuget/vigenere | vigenere/class/MatrixViewController.swift | 1 | 4772 | //
// MainViewController.swift
// Vigenere
//
// Created by Vincent PUGET on 05/08/2015.
// Copyright (c) 2015 Vincent PUGET. All rights reserved.
//
import Cocoa
protocol MatrixProtocol
{
func matrixIsAvailable(_ isAvailable:Bool!) -> Void
}
class MatrixViewController: NSViewController {
@IBOutlet weak var buttonValidate: NSButton!
@IBOutlet weak var buttonCancel: NSButton!
@IBOutlet weak var tfMatrixName: NSTextField!
@IBOutlet var tvMatrix: NSTextView!
@IBOutlet weak var viewBackground: NSView!
var delegate:MatrixProtocol!
var isNewMatrix:Bool! = true;
var matrixObj:Matrix!;
override func viewWillAppear() {
self.view.wantsLayer = true
self.view.layer?.backgroundColor = NSColor(calibratedRed: 69/255, green: 69/255, blue: 69/255, alpha: 1).cgColor
self.viewBackground.layer?.backgroundColor = NSColor(calibratedRed: 35/255, green: 35/255, blue: 35/255, alpha: 1).cgColor
self.tvMatrix.textColor = NSColor.white
self.tvMatrix.insertionPointColor = NSColor.white
let color = NSColor.gray
let attrs = [NSForegroundColorAttributeName: color]
let placeHolderStr = NSAttributedString(string: NSLocalizedString("matrixName", tableName: "LocalizableStrings", comment: "Matrix name"), attributes: attrs)
self.tfMatrixName.placeholderAttributedString = placeHolderStr
self.tfMatrixName.focusRingType = NSFocusRingType.none
let fieldEditor: NSTextView! = self.tfMatrixName.window?.fieldEditor(true, for: self.tfMatrixName) as! NSTextView
fieldEditor.insertionPointColor = NSColor.white
let pstyle = NSMutableParagraphStyle()
pstyle.alignment = NSTextAlignment.center
self.buttonValidate.attributedTitle = NSAttributedString(string: NSLocalizedString("save", tableName: "LocalizableStrings", comment: "Save"), attributes: [ NSForegroundColorAttributeName : NSColor.white, NSParagraphStyleAttributeName : pstyle ])
self.buttonCancel.attributedTitle = NSAttributedString(string: NSLocalizedString("cancel", tableName: "LocalizableStrings", comment: "Cancel"), attributes: [ NSForegroundColorAttributeName : NSColor.white, NSParagraphStyleAttributeName : pstyle ])
let widthConstraint = NSLayoutConstraint(item: self.view, attribute: NSLayoutAttribute.width, relatedBy: NSLayoutRelation.equal, toItem: nil, attribute: NSLayoutAttribute.notAnAttribute, multiplier: 1, constant: 460)
self.view.addConstraint(widthConstraint)
let heightConstraint = NSLayoutConstraint(item: self.view, attribute: NSLayoutAttribute.height, relatedBy: NSLayoutRelation.equal, toItem: nil, attribute: NSLayoutAttribute.notAnAttribute, multiplier: 1, constant: 260)
self.view.addConstraint(heightConstraint)
}
override func viewDidAppear() {
super.viewDidAppear()
self.view.window?.title = "Vigenere"
self.view.window?.isMovableByWindowBackground = true
self.tfMatrixName.currentEditor()?.moveToEndOfLine(self)
}
override func viewDidLoad() {
super.viewDidLoad()
self.tvMatrix.delegate = self
self.tfMatrixName.delegate = self
matrixObj = DataSingleton.instance.getMatrixObject();
if(matrixObj != nil)
{
self.isNewMatrix = false;
self.tfMatrixName.stringValue = matrixObj.name
self.tvMatrix.string = matrixObj.matrix
}
else
{
self.isNewMatrix = true;
self.tfMatrixName.stringValue = ""
self.tvMatrix.string = ""
}
}
@IBAction func IBA_buttonCancel(_ sender: AnyObject) {
self.dismissViewController(self)
}
@IBAction func IBA_buttonValidate(_ sender: AnyObject) {
var saveIsOk = false;
if(self.isNewMatrix == true)
{
saveIsOk = DataSingleton.instance.saveNewMatrix(self.tfMatrixName.stringValue, matrix: self.tvMatrix.textStorage?.string)
}
else{
saveIsOk = DataSingleton.instance.saveThisMatrix(self.matrixObj, name: self.tfMatrixName.stringValue, matrix: self.tvMatrix.textStorage?.string)
}
self.delegate.matrixIsAvailable(saveIsOk)
self.dismissViewController(self)
}
}
extension MatrixViewController: NSTextFieldDelegate {
override func controlTextDidChange(_ obj: Notification) {
}
override func controlTextDidEndEditing(_ obj: Notification) {
}
}
extension MatrixViewController: NSTextViewDelegate {
func textDidChange(_ obj: Notification)
{
}
}
| mit | a8cbf91b909878fdeca58847256e2c77 | 36.574803 | 255 | 0.680637 | 4.924665 | false | false | false | false |
m0rb1u5/iOS_10_1 | iOS_15_1 Extension/TipoMasaWKController.swift | 1 | 1138 | //
// TipoMasaWKController.swift
// iOS_10_1
//
// Created by Juan Carlos Carbajal Ipenza on 18/04/16.
// Copyright © 2016 Juan Carlos Carbajal Ipenza. All rights reserved.
//
import WatchKit
import Foundation
class TipoMasaWKController: WKInterfaceController {
let delgada: String = "Delgada"
let crujiente: String = "Crujiente"
let gruesa: String = "Gruesa"
var valorContexto: Valor = Valor()
override func awakeWithContext(context: AnyObject?) {
super.awakeWithContext(context)
self.setTitle("Tipo de Masa")
valorContexto = context as! Valor
}
override func willActivate() {
super.willActivate()
}
override func didDeactivate() {
super.didDeactivate()
}
@IBAction func guardarDelgada() {
setContexto(delgada)
}
@IBAction func guardarCrujiente() {
setContexto(crujiente)
}
@IBAction func guardarGruesa() {
setContexto(gruesa)
}
func setContexto(opcion: String) {
valorContexto.masa = opcion
pushControllerWithName("idQueso", context: valorContexto)
print(opcion)
}
}
| gpl-3.0 | 10ecab394cd52cca69c0e59b4ab7cdab | 24.840909 | 70 | 0.657872 | 3.79 | false | false | false | false |
huonw/swift | test/stdlib/Reflection.swift | 5 | 5176 | // RUN: %empty-directory(%t)
// RUN: %target-build-swift -parse-stdlib %s -module-name Reflection -o %t/a.out
// RUN: %S/timeout.sh 360 %target-run %t/a.out | %FileCheck %s
// REQUIRES: executable_test
// FIXME: timeout wrapper is necessary because the ASan test runs for hours
//
// DO NOT add more tests to this file. Add them to test/1_stdlib/Runtime.swift.
//
import Swift
// A more interesting struct type.
struct Complex<T> {
let real, imag: T
}
// CHECK-LABEL: Complex:
print("Complex:")
// CHECK-NEXT: Reflection.Complex<Swift.Double>
// CHECK-NEXT: real: 1.5
// CHECK-NEXT: imag: 0.75
dump(Complex<Double>(real: 1.5, imag: 0.75))
// CHECK-NEXT: Reflection.Complex<Swift.Double>
// CHECK-NEXT: real: -1.5
// CHECK-NEXT: imag: -0.75
dump(Complex<Double>(real: -1.5, imag: -0.75))
// CHECK-NEXT: Reflection.Complex<Swift.Int>
// CHECK-NEXT: real: 22
// CHECK-NEXT: imag: 44
dump(Complex<Int>(real: 22, imag: 44))
// CHECK-NEXT: Reflection.Complex<Swift.String>
// CHECK-NEXT: real: "is this the real life?"
// CHECK-NEXT: imag: "is it just fantasy?"
dump(Complex<String>(real: "is this the real life?",
imag: "is it just fantasy?"))
// Test destructuring of a pure Swift class hierarchy.
class Good {
let x: UInt = 11
let y: String = "222"
}
class Better : Good {
let z: Double = 333.5
}
class Best : Better {
let w: String = "4444"
}
// CHECK-LABEL: Root class:
// CHECK-NEXT: Reflection.Good #0
// CHECK-NEXT: x: 11
// CHECK-NEXT: y: "222"
print("Root class:")
dump(Good())
// CHECK-LABEL: Subclass:
// CHECK-NEXT: Reflection.Best #0
// CHECK-NEXT: super: Reflection.Better
// CHECK-NEXT: super: Reflection.Good
// CHECK-NEXT: x: 11
// CHECK-NEXT: y: "222"
// CHECK-NEXT: z: 333.5
// CHECK-NEXT: w: "4444"
print("Subclass:")
dump(Best())
// Test protocol types, which reflect as their dynamic types.
// CHECK-LABEL: Any int:
// CHECK-NEXT: 1
print("Any int:")
var any: Any = 1
dump(any)
// CHECK-LABEL: Any class:
// CHECK-NEXT: Reflection.Best #0
// CHECK-NEXT: super: Reflection.Better
// CHECK-NEXT: super: Reflection.Good
// CHECK-NEXT: x: 11
// CHECK-NEXT: y: "222"
// CHECK-NEXT: z: 333.5
// CHECK-NEXT: w: "4444"
print("Any class:")
any = Best()
dump(any)
// CHECK-LABEL: second verse
// CHECK-NEXT: Reflection.Best #0
print("second verse same as the first:")
dump(any)
// CHECK-LABEL: Any double:
// CHECK-NEXT: 2.5
print("Any double:")
any = 2.5
dump(any)
// CHECK-LABEL: Character:
// CHECK-NEXT: "a"
print("Character:")
dump(Character("a"))
protocol Fooable {}
extension Int : Fooable {}
extension Double : Fooable {}
// CHECK-LABEL: Fooable int:
// CHECK-NEXT: 1
print("Fooable int:")
var fooable: Fooable = 1
dump(fooable)
// CHECK-LABEL: Fooable double:
// CHECK-NEXT: 2.5
print("Fooable double:")
fooable = 2.5
dump(fooable)
protocol Barrable : class {}
extension Best: Barrable {}
// CHECK-LABEL: Barrable class:
// CHECK-NEXT: Reflection.Best #0
// CHECK-NEXT: super: Reflection.Better
// CHECK-NEXT: super: Reflection.Good
// CHECK-NEXT: x: 11
// CHECK-NEXT: y: "222"
// CHECK-NEXT: z: 333.5
// CHECK-NEXT: w: "4444"
print("Barrable class:")
var barrable: Barrable = Best()
dump(barrable)
// CHECK-LABEL: second verse
// CHECK-NEXT: Reflection.Best #0
// CHECK-NEXT: super: Reflection.Better
// CHECK-NEXT: super: Reflection.Good
// CHECK-NEXT: x: 11
// CHECK-NEXT: y: "222"
// CHECK-NEXT: z: 333.5
// CHECK-NEXT: w: "4444"
print("second verse same as the first:")
dump(barrable)
// CHECK-NEXT: Logical: true
switch true.customPlaygroundQuickLook {
case .bool(let x): print("Logical: \(x)")
default: print("wrong quicklook type")
}
let intArray = [1,2,3,4,5]
// CHECK-NEXT: 5 elements
// CHECK-NEXT: 1
// CHECK-NEXT: 2
// CHECK-NEXT: 3
// CHECK-NEXT: 4
// CHECK-NEXT: 5
dump(intArray)
var justSomeFunction = { (x:Int) -> Int in return x + 1 }
// CHECK-NEXT: (Function)
dump(justSomeFunction as Any)
// CHECK-NEXT: Swift.String
dump(String.self)
// CHECK-NEXT: ▿
// CHECK-NEXT: from: 1.0
// CHECK-NEXT: through: 12.15
// CHECK-NEXT: by: 3.14
dump(stride(from: 1.0, through: 12.15, by: 3.14))
// CHECK-NEXT: nil
var nilUnsafeMutablePointerString: UnsafeMutablePointer<String>?
dump(nilUnsafeMutablePointerString)
// CHECK-NEXT: 123456
// CHECK-NEXT: - pointerValue: 1193046
var randomUnsafeMutablePointerString = UnsafeMutablePointer<String>(
bitPattern: 0x123456)!
dump(randomUnsafeMutablePointerString)
// CHECK-NEXT: Hello panda
var sanePointerString = UnsafeMutablePointer<String>.allocate(capacity: 1)
sanePointerString.initialize(to: "Hello panda")
dump(sanePointerString.pointee)
sanePointerString.deinitialize(count: 1)
sanePointerString.deallocate()
// Don't crash on types with opaque metadata. rdar://problem/19791252
// CHECK-NEXT: (Opaque Value)
var rawPointer = unsafeBitCast(0 as Int, to: Builtin.RawPointer.self)
dump(rawPointer)
// CHECK-LABEL: and now our song is done
print("and now our song is done")
| apache-2.0 | 49b3b648212f13b1ea82f914510c0c13 | 25.397959 | 80 | 0.654813 | 3.130067 | false | false | false | false |
huonw/swift | test/SILOptimizer/inout_deshadow_integration.swift | 5 | 3080 | // RUN: %target-swift-frontend %s -emit-sil | %FileCheck %s
// This is an integration check for the inout-deshadow pass, verifying that it
// deshadows the inout variables in certain cases. These test should not be
// very specific (as they are running the parser, silgen and other sil
// diagnostic passes), they should just check the inout shadow got removed.
// CHECK-LABEL: sil hidden @{{.*}}exploded_trivial_type_dead
// CHECK-NOT: alloc_box
// CHECK-NOT: alloc_stack
// CHECK: }
func exploded_trivial_type_dead(a: inout Int) {
}
// CHECK-LABEL: sil hidden @{{.*}}exploded_trivial_type_returned
// CHECK-NOT: alloc_box
// CHECK-NOT: alloc_stack
// CHECK: }
func exploded_trivial_type_returned(a: inout Int) -> Int {
return a
}
// CHECK-LABEL: sil hidden @{{.*}}exploded_trivial_type_stored
// CHECK-NOT: alloc_box
// CHECK-NOT: alloc_stack
// CHECK: }
func exploded_trivial_type_stored(a: inout Int) {
a = 12
}
// CHECK-LABEL: sil hidden @{{.*}}exploded_trivial_type_stored_returned
// CHECK-NOT: alloc_box
// CHECK-NOT: alloc_stack
// CHECK: }
func exploded_trivial_type_stored_returned(a: inout Int) -> Int {
a = 12
return a
}
// CHECK-LABEL: sil hidden @{{.*}}exploded_nontrivial_type_dead
// CHECK-NOT: alloc_box
// CHECK-NOT: alloc_stack
// CHECK: }
func exploded_nontrivial_type_dead(a: inout String) {
}
// CHECK-LABEL: sil hidden @{{.*}}exploded_nontrivial_type_returned
// CHECK-NOT: alloc_box
// CHECK-NOT: alloc_stack
// CHECK: }
func exploded_nontrivial_type_returned(a: inout String) -> String {
return a
}
// CHECK-LABEL: sil hidden @{{.*}}exploded_nontrivial_type_stored
// CHECK-NOT: alloc_box
// CHECK-NOT: alloc_stack
// CHECK: }
func exploded_nontrivial_type_stored(a: inout String) {
a = "x"
}
// CHECK-LABEL: sil hidden @{{.*}}exploded_nontrivial_type_stored_returned
// CHECK-NOT: alloc_box
// CHECK-NOT: alloc_stack
// CHECK: }
func exploded_nontrivial_type_stored_returned(a: inout String) -> String {
a = "x"
return a
}
// Use an external function so inout deshadowing cannot see its body.
@_silgen_name("takesNoEscapeClosure")
func takesNoEscapeClosure(fn : () -> Int)
struct StructWithMutatingMethod {
var x = 42
// We should be able to deshadow this. The closure is capturing self, but it
// is itself noescape.
mutating func mutatingMethod() {
takesNoEscapeClosure { x = 42; return x }
}
mutating func testStandardLibraryOperators() {
if x != 4 || x != 0 {
testStandardLibraryOperators()
}
}
}
// CHECK-LABEL: sil hidden @$S26inout_deshadow_integration24StructWithMutatingMethodV08mutatingG0{{[_0-9a-zA-Z]*}}F : $@convention(method) (@inout StructWithMutatingMethod) -> () {
// CHECK-NOT: alloc_box
// CHECK-NOT: alloc_stack
// CHECK: }
// CHECK-LABEL: sil hidden @$S26inout_deshadow_integration24StructWithMutatingMethodV28testStandardLibraryOperators{{[_0-9a-zA-Z]*}}F : $@convention(method) (@inout StructWithMutatingMethod) -> () {
// CHECK-NOT: alloc_box $<τ_0_0> { var τ_0_0 } <StructWithMutatingMethod>
// CHECK-NOT: alloc_stack $StructWithMutatingMethod
// CHECK: }
| apache-2.0 | 4d23a53b77f1436fe626958950b083a9 | 28.314286 | 198 | 0.697856 | 3.497727 | false | false | false | false |
faimin/ZDOpenSourceDemo | ZDOpenSourceSwiftDemo/Pods/Toast-Swift/Toast/Toast.swift | 4 | 30625 | //
// Toast.swift
// Toast-Swift
//
// Copyright (c) 2015-2019 Charles Scalesse.
//
// 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 ObjectiveC
/**
Toast is a Swift extension that adds toast notifications to the `UIView` object class.
It is intended to be simple, lightweight, and easy to use. Most toast notifications
can be triggered with a single line of code.
The `makeToast` methods create a new view and then display it as toast.
The `showToast` methods display any view as toast.
*/
public extension UIView {
/**
Keys used for associated objects.
*/
private struct ToastKeys {
static var timer = "com.toast-swift.timer"
static var duration = "com.toast-swift.duration"
static var point = "com.toast-swift.point"
static var completion = "com.toast-swift.completion"
static var activeToasts = "com.toast-swift.activeToasts"
static var activityView = "com.toast-swift.activityView"
static var queue = "com.toast-swift.queue"
}
/**
Swift closures can't be directly associated with objects via the
Objective-C runtime, so the (ugly) solution is to wrap them in a
class that can be used with associated objects.
*/
private class ToastCompletionWrapper {
let completion: ((Bool) -> Void)?
init(_ completion: ((Bool) -> Void)?) {
self.completion = completion
}
}
private enum ToastError: Error {
case missingParameters
}
private var activeToasts: NSMutableArray {
get {
if let activeToasts = objc_getAssociatedObject(self, &ToastKeys.activeToasts) as? NSMutableArray {
return activeToasts
} else {
let activeToasts = NSMutableArray()
objc_setAssociatedObject(self, &ToastKeys.activeToasts, activeToasts, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
return activeToasts
}
}
}
private var queue: NSMutableArray {
get {
if let queue = objc_getAssociatedObject(self, &ToastKeys.queue) as? NSMutableArray {
return queue
} else {
let queue = NSMutableArray()
objc_setAssociatedObject(self, &ToastKeys.queue, queue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
return queue
}
}
}
// MARK: - Make Toast Methods
/**
Creates and presents a new toast view.
@param message The message to be displayed
@param duration The toast duration
@param position The toast's position
@param title The title
@param image The image
@param style The style. The shared style will be used when nil
@param completion The completion closure, executed after the toast view disappears.
didTap will be `true` if the toast view was dismissed from a tap.
*/
func makeToast(_ message: String?, duration: TimeInterval = ToastManager.shared.duration, position: ToastPosition = ToastManager.shared.position, title: String? = nil, image: UIImage? = nil, style: ToastStyle = ToastManager.shared.style, completion: ((_ didTap: Bool) -> Void)? = nil) {
do {
let toast = try toastViewForMessage(message, title: title, image: image, style: style)
showToast(toast, duration: duration, position: position, completion: completion)
} catch ToastError.missingParameters {
print("Error: message, title, and image are all nil")
} catch {}
}
/**
Creates a new toast view and presents it at a given center point.
@param message The message to be displayed
@param duration The toast duration
@param point The toast's center point
@param title The title
@param image The image
@param style The style. The shared style will be used when nil
@param completion The completion closure, executed after the toast view disappears.
didTap will be `true` if the toast view was dismissed from a tap.
*/
func makeToast(_ message: String?, duration: TimeInterval = ToastManager.shared.duration, point: CGPoint, title: String?, image: UIImage?, style: ToastStyle = ToastManager.shared.style, completion: ((_ didTap: Bool) -> Void)?) {
do {
let toast = try toastViewForMessage(message, title: title, image: image, style: style)
showToast(toast, duration: duration, point: point, completion: completion)
} catch ToastError.missingParameters {
print("Error: message, title, and image cannot all be nil")
} catch {}
}
// MARK: - Show Toast Methods
/**
Displays any view as toast at a provided position and duration. The completion closure
executes when the toast view completes. `didTap` will be `true` if the toast view was
dismissed from a tap.
@param toast The view to be displayed as toast
@param duration The notification duration
@param position The toast's position
@param completion The completion block, executed after the toast view disappears.
didTap will be `true` if the toast view was dismissed from a tap.
*/
func showToast(_ toast: UIView, duration: TimeInterval = ToastManager.shared.duration, position: ToastPosition = ToastManager.shared.position, completion: ((_ didTap: Bool) -> Void)? = nil) {
let point = position.centerPoint(forToast: toast, inSuperview: self)
showToast(toast, duration: duration, point: point, completion: completion)
}
/**
Displays any view as toast at a provided center point and duration. The completion closure
executes when the toast view completes. `didTap` will be `true` if the toast view was
dismissed from a tap.
@param toast The view to be displayed as toast
@param duration The notification duration
@param point The toast's center point
@param completion The completion block, executed after the toast view disappears.
didTap will be `true` if the toast view was dismissed from a tap.
*/
func showToast(_ toast: UIView, duration: TimeInterval = ToastManager.shared.duration, point: CGPoint, completion: ((_ didTap: Bool) -> Void)? = nil) {
objc_setAssociatedObject(toast, &ToastKeys.completion, ToastCompletionWrapper(completion), .OBJC_ASSOCIATION_RETAIN_NONATOMIC);
if ToastManager.shared.isQueueEnabled, activeToasts.count > 0 {
objc_setAssociatedObject(toast, &ToastKeys.duration, NSNumber(value: duration), .OBJC_ASSOCIATION_RETAIN_NONATOMIC);
objc_setAssociatedObject(toast, &ToastKeys.point, NSValue(cgPoint: point), .OBJC_ASSOCIATION_RETAIN_NONATOMIC);
queue.add(toast)
} else {
showToast(toast, duration: duration, point: point)
}
}
// MARK: - Hide Toast Methods
/**
Hides the active toast. If there are multiple toasts active in a view, this method
hides the oldest toast (the first of the toasts to have been presented).
@see `hideAllToasts()` to remove all active toasts from a view.
@warning This method has no effect on activity toasts. Use `hideToastActivity` to
hide activity toasts.
*/
func hideToast() {
guard let activeToast = activeToasts.firstObject as? UIView else { return }
hideToast(activeToast)
}
/**
Hides an active toast.
@param toast The active toast view to dismiss. Any toast that is currently being displayed
on the screen is considered active.
@warning this does not clear a toast view that is currently waiting in the queue.
*/
func hideToast(_ toast: UIView) {
guard activeToasts.contains(toast) else { return }
hideToast(toast, fromTap: false)
}
/**
Hides all toast views.
@param includeActivity If `true`, toast activity will also be hidden. Default is `false`.
@param clearQueue If `true`, removes all toast views from the queue. Default is `true`.
*/
func hideAllToasts(includeActivity: Bool = false, clearQueue: Bool = true) {
if clearQueue {
clearToastQueue()
}
activeToasts.compactMap { $0 as? UIView }
.forEach { hideToast($0) }
if includeActivity {
hideToastActivity()
}
}
/**
Removes all toast views from the queue. This has no effect on toast views that are
active. Use `hideAllToasts(clearQueue:)` to hide the active toasts views and clear
the queue.
*/
func clearToastQueue() {
queue.removeAllObjects()
}
// MARK: - Activity Methods
/**
Creates and displays a new toast activity indicator view at a specified position.
@warning Only one toast activity indicator view can be presented per superview. Subsequent
calls to `makeToastActivity(position:)` will be ignored until `hideToastActivity()` is called.
@warning `makeToastActivity(position:)` works independently of the `showToast` methods. Toast
activity views can be presented and dismissed while toast views are being displayed.
`makeToastActivity(position:)` has no effect on the queueing behavior of the `showToast` methods.
@param position The toast's position
*/
func makeToastActivity(_ position: ToastPosition) {
// sanity
guard objc_getAssociatedObject(self, &ToastKeys.activityView) as? UIView == nil else { return }
let toast = createToastActivityView()
let point = position.centerPoint(forToast: toast, inSuperview: self)
makeToastActivity(toast, point: point)
}
/**
Creates and displays a new toast activity indicator view at a specified position.
@warning Only one toast activity indicator view can be presented per superview. Subsequent
calls to `makeToastActivity(position:)` will be ignored until `hideToastActivity()` is called.
@warning `makeToastActivity(position:)` works independently of the `showToast` methods. Toast
activity views can be presented and dismissed while toast views are being displayed.
`makeToastActivity(position:)` has no effect on the queueing behavior of the `showToast` methods.
@param point The toast's center point
*/
func makeToastActivity(_ point: CGPoint) {
// sanity
guard objc_getAssociatedObject(self, &ToastKeys.activityView) as? UIView == nil else { return }
let toast = createToastActivityView()
makeToastActivity(toast, point: point)
}
/**
Dismisses the active toast activity indicator view.
*/
func hideToastActivity() {
if let toast = objc_getAssociatedObject(self, &ToastKeys.activityView) as? UIView {
UIView.animate(withDuration: ToastManager.shared.style.fadeDuration, delay: 0.0, options: [.curveEaseIn, .beginFromCurrentState], animations: {
toast.alpha = 0.0
}) { _ in
toast.removeFromSuperview()
objc_setAssociatedObject(self, &ToastKeys.activityView, nil, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
}
// MARK: - Private Activity Methods
private func makeToastActivity(_ toast: UIView, point: CGPoint) {
toast.alpha = 0.0
toast.center = point
objc_setAssociatedObject(self, &ToastKeys.activityView, toast, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
self.addSubview(toast)
UIView.animate(withDuration: ToastManager.shared.style.fadeDuration, delay: 0.0, options: .curveEaseOut, animations: {
toast.alpha = 1.0
})
}
private func createToastActivityView() -> UIView {
let style = ToastManager.shared.style
let activityView = UIView(frame: CGRect(x: 0.0, y: 0.0, width: style.activitySize.width, height: style.activitySize.height))
activityView.backgroundColor = style.activityBackgroundColor
activityView.autoresizingMask = [.flexibleLeftMargin, .flexibleRightMargin, .flexibleTopMargin, .flexibleBottomMargin]
activityView.layer.cornerRadius = style.cornerRadius
if style.displayShadow {
activityView.layer.shadowColor = style.shadowColor.cgColor
activityView.layer.shadowOpacity = style.shadowOpacity
activityView.layer.shadowRadius = style.shadowRadius
activityView.layer.shadowOffset = style.shadowOffset
}
let activityIndicatorView = UIActivityIndicatorView(style: .whiteLarge)
activityIndicatorView.center = CGPoint(x: activityView.bounds.size.width / 2.0, y: activityView.bounds.size.height / 2.0)
activityView.addSubview(activityIndicatorView)
activityIndicatorView.color = style.activityIndicatorColor
activityIndicatorView.startAnimating()
return activityView
}
// MARK: - Private Show/Hide Methods
private func showToast(_ toast: UIView, duration: TimeInterval, point: CGPoint) {
toast.center = point
toast.alpha = 0.0
if ToastManager.shared.isTapToDismissEnabled {
let recognizer = UITapGestureRecognizer(target: self, action: #selector(UIView.handleToastTapped(_:)))
toast.addGestureRecognizer(recognizer)
toast.isUserInteractionEnabled = true
toast.isExclusiveTouch = true
}
activeToasts.add(toast)
self.addSubview(toast)
UIView.animate(withDuration: ToastManager.shared.style.fadeDuration, delay: 0.0, options: [.curveEaseOut, .allowUserInteraction], animations: {
toast.alpha = 1.0
}) { _ in
let timer = Timer(timeInterval: duration, target: self, selector: #selector(UIView.toastTimerDidFinish(_:)), userInfo: toast, repeats: false)
RunLoop.main.add(timer, forMode: .common)
objc_setAssociatedObject(toast, &ToastKeys.timer, timer, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
private func hideToast(_ toast: UIView, fromTap: Bool) {
if let timer = objc_getAssociatedObject(toast, &ToastKeys.timer) as? Timer {
timer.invalidate()
}
UIView.animate(withDuration: ToastManager.shared.style.fadeDuration, delay: 0.0, options: [.curveEaseIn, .beginFromCurrentState], animations: {
toast.alpha = 0.0
}) { _ in
toast.removeFromSuperview()
self.activeToasts.remove(toast)
if let wrapper = objc_getAssociatedObject(toast, &ToastKeys.completion) as? ToastCompletionWrapper, let completion = wrapper.completion {
completion(fromTap)
}
if let nextToast = self.queue.firstObject as? UIView, let duration = objc_getAssociatedObject(nextToast, &ToastKeys.duration) as? NSNumber, let point = objc_getAssociatedObject(nextToast, &ToastKeys.point) as? NSValue {
self.queue.removeObject(at: 0)
self.showToast(nextToast, duration: duration.doubleValue, point: point.cgPointValue)
}
}
}
// MARK: - Events
@objc
private func handleToastTapped(_ recognizer: UITapGestureRecognizer) {
guard let toast = recognizer.view else { return }
hideToast(toast, fromTap: true)
}
@objc
private func toastTimerDidFinish(_ timer: Timer) {
guard let toast = timer.userInfo as? UIView else { return }
hideToast(toast)
}
// MARK: - Toast Construction
/**
Creates a new toast view with any combination of message, title, and image.
The look and feel is configured via the style. Unlike the `makeToast` methods,
this method does not present the toast view automatically. One of the `showToast`
methods must be used to present the resulting view.
@warning if message, title, and image are all nil, this method will throw
`ToastError.missingParameters`
@param message The message to be displayed
@param title The title
@param image The image
@param style The style. The shared style will be used when nil
@throws `ToastError.missingParameters` when message, title, and image are all nil
@return The newly created toast view
*/
func toastViewForMessage(_ message: String?, title: String?, image: UIImage?, style: ToastStyle) throws -> UIView {
// sanity
guard message != nil || title != nil || image != nil else {
throw ToastError.missingParameters
}
var messageLabel: UILabel?
var titleLabel: UILabel?
var imageView: UIImageView?
let wrapperView = UIView()
wrapperView.backgroundColor = style.backgroundColor
wrapperView.autoresizingMask = [.flexibleLeftMargin, .flexibleRightMargin, .flexibleTopMargin, .flexibleBottomMargin]
wrapperView.layer.cornerRadius = style.cornerRadius
if style.displayShadow {
wrapperView.layer.shadowColor = UIColor.black.cgColor
wrapperView.layer.shadowOpacity = style.shadowOpacity
wrapperView.layer.shadowRadius = style.shadowRadius
wrapperView.layer.shadowOffset = style.shadowOffset
}
if let image = image {
imageView = UIImageView(image: image)
imageView?.contentMode = .scaleAspectFit
imageView?.frame = CGRect(x: style.horizontalPadding, y: style.verticalPadding, width: style.imageSize.width, height: style.imageSize.height)
}
var imageRect = CGRect.zero
if let imageView = imageView {
imageRect.origin.x = style.horizontalPadding
imageRect.origin.y = style.verticalPadding
imageRect.size.width = imageView.bounds.size.width
imageRect.size.height = imageView.bounds.size.height
}
if let title = title {
titleLabel = UILabel()
titleLabel?.numberOfLines = style.titleNumberOfLines
titleLabel?.font = style.titleFont
titleLabel?.textAlignment = style.titleAlignment
titleLabel?.lineBreakMode = .byTruncatingTail
titleLabel?.textColor = style.titleColor
titleLabel?.backgroundColor = UIColor.clear
titleLabel?.text = title;
let maxTitleSize = CGSize(width: (self.bounds.size.width * style.maxWidthPercentage) - imageRect.size.width, height: self.bounds.size.height * style.maxHeightPercentage)
let titleSize = titleLabel?.sizeThatFits(maxTitleSize)
if let titleSize = titleSize {
titleLabel?.frame = CGRect(x: 0.0, y: 0.0, width: titleSize.width, height: titleSize.height)
}
}
if let message = message {
messageLabel = UILabel()
messageLabel?.text = message
messageLabel?.numberOfLines = style.messageNumberOfLines
messageLabel?.font = style.messageFont
messageLabel?.textAlignment = style.messageAlignment
messageLabel?.lineBreakMode = .byTruncatingTail;
messageLabel?.textColor = style.messageColor
messageLabel?.backgroundColor = UIColor.clear
let maxMessageSize = CGSize(width: (self.bounds.size.width * style.maxWidthPercentage) - imageRect.size.width, height: self.bounds.size.height * style.maxHeightPercentage)
let messageSize = messageLabel?.sizeThatFits(maxMessageSize)
if let messageSize = messageSize {
let actualWidth = min(messageSize.width, maxMessageSize.width)
let actualHeight = min(messageSize.height, maxMessageSize.height)
messageLabel?.frame = CGRect(x: 0.0, y: 0.0, width: actualWidth, height: actualHeight)
}
}
var titleRect = CGRect.zero
if let titleLabel = titleLabel {
titleRect.origin.x = imageRect.origin.x + imageRect.size.width + style.horizontalPadding
titleRect.origin.y = style.verticalPadding
titleRect.size.width = titleLabel.bounds.size.width
titleRect.size.height = titleLabel.bounds.size.height
}
var messageRect = CGRect.zero
if let messageLabel = messageLabel {
messageRect.origin.x = imageRect.origin.x + imageRect.size.width + style.horizontalPadding
messageRect.origin.y = titleRect.origin.y + titleRect.size.height + style.verticalPadding
messageRect.size.width = messageLabel.bounds.size.width
messageRect.size.height = messageLabel.bounds.size.height
}
let longerWidth = max(titleRect.size.width, messageRect.size.width)
let longerX = max(titleRect.origin.x, messageRect.origin.x)
let wrapperWidth = max((imageRect.size.width + (style.horizontalPadding * 2.0)), (longerX + longerWidth + style.horizontalPadding))
let wrapperHeight = max((messageRect.origin.y + messageRect.size.height + style.verticalPadding), (imageRect.size.height + (style.verticalPadding * 2.0)))
wrapperView.frame = CGRect(x: 0.0, y: 0.0, width: wrapperWidth, height: wrapperHeight)
if let titleLabel = titleLabel {
titleRect.size.width = longerWidth
titleLabel.frame = titleRect
wrapperView.addSubview(titleLabel)
}
if let messageLabel = messageLabel {
messageRect.size.width = longerWidth
messageLabel.frame = messageRect
wrapperView.addSubview(messageLabel)
}
if let imageView = imageView {
wrapperView.addSubview(imageView)
}
return wrapperView
}
}
// MARK: - Toast Style
/**
`ToastStyle` instances define the look and feel for toast views created via the
`makeToast` methods as well for toast views created directly with
`toastViewForMessage(message:title:image:style:)`.
@warning `ToastStyle` offers relatively simple styling options for the default
toast view. If you require a toast view with more complex UI, it probably makes more
sense to create your own custom UIView subclass and present it with the `showToast`
methods.
*/
public struct ToastStyle {
public init() {}
/**
The background color. Default is `.black` at 80% opacity.
*/
public var backgroundColor: UIColor = UIColor.black.withAlphaComponent(0.8)
/**
The title color. Default is `UIColor.whiteColor()`.
*/
public var titleColor: UIColor = .white
/**
The message color. Default is `.white`.
*/
public var messageColor: UIColor = .white
/**
A percentage value from 0.0 to 1.0, representing the maximum width of the toast
view relative to it's superview. Default is 0.8 (80% of the superview's width).
*/
public var maxWidthPercentage: CGFloat = 0.8 {
didSet {
maxWidthPercentage = max(min(maxWidthPercentage, 1.0), 0.0)
}
}
/**
A percentage value from 0.0 to 1.0, representing the maximum height of the toast
view relative to it's superview. Default is 0.8 (80% of the superview's height).
*/
public var maxHeightPercentage: CGFloat = 0.8 {
didSet {
maxHeightPercentage = max(min(maxHeightPercentage, 1.0), 0.0)
}
}
/**
The spacing from the horizontal edge of the toast view to the content. When an image
is present, this is also used as the padding between the image and the text.
Default is 10.0.
*/
public var horizontalPadding: CGFloat = 10.0
/**
The spacing from the vertical edge of the toast view to the content. When a title
is present, this is also used as the padding between the title and the message.
Default is 10.0. On iOS11+, this value is added added to the `safeAreaInset.top`
and `safeAreaInsets.bottom`.
*/
public var verticalPadding: CGFloat = 10.0
/**
The corner radius. Default is 10.0.
*/
public var cornerRadius: CGFloat = 10.0;
/**
The title font. Default is `.boldSystemFont(16.0)`.
*/
public var titleFont: UIFont = .boldSystemFont(ofSize: 16.0)
/**
The message font. Default is `.systemFont(ofSize: 16.0)`.
*/
public var messageFont: UIFont = .systemFont(ofSize: 16.0)
/**
The title text alignment. Default is `NSTextAlignment.Left`.
*/
public var titleAlignment: NSTextAlignment = .left
/**
The message text alignment. Default is `NSTextAlignment.Left`.
*/
public var messageAlignment: NSTextAlignment = .left
/**
The maximum number of lines for the title. The default is 0 (no limit).
*/
public var titleNumberOfLines = 0
/**
The maximum number of lines for the message. The default is 0 (no limit).
*/
public var messageNumberOfLines = 0
/**
Enable or disable a shadow on the toast view. Default is `false`.
*/
public var displayShadow = false
/**
The shadow color. Default is `.black`.
*/
public var shadowColor: UIColor = .black
/**
A value from 0.0 to 1.0, representing the opacity of the shadow.
Default is 0.8 (80% opacity).
*/
public var shadowOpacity: Float = 0.8 {
didSet {
shadowOpacity = max(min(shadowOpacity, 1.0), 0.0)
}
}
/**
The shadow radius. Default is 6.0.
*/
public var shadowRadius: CGFloat = 6.0
/**
The shadow offset. The default is 4 x 4.
*/
public var shadowOffset = CGSize(width: 4.0, height: 4.0)
/**
The image size. The default is 80 x 80.
*/
public var imageSize = CGSize(width: 80.0, height: 80.0)
/**
The size of the toast activity view when `makeToastActivity(position:)` is called.
Default is 100 x 100.
*/
public var activitySize = CGSize(width: 100.0, height: 100.0)
/**
The fade in/out animation duration. Default is 0.2.
*/
public var fadeDuration: TimeInterval = 0.2
/**
Activity indicator color. Default is `.white`.
*/
public var activityIndicatorColor: UIColor = .white
/**
Activity background color. Default is `.black` at 80% opacity.
*/
public var activityBackgroundColor: UIColor = UIColor.black.withAlphaComponent(0.8)
}
// MARK: - Toast Manager
/**
`ToastManager` provides general configuration options for all toast
notifications. Backed by a singleton instance.
*/
public class ToastManager {
/**
The `ToastManager` singleton instance.
*/
public static let shared = ToastManager()
/**
The shared style. Used whenever toastViewForMessage(message:title:image:style:) is called
with with a nil style.
*/
public var style = ToastStyle()
/**
Enables or disables tap to dismiss on toast views. Default is `true`.
*/
public var isTapToDismissEnabled = true
/**
Enables or disables queueing behavior for toast views. When `true`,
toast views will appear one after the other. When `false`, multiple toast
views will appear at the same time (potentially overlapping depending
on their positions). This has no effect on the toast activity view,
which operates independently of normal toast views. Default is `false`.
*/
public var isQueueEnabled = false
/**
The default duration. Used for the `makeToast` and
`showToast` methods that don't require an explicit duration.
Default is 3.0.
*/
public var duration: TimeInterval = 3.0
/**
Sets the default position. Used for the `makeToast` and
`showToast` methods that don't require an explicit position.
Default is `ToastPosition.Bottom`.
*/
public var position: ToastPosition = .bottom
}
// MARK: - ToastPosition
public enum ToastPosition {
case top
case center
case bottom
fileprivate func centerPoint(forToast toast: UIView, inSuperview superview: UIView) -> CGPoint {
let topPadding: CGFloat = ToastManager.shared.style.verticalPadding + superview.csSafeAreaInsets.top
let bottomPadding: CGFloat = ToastManager.shared.style.verticalPadding + superview.csSafeAreaInsets.bottom
switch self {
case .top:
return CGPoint(x: superview.bounds.size.width / 2.0, y: (toast.frame.size.height / 2.0) + topPadding)
case .center:
return CGPoint(x: superview.bounds.size.width / 2.0, y: superview.bounds.size.height / 2.0)
case .bottom:
return CGPoint(x: superview.bounds.size.width / 2.0, y: (superview.bounds.size.height - (toast.frame.size.height / 2.0)) - bottomPadding)
}
}
}
// MARK: - Private UIView Extensions
private extension UIView {
var csSafeAreaInsets: UIEdgeInsets {
if #available(iOS 11.0, *) {
return self.safeAreaInsets
} else {
return .zero
}
}
}
| mit | 0fd22877628230aa73bb22ca5892a6f4 | 38.162404 | 290 | 0.64849 | 4.914153 | false | false | false | false |
travismmorgan/TMPasscodeLock | TMPasscodeLock/TMPasscodeLockController.swift | 1 | 4076 | //
// TMPasscodeLockController.swift
// TMPasscodeLock
//
// Created by Travis Morgan on 1/16/17.
// Copyright © 2017 Travis Morgan. All rights reserved.
//
import UIKit
public enum TMPasscodeLockState {
case enter
case set
case change
case remove
}
public enum TMPasscodeLockStyle {
case basic
}
public protocol TMPasscodeLockControllerDelegate: class {
func passcodeLockController(passcodeLockController: TMPasscodeLockController, didFinishFor state: TMPasscodeLockState)
func passcodeLockControllerDidCancel(passcodeLockController: TMPasscodeLockController)
}
public class TMPasscodeLockController: NSObject, TMPasscodeLockViewControllerDelegate {
public weak var delegate: TMPasscodeLockControllerDelegate?
public var style: TMPasscodeLockStyle = .basic
public var state: TMPasscodeLockState = .set
public var isPresented: Bool {
get {
return rootViewController != nil
}
}
fileprivate var passcodeLockViewController: TMPasscodeLockViewController?
fileprivate var mainWindow: UIWindow?
fileprivate var rootViewController: UIViewController?
public convenience init(style: TMPasscodeLockStyle, state: TMPasscodeLockState) {
self.init()
self.style = style
self.state = state
}
public func presentIn(window: UIWindow, animated: Bool) {
guard !isPresented else { return }
if (state != .set) && !TMPasscodeLock.isPasscodeSet {
print("Passcode not set")
return
}
mainWindow = window
rootViewController = mainWindow?.rootViewController
passcodeLockViewController = TMPasscodeLockViewController(style: style, state: state)
passcodeLockViewController?.delegate = self
if animated {
UIView.transition(with: window, duration: CATransaction.animationDuration(), options: .transitionCrossDissolve, animations: {
self.mainWindow?.rootViewController = UINavigationController(rootViewController: self.passcodeLockViewController!)
}, completion: nil)
} else {
self.mainWindow?.rootViewController = UINavigationController(rootViewController: passcodeLockViewController!)
}
}
public func presentIn(viewController: UIViewController, animated: Bool) {
passcodeLockViewController = TMPasscodeLockViewController(style: style, state: state)
passcodeLockViewController?.delegate = self
viewController.present(UINavigationController(rootViewController: passcodeLockViewController!), animated: animated, completion: nil)
}
public func dismiss(animated: Bool) {
if mainWindow != nil {
if animated {
UIView.transition(from: self.mainWindow!.rootViewController!.view, to: self.rootViewController!.view, duration: CATransaction.animationDuration(), options: .transitionCrossDissolve, completion: { (finished) in
if finished {
self.mainWindow?.rootViewController = self.rootViewController
self.mainWindow = nil
self.rootViewController = nil
self.passcodeLockViewController = nil
}
})
} else {
mainWindow?.rootViewController = rootViewController
mainWindow = nil
rootViewController = nil
passcodeLockViewController = nil
}
} else {
passcodeLockViewController?.dismiss(animated: animated, completion: nil)
}
}
func passcodeLockViewControllerDidCancel() {
delegate?.passcodeLockControllerDidCancel(passcodeLockController: self)
dismiss(animated: true)
}
func passcodeLockViewControllerDidFinish(state: TMPasscodeLockState) {
delegate?.passcodeLockController(passcodeLockController: self, didFinishFor: state)
dismiss(animated: true)
}
}
| mit | af1f04a89c44d82d531af04bfd976088 | 36.045455 | 225 | 0.669693 | 5.715288 | false | false | false | false |
crossroadlabs/Boilerplate | Sources/Boilerplate/Optional.swift | 2 | 1265 | //===--- Optional.swift ------------------------------------------------------===//
//Copyright (c) 2016 Daniel Leping (dileping)
//
//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
public extension Optional {
func getOr(else el:@autoclosure () throws -> Wrapped) rethrows -> Wrapped {
return try self ?? el()
}
func getOr(else el:() throws -> Wrapped) rethrows -> Wrapped {
return try self ?? el()
}
func or(else el:@autoclosure () throws -> Wrapped?) rethrows -> Wrapped? {
return try self ?? el()
}
func or(else el:() throws -> Wrapped?) rethrows -> Wrapped? {
return try self ?? el()
}
}
| apache-2.0 | 5ca74af3ffb8cb615c60fcab56960d8d | 35.142857 | 83 | 0.592885 | 4.755639 | false | false | false | false |
hyperconnect/Bond | Bond/Bond+UITextField.swift | 1 | 4200 | //
// Bond+UITextField.swift
// Bond
//
// The MIT License (MIT)
//
// Copyright (c) 2015 Srdan Rasic (@srdanrasic)
//
// 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
@objc class TextFieldDynamicHelper
{
weak var control: UITextField?
var listener: (String -> Void)?
init(control: UITextField) {
self.control = control
control.addTarget(self, action: Selector("editingChanged:"), forControlEvents: .EditingChanged)
}
func editingChanged(control: UITextField) {
self.listener?(control.text ?? "")
}
deinit {
control?.removeTarget(self, action: nil, forControlEvents: .EditingChanged)
}
}
class TextFieldDynamic<T>: InternalDynamic<String>
{
let helper: TextFieldDynamicHelper
init(control: UITextField) {
self.helper = TextFieldDynamicHelper(control: control)
super.init(control.text ?? "")
self.helper.listener = { [unowned self] in
self.updatingFromSelf = true
self.value = $0
self.updatingFromSelf = false
}
}
}
private var textDynamicHandleUITextField: UInt8 = 0;
extension UITextField /*: Dynamical, Bondable */ {
public var dynText: Dynamic<String> {
if let d: AnyObject = objc_getAssociatedObject(self, &textDynamicHandleUITextField) {
return (d as? Dynamic<String>)!
} else {
let d = TextFieldDynamic<String>(control: self)
let bond = Bond<String>() { [weak self, weak d] v in
if let s = self, d = d where !d.updatingFromSelf {
s.text = v
}
}
d.bindTo(bond, fire: false, strongly: false)
d.retain(bond)
objc_setAssociatedObject(self, &textDynamicHandleUITextField, d, objc_AssociationPolicy(OBJC_ASSOCIATION_RETAIN_NONATOMIC))
return d
}
}
public var designatedDynamic: Dynamic<String> {
return self.dynText
}
public var designatedBond: Bond<String> {
return self.dynText.valueBond
}
}
public func ->> (left: UITextField, right: Bond<String>) {
left.designatedDynamic ->> right
}
public func ->> <U: Bondable where U.BondType == String>(left: UITextField, right: U) {
left.designatedDynamic ->> right.designatedBond
}
public func ->> (left: UITextField, right: UITextField) {
left.designatedDynamic ->> right.designatedBond
}
public func ->> (left: UITextField, right: UILabel) {
left.designatedDynamic ->> right.designatedBond
}
public func ->> (left: UITextField, right: UITextView) {
left.designatedDynamic ->> right.designatedBond
}
public func ->> <T: Dynamical where T.DynamicType == String>(left: T, right: UITextField) {
left.designatedDynamic ->> right.designatedBond
}
public func ->> (left: Dynamic<String>, right: UITextField) {
left ->> right.designatedBond
}
public func <->> (left: UITextField, right: UITextField) {
left.designatedDynamic <->> right.designatedDynamic
}
public func <->> (left: Dynamic<String>, right: UITextField) {
left <->> right.designatedDynamic
}
public func <->> (left: UITextField, right: Dynamic<String>) {
left.designatedDynamic <->> right
}
public func <->> (left: UITextField, right: UITextView) {
left.designatedDynamic <->> right.designatedDynamic
}
| mit | b79a2596dc206def4fbd3ee3d1414768 | 29.882353 | 129 | 0.703095 | 4.195804 | false | false | false | false |
ABTSoftware/SciChartiOSTutorial | v2.x/Sandbox/SciChart_Boilerplate_Swift_customTooltipDataView/SciChart_Boilerplate_Swift/ChartView.swift | 1 | 2943 | //
// SCSLineChartView.swift
// SciChartSwiftDemo
//
// Created by Mykola Hrybeniuk on 5/30/16.
// Copyright © 2016 SciChart Ltd. All rights reserved.
//
import UIKit
import SciChart
class CustomSeriesDataView : SCIXySeriesDataView {
static override func createInstance() -> SCITooltipDataView! {
let view : CustomSeriesDataView = (Bundle.main.loadNibNamed("CustomSeriesDataView", owner: nil, options: nil)![0] as? CustomSeriesDataView)!
view.translatesAutoresizingMaskIntoConstraints = false
return view
}
override func setData(_ data: SCISeriesInfo!) {
let series : SCIRenderableSeriesProtocol = data.renderableSeries()
let xAxis = series.xAxis
let yAxis = series.yAxis
self.nameLabel.text = data.seriesName()
var xFormattedValue : String? = data.fortmatterdValue(fromSeriesInfo: data.xValue(), for: series.dataSeries.xType())
if (xFormattedValue == nil) {
xFormattedValue = xAxis?.formatCursorText(data.xValue())
}
var yFormattedValue : String? = data.fortmatterdValue(fromSeriesInfo: data.yValue(), for: series.dataSeries.yType())
if (yFormattedValue == nil) {
yFormattedValue = yAxis?.formatCursorText(data.yValue())
}
self.dataLabel.text = String(format: "Custom-X: %@ Custom-Y %@", xFormattedValue!, yFormattedValue!)
self.invalidateIntrinsicContentSize()
}
}
class CustomSeriesInfo : SCIXySeriesInfo {
override func createDataSeriesView() -> SCITooltipDataView! {
let view : CustomSeriesDataView = CustomSeriesDataView.createInstance() as! CustomSeriesDataView
view.setData(self)
return view;
}
}
class CustomLineSeries : SCIFastLineRenderableSeries {
override func toSeriesInfo(withHitTest info: SCIHitTestInfo) -> SCISeriesInfo! {
return CustomSeriesInfo(series: self, hitTest: info)
}
}
class ChartView: SCIChartSurface {
var data1 : SCIXyDataSeries! = nil
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
let xAxis = SCINumericAxis()
xAxis.axisId = "XAxis"
let yAxis = SCINumericAxis()
yAxis.axisId = "YAxis"
self.xAxes.add(xAxis)
self.yAxes.add(yAxis)
self.chartModifiers.add(SCIRolloverModifier())
addSeries()
}
private func addSeries() {
data1 = SCIXyDataSeries(xType: .float, yType: .float)
for i in 0...10 {
data1.appendX(SCIGeneric(i), y: SCIGeneric((i % 3) * 2))
}
let renderSeries1 = CustomLineSeries()
renderSeries1.dataSeries = data1
renderSeries1.xAxisId = "XAxis"
renderSeries1.yAxisId = "YAxis"
self.renderableSeries.add(renderSeries1)
self.invalidateElement()
}
}
| mit | 27fa88ce9f52dadf8494261ff90e9dd0 | 30.634409 | 148 | 0.637322 | 4.397608 | false | false | false | false |
fespinoza/linked-ideas-osx | LinkedIdeas-Shared/Sources/ViewModels/DrawableConcept.swift | 1 | 1271 | //
// File.swift
// LinkedIdeas
//
// Created by Felipe Espinoza Castillo on 16/02/2017.
// Copyright © 2017 Felipe Espinoza Dev. All rights reserved.
//
#if os(iOS)
import UIKit
public typealias BezierPath = UIBezierPath
extension CGRect {
func fill() {
BezierPath(rect: self).fill()
}
}
#else
import AppKit
public typealias BezierPath = NSBezierPath
#endif
public struct DrawableConcept: DrawableElement {
let concept: Concept
public init(concept: Concept) {
self.concept = concept
}
public var drawingBounds: CGRect { return concept.area }
public func draw() {
drawBackground()
concept.draw()
drawSelectedRing()
drawForDebug()
}
func drawBackground() {
Color.white.set()
drawingBounds.fill()
}
func drawSelectedRing() {
guard concept.isSelected else {
return
}
Color(red: 146/255, green: 178/255, blue: 254/255, alpha: 1).set()
let bezierPath = BezierPath(rect: drawingBounds)
bezierPath.lineWidth = 1
bezierPath.stroke()
concept.leftHandler?.draw()
concept.rightHandler?.draw()
}
public func drawForDebug() {
if isDebugging() {
drawDebugHelpers()
drawCenteredDotAtPoint(concept.centerPoint, color: Color.red)
}
}
}
| mit | 4ee29dab53150c002fed349855022914 | 18.84375 | 70 | 0.667717 | 3.944099 | false | false | false | false |
PureSwift/Bluetooth | Sources/BluetoothGATT/GATTAlertCategory.swift | 1 | 2000 | //
// GATTAlertCategory.swift
// Bluetooth
//
// Created by Carlos Duclos on 6/13/18.
// Copyright © 2018 PureSwift. All rights reserved.
//
import Foundation
/**
Categories of alerts/messages.
The value of the characteristic is an unsigned 8 bit integer that has a fixed point exponent of 0.
The Alert Category ID characteristic defines the predefined categories of messages as an enumeration.
- Example:
The value 0x01 is interpreted as “Email”
- SeeAlso: [New Alert](https://www.bluetooth.com/specifications/gatt/viewer?attributeXmlFile=org.bluetooth.characteristic.new_alert.xml)
*/
@frozen
public enum GATTAlertCategory: UInt8, GATTCharacteristic {
internal static let length = 1
public static var uuid: BluetoothUUID { return .alertCategoryId }
/// Simple Alert: General text alert or non-text alert
case simpleAlert = 0
/// Email: Alert when Email messages arrives
case email
/// News: News feeds such as RSS, Atom
case news
/// Call: Incoming call
case call
/// Missed call: Missed Call
case missedCall
/// SMS/MMS: SMS/MMS message arrives
case sms
/// Voice mail: Voice mail
case voiceMail
/// Schedule: Alert occurred on calendar, planner
case schedule
/// High Prioritized Alert: Alert that should be handled as high priority
case highPrioritizedAlert
/// Instant Message: Alert for incoming instant messages
case instantMessage
public init?(data: Data) {
guard data.count == type(of: self).length
else { return nil }
self.init(rawValue: data[0])
}
public var data: Data {
return Data([rawValue])
}
}
extension GATTAlertCategory: Equatable {
public static func == (lhs: GATTAlertCategory,
rhs: GATTAlertCategory) -> Bool {
return lhs.rawValue == rhs.rawValue
}
}
| mit | 4abe7313399b88f71f50bb25a0d1a165 | 23.329268 | 137 | 0.642105 | 4.60739 | false | false | false | false |
PureSwift/Bluetooth | Sources/Bluetooth/ClassOfDevice.swift | 1 | 17545 | //
// ClassOfDevice.swift
// Bluetooth
//
// Created by Alsey Coleman Miller on 6/1/18.
// Copyright © 2018 PureSwift. All rights reserved.
//
import Foundation
public struct ClassOfDevice: Equatable {
internal static let length = 3
public var formatType: FormatType
public var majorServiceClass: BitMaskOptionSet<MajorServiceClass>
public var majorDeviceClass: MajorDeviceClass
public init(formatType: FormatType,
majorServiceClass: BitMaskOptionSet<MajorServiceClass>,
majorDeviceClass: MajorDeviceClass) {
self.formatType = formatType
self.majorServiceClass = majorServiceClass
self.majorDeviceClass = majorDeviceClass
}
public init?(data: Data) {
guard data.count == type(of: self).length
else { return nil }
guard let formatType = FormatType(rawValue: (data[0] << 6) >> 6)
else { return nil }
self.formatType = formatType
let majorServiceValue = UInt16(littleEndian: UInt16(bytes: (data[1], data[2]))) >> 5
self.majorServiceClass = BitMaskOptionSet<MajorServiceClass>(rawValue: majorServiceValue)
let majorDeviceClassType = MajorDeviceClassType(rawValue: (data[1] << 3) >> 3) ?? MajorDeviceClassType.miscellaneous
switch majorDeviceClassType {
case .miscellaneous:
self.majorDeviceClass = .miscellaneous
case .computer:
self.majorDeviceClass = .computer(Computer(rawValue: data[0] >> 2) ?? .uncategorized)
case .phone:
self.majorDeviceClass = .phone(Phone(rawValue: data[0] >> 2) ?? .uncategorized)
case .lanNetwork:
self.majorDeviceClass = .lanNetwork(NetworkAccessPoint(rawValue: data[0] >> 2) ?? .fullyAvailable)
case .audioVideo:
self.majorDeviceClass = .audioVideo(AudioVideo(rawValue: data[0] >> 2) ?? .uncategorized)
case .peripheral:
self.majorDeviceClass = .peripheral(PeripheralKeyboardPointing(rawValue: data[0] >> 6) ?? .notKeyboard,
PeripheralDevice(rawValue: (data[0] << 2) >> 4) ?? .uncategorized)
case .imaging:
self.majorDeviceClass = .imaging(BitMaskOptionSet<Imaging>(rawValue: data[0] >> 4))
case .wearable:
self.majorDeviceClass = .wearable(Wearable(rawValue: data[0] >> 2) ?? .uncategorized)
case .toy:
self.majorDeviceClass = .toy(Toy(rawValue: data[0] >> 2) ?? .uncategorized)
case .health:
self.majorDeviceClass = .health(Health(rawValue: data[0] >> 2) ?? .uncategorized)
case .uncategorized:
self.majorDeviceClass = .uncategorized
}
}
public var data: Data {
// combine Format Type with Major Device Class
let firstByte = formatType.rawValue | (majorDeviceClass.minorClassValue << 2)
// get first 3 bits of the Mejor Service Class
let majorServiceClass3Bits = (majorServiceClass.rawValue.bytes.0 << 5) /// e.g. 11100000
// combine part of the Major Device Class of part with the Major Service Class
let secondByte = majorDeviceClass.type.rawValue | majorServiceClass3Bits
let thirdByte = (majorServiceClass.rawValue.bytes.1 << 5) | (majorServiceClass.rawValue.bytes.0 >> 3)
return Data([firstByte, secondByte, thirdByte])
}
}
extension ClassOfDevice {
public struct FormatType: RawRepresentable, Equatable, Hashable {
public static let min = FormatType(0b00)
public static let max = FormatType(0b11)
public let rawValue: UInt8
public init?(rawValue: UInt8) {
guard rawValue <= type(of: self).max.rawValue, rawValue >= type(of: self).min.rawValue
else { return nil }
self.rawValue = rawValue
}
private init(_ unsafe: UInt8) {
self.rawValue = unsafe
}
}
}
public extension ClassOfDevice {
enum MajorServiceClass: UInt16, BitMaskOption {
/// Limited Discoverable Mode [Ref #1]
case limitedDiscoverable = 0b01
/// Positioning (Location identification)
case positioning = 0b1000
/// Networking (LAN, Ad hoc, ...)
case networking = 0b10000
/// Rendering (Printing, Speakers, ...)
case rendering = 0b100000
/// Capturing (Scanner, Microphone, ...)
case capturing = 0b1000000
/// Object Transfer (v-Inbox, v-Folder, ...)
case objectTransfer = 0b10000000
/// Audio (Speaker, Microphone, Headset service, ...)
case audio = 0b1_00000000
/// Telephony (Cordless telephony, Modem, Headset service, ...)
case telephony = 0b10_00000000
/// Information (WEB-server, WAP-server, ...)
case information = 0b100_00000000
public static let allCases: [MajorServiceClass] = [
.limitedDiscoverable,
.positioning,
.networking,
.rendering,
.capturing,
.objectTransfer,
.audio,
.telephony,
.information
]
}
}
public extension ClassOfDevice {
enum MajorDeviceClass: Equatable {
/// Miscellaneous
case miscellaneous
/// Computer (desktop, notebook, PDA, organizer, ... )
case computer(Computer)
/// Phone (cellular, cordless, pay phone, modem, ...)
case phone(Phone)
/// Networking (LAN, Ad hoc, ...)
case lanNetwork(NetworkAccessPoint)
/// Audio/Video (headset, speaker, stereo, video display, VCR, ...
case audioVideo(AudioVideo)
/// Peripheral (mouse, joystick, keyboard, ... )
case peripheral(PeripheralKeyboardPointing, PeripheralDevice)
/// Imaging (printer, scanner, camera, display, ...)
case imaging(BitMaskOptionSet<Imaging>)
/// Wearable
case wearable(Wearable)
/// Toy
case toy(Toy)
/// Health
case health(Health)
/// Uncategorized: device code not specified
case uncategorized
var type: MajorDeviceClassType {
switch self {
case .miscellaneous: return .miscellaneous
case .computer: return .computer
case .phone: return .phone
case .lanNetwork: return .lanNetwork
case .audioVideo: return .audioVideo
case .peripheral: return .peripheral
case .imaging: return .imaging
case .wearable: return .wearable
case .toy: return .toy
case .health: return .health
case .uncategorized: return .uncategorized
}
}
var minorClassValue: UInt8 {
switch self {
case .miscellaneous:
return 0
case .computer(let computer):
return computer.rawValue
case .phone(let phone):
return phone.rawValue
case .lanNetwork(let network):
return network.rawValue
case .audioVideo(let audioVideo):
return audioVideo.rawValue
case .peripheral(let keyboardPointing, let device):
return (keyboardPointing.rawValue << 4) | device.rawValue
case .imaging(let imaging):
return imaging.rawValue
case .wearable(let wearable):
return wearable.rawValue
case .toy(let toy):
return toy.rawValue
case .health(let health):
return health.rawValue
case .uncategorized:
return MajorDeviceClassType.uncategorized.rawValue
}
}
}
enum MajorDeviceClassType: UInt8 {
/// Miscellaneous
case miscellaneous = 0b00
/// Computer (desktop, notebook, PDA, organizer, ... )
case computer = 0b1
/// Phone (cellular, cordless, pay phone, modem, ...)
case phone = 0b10
/// LAN /Network Access point
case lanNetwork = 0b11
/// Audio/Video (headset, speaker, stereo, video display, VCR, ...
case audioVideo = 0b100
/// Peripheral (mouse, joystick, keyboard, ... )
case peripheral = 0b101
/// Imaging (printer, scanner, camera, display, ...)
case imaging = 0b110
/// Wearable
case wearable = 0b111
/// Toy
case toy = 0b1000
/// Health
case health = 0b1001
/// Uncategorized: device code not specified
case uncategorized = 0b11111
}
}
public extension ClassOfDevice {
typealias Computer = MinorDeviceClass.Computer
typealias Phone = MinorDeviceClass.Phone
typealias NetworkAccessPoint = MinorDeviceClass.NetworkAccessPoint
typealias AudioVideo = MinorDeviceClass.AudioVideo
typealias PeripheralKeyboardPointing = MinorDeviceClass.PeripheralKeyboardPointing
typealias PeripheralDevice = MinorDeviceClass.PeripheralDevice
typealias Imaging = MinorDeviceClass.Imaging
typealias Wearable = MinorDeviceClass.Wearable
typealias Toy = MinorDeviceClass.Toy
typealias Health = MinorDeviceClass.Health
enum MinorDeviceClass {}
}
public extension ClassOfDevice.MinorDeviceClass {
enum Computer: UInt8 {
/// Uncategorized
case uncategorized = 0b00
/// Desktop workstation
case desktopWorkstation = 0b01
/// Server-class computer
case serverClassComputer = 0b10
/// Laptop
case laptop = 0b11
/// Handheld PC/PDA (clamshell)
case handHeld = 0b100
/// Palm-size PC/PDA
case palmSize = 0b101
/// Wearable computer (watch size)
case wearable = 0b110
// Tablet
case tablet = 0b111
}
}
public extension ClassOfDevice.MinorDeviceClass {
enum Phone: UInt8 {
/// Uncategorized, code for device not assigned
case uncategorized = 0b00
/// Cellular
case celullar = 0b01
/// Cordless
case cordless = 0b10
/// Smartphone
case smartphone = 0b11
/// Wired modem or voice gateway
case wiredModem = 0b100
/// Common ISDN access
case commonISDNAccess = 0b101
}
}
public extension ClassOfDevice.MinorDeviceClass {
enum NetworkAccessPoint: UInt8 {
/// Fully available
case fullyAvailable = 0b00
/// 1% to 17% utilized
case from1To17Used = 0b01
/// 17% to 33% utilized
case from17To33Used = 0b10
/// 33% to 50% utilized
case from33To50Used = 0b11
/// 50% to 67% utilized
case from50to67Used = 0b100
/// 67% to 83% utilized
case from67to83Used = 0b101
/// 83% to 99% utilized
case from83to99Used = 0b110
/// No service available
case noServiceAvailable = 0b111
}
}
public extension ClassOfDevice.MinorDeviceClass {
enum AudioVideo: UInt8 {
/// Uncategorized, code not assigned
case uncategorized = 0b00
/// Wearable Headset Device
case wearableHeadSet = 0b01
/// Hands-free Device
case handsFree = 0b10
/// Microphone
case microphone = 0b100
/// Loudspeaker
case loudspeaker = 0b101
/// Headphones
case headphones = 0b110
/// Portable Audio
case portableAudio = 0b111
/// Car audio
case carAudio = 0b1000
/// Set-top box
case setTopBox = 0b1001
/// HiFi Audio Device
case hifiAudio = 0b1010
/// VCR
case vcr = 0b1011
/// Video Camera
case videoCamera = 0b1100
/// Camcorder
case camcorder = 0b1101
/// Video Monitor
case videoMonitor = 0b1110
/// Video Display and Loudspeaker
case videoDisplayLoudspeaker = 0b1111
/// Video Conferencing
case videoConferencing = 0b10000
/// Gaming/Toy
case gamingToy = 0b10010
}
}
public extension ClassOfDevice.MinorDeviceClass {
enum PeripheralKeyboardPointing: UInt8 {
/// Not Keyboard / Not Pointing Device
case notKeyboard = 0b00
/// Keyboard
case keyboard = 0b01
/// Pointing device
case pointingDevice = 0b10
/// Combo keyboard/pointing device
case comboKeyboardPointingDevice = 0b11
}
enum PeripheralDevice: UInt8 {
/// Uncategorized device
case uncategorized = 0b00
/// Joystick
case joystick = 0b01
/// Gamepad
case gamepad = 0b10
/// Remote control
case remoteControl = 0b11
/// Sensing Device
case sensingDevice = 0b100
/// Digitizer Tablet
case digitizerTablet = 0b101
/// Card Reader (e.g. SIM Card Reader)
case cardReader = 0b110
/// Digital Pen
case digitalPen = 0b111
/// Handheld scanner for bar-codes, RFID, etc.
case handheldScannerBarCodes = 0b1000
/// Handheld gestural input device (e.g., "wand" form factor)
case handheldGesturalInput = 0b1001
}
}
public extension ClassOfDevice.MinorDeviceClass {
enum Imaging: UInt8, BitMaskOption {
/// Uncategorized
case uncategorized = 0b00
/// Display
case display = 0b01
/// Camera
case camera = 0b10
/// Scanner
case scanner = 0b100
/// Printer
case printer = 0b1000
public static let allCases: [ClassOfDevice.MinorDeviceClass.Imaging] = [
.uncategorized,
.display,
.camera,
.scanner,
.printer
]
}
}
public extension ClassOfDevice.MinorDeviceClass {
enum Wearable: UInt8 {
/// Uncategorized
case uncategorized = 0b00
/// Wristwatch
case wristwatch = 0b01
/// Pager
case pager = 0b10
/// Jacket
case jacket = 0b11
/// Helmet
case helmet = 0b100
/// Glasses
case glasses = 0b101
}
}
public extension ClassOfDevice.MinorDeviceClass {
enum Toy: UInt8 {
/// Uncategorized
case uncategorized = 0b00
/// Robot
case robot = 0b01
/// Vehicle
case vehicle = 0b10
/// Doll / Action figure
case actionFigure = 0b11
/// Controller
case controller = 0b100
/// Game
case game = 0b101
}
}
public extension ClassOfDevice.MinorDeviceClass {
enum Health: UInt8 {
/// Uncategorized
case uncategorized = 0b00
/// Blood Pressure Monitor
case bloodPressureMonitor = 0b01
/// Thermometer
case thermometer = 0b10
/// Weighing Scale
case weighingScale = 0b11
/// Glucose Meter
case glucoseMeter = 0b100
/// Pulse Oximeter
case pulseOximeter = 0b101
/// Heart/Pulse Rate Monitor
case heartRateMonitor = 0b110
/// Health Data Display
case healthDataDisplay = 0b111
/// Step Counter
case stepCounter = 0b1000
/// Body Composition Analyzer
case bodyCompositionAnalyzer = 0b1001
/// Peak Flow Monitor
case peakFlowMonitor = 0b1010
/// Medication Monitor
case medicationMonitor = 0b1011
/// Knee Prosthesis
case kneeProsthesis = 0b1100
/// Ankle Prosthesis
case ankleProsthesis = 0b1101
/// Generic Health Manager
case genericHealthManager = 0b1110
/// Personal Mobility Device
case personalMobilityDevice = 0b1111
}
}
| mit | 893ce9320dd8bc7a247a5c23c9c56312 | 25.990769 | 124 | 0.534941 | 4.943364 | false | false | false | false |
plivesey/SwiftGen | Pods/Stencil/Sources/Variable.swift | 6 | 4518 | import Foundation
typealias Number = Float
class FilterExpression : Resolvable {
let filters: [(FilterType, [Variable])]
let variable: Variable
init(token: String, parser: TokenParser) throws {
let bits = token.characters.split(separator: "|").map({ String($0).trim(character: " ") })
if bits.isEmpty {
filters = []
variable = Variable("")
throw TemplateSyntaxError("Variable tags must include at least 1 argument")
}
variable = Variable(bits[0])
let filterBits = bits[bits.indices.suffix(from: 1)]
do {
filters = try filterBits.map {
let (name, arguments) = parseFilterComponents(token: $0)
let filter = try parser.findFilter(name)
return (filter, arguments)
}
} catch {
filters = []
throw error
}
}
func resolve(_ context: Context) throws -> Any? {
let result = try variable.resolve(context)
return try filters.reduce(result) { x, y in
let arguments = try y.1.map { try $0.resolve(context) }
return try y.0.invoke(value: x, arguments: arguments)
}
}
}
/// A structure used to represent a template variable, and to resolve it in a given context.
public struct Variable : Equatable, Resolvable {
public let variable: String
/// Create a variable with a string representing the variable
public init(_ variable: String) {
self.variable = variable
}
fileprivate func lookup() -> [String] {
return variable.characters.split(separator: ".").map(String.init)
}
/// Resolve the variable in the given context
public func resolve(_ context: Context) throws -> Any? {
var current: Any? = context
if (variable.hasPrefix("'") && variable.hasSuffix("'")) || (variable.hasPrefix("\"") && variable.hasSuffix("\"")) {
// String literal
return variable[variable.characters.index(after: variable.startIndex) ..< variable.characters.index(before: variable.endIndex)]
}
if let number = Number(variable) {
// Number literal
return number
}
for bit in lookup() {
current = normalize(current)
if let context = current as? Context {
current = context[bit]
} else if let dictionary = current as? [String: Any] {
current = dictionary[bit]
} else if let array = current as? [Any] {
if let index = Int(bit) {
if index >= 0 && index < array.count {
current = array[index]
} else {
current = nil
}
} else if bit == "first" {
current = array.first
} else if bit == "last" {
current = array.last
} else if bit == "count" {
current = array.count
}
} else if let object = current as? NSObject { // NSKeyValueCoding
#if os(Linux)
return nil
#else
current = object.value(forKey: bit)
#endif
} else if let value = current {
let mirror = Mirror(reflecting: value)
current = mirror.descendant(bit)
if current == nil {
return nil
}
} else {
return nil
}
}
if let resolvable = current as? Resolvable {
current = try resolvable.resolve(context)
} else if let node = current as? NodeType {
current = try node.render(context)
}
return normalize(current)
}
}
public func ==(lhs: Variable, rhs: Variable) -> Bool {
return lhs.variable == rhs.variable
}
func normalize(_ current: Any?) -> Any? {
if let current = current as? Normalizable {
return current.normalize()
}
return current
}
protocol Normalizable {
func normalize() -> Any?
}
extension Array : Normalizable {
func normalize() -> Any? {
return map { $0 as Any }
}
}
extension NSArray : Normalizable {
func normalize() -> Any? {
return map { $0 as Any }
}
}
extension Dictionary : Normalizable {
func normalize() -> Any? {
var dictionary: [String: Any] = [:]
for (key, value) in self {
if let key = key as? String {
dictionary[key] = Stencil.normalize(value)
} else if let key = key as? CustomStringConvertible {
dictionary[key.description] = Stencil.normalize(value)
}
}
return dictionary
}
}
func parseFilterComponents(token: String) -> (String, [Variable]) {
var components = token.smartSplit(separator: ":")
let name = components.removeFirst()
let variables = components
.joined(separator: ":")
.smartSplit(separator: ",")
.map { Variable($0) }
return (name, variables)
}
| mit | c7f1d9f76fcd592b804d054b81138a9f | 25.115607 | 133 | 0.612439 | 4.126027 | false | false | false | false |
gvzq/iOS-Twitter | Twitter/ProfileViewController.swift | 1 | 2913 | //
// ProfileViewController.swift
// Twitter
//
// Created by Gerardo Vazquez on 2/24/16.
// Copyright © 2016 Gerardo Vazquez. All rights reserved.
//
import UIKit
class ProfileViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
@IBOutlet weak var profileImageView: UIImageView!
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var screenNameLabel: UILabel!
@IBOutlet weak var tweetsCountLabel: UILabel!
@IBOutlet weak var followingCountLabel: UILabel!
@IBOutlet weak var followersCountLabel: UILabel!
@IBOutlet weak var tableView: UITableView!
var user: User!
var tweets: [Tweet]?
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
self.tableView.separatorInset = UIEdgeInsetsZero
profileImageView.setImageWithURL(NSURL(string: (user?.profileImageUrl)!)!)
nameLabel.text = user?.name
screenNameLabel.text = user?.screenName
let formatter = NSNumberFormatter()
formatter.numberStyle = .DecimalStyle
tweetsCountLabel.text = formatter.stringFromNumber((user?.tweetsCount)!)
followingCountLabel.text = formatter.stringFromNumber((user?.followingCount)!)
followersCountLabel.text = formatter.stringFromNumber((user?.followersCount)!)
TwitterClient.sharedInstance.userTimeLineWithParams(user.screenName, params: nil, completion: {(tweets, error) -> () in
print(self.user.screenName)
self.tweets = tweets
self.tableView.reloadData()
})
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
if tweets != nil {
return tweets!.count
} else {
return 0
}
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("UserTweetCell", forIndexPath: indexPath) as! UserTweetCell
cell.tweet = tweets![indexPath.row]
cell.selectionStyle = .Default
let backgroundView = UIView()
backgroundView.backgroundColor = UIColor.whiteColor()
cell.selectedBackgroundView = backgroundView
return cell
}
/*
// 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.
}
*/
}
| apache-2.0 | 7b9f52c05299d03f6be9b278a01985b7 | 34.084337 | 127 | 0.676168 | 5.567878 | false | false | false | false |
githubxiangdong/DouYuZB | DouYuZB/DouYuZB/Classes/Home/View/AmuseMenuView.swift | 1 | 3153 | //
// AmuseMenuView.swift
// DouYuZB
//
// Created by new on 2017/5/16.
// Copyright © 2017年 9-kylins. All rights reserved.
//
import UIKit
private let kMenuCellID = "kMenuCellID"
class AmuseMenuView: UIView {
//MARK:- 定义属性
var groupModels : [AnchorGroupModel]? {
didSet {
collectionView.reloadData()
}
}
//MARK:- 控件属性
@IBOutlet var collectionView: UICollectionView!
@IBOutlet var pageControl: UIPageControl!
//MARK:- 系统回调函数
override func awakeFromNib() {
super.awakeFromNib()
// 设置该控件不随着父控件的拉伸而拉伸
autoresizingMask = UIViewAutoresizing()
collectionView.register(UINib(nibName: "AmuseMenuCell", bundle: nil), forCellWithReuseIdentifier: kMenuCellID)
//MARK:- 不能在这里面设置layout的尺寸,collectionView的frame是不对的在这里面
}
//MARK:- 在layoutSubviews()里面设置layout
override func layoutSubviews() {
super.layoutSubviews()
// 根据collectionView的layout设置layout.itemSize
let layout = collectionView.collectionViewLayout as! UICollectionViewFlowLayout
layout.itemSize = collectionView.bounds.size
}
}
//MARK:- 快速创建AmuseMenuView的方法
extension AmuseMenuView {
class func amuseMenuView() -> AmuseMenuView {
return Bundle.main.loadNibNamed("AmuseMenuView", owner: nil, options: nil)?.first as! AmuseMenuView
}
}
//MARK:- 实现collectionView的数据源协议
extension AmuseMenuView : UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
if groupModels == nil { return 0 }
let pageNum = (groupModels!.count - 1) / 8 + 1
pageControl.numberOfPages = pageNum
return pageNum
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: kMenuCellID, for: indexPath) as! AmuseMenuCell
setupCellDataWithCell(cell: cell, indexPath: indexPath)
return cell
}
private func setupCellDataWithCell(cell : AmuseMenuCell, indexPath : IndexPath) {
// 0页:0~7
// 1页:8~15
// 2页:16~23
// 1, 取出起始位置和终点位置
let startIndex = indexPath.item * 8
var endIndex = (indexPath.item + 1) * 8 - 1
// 2, 判断越界的问题
if endIndex > groupModels!.count - 1 { // 这个地方可以强制解包,因为如果是0的话,就不会到这个方法里面
endIndex = groupModels!.count - 1
}
// 3, 给cell赋值
cell.groupModels = Array(groupModels![startIndex...endIndex])// 数组范围的写法
}
}
//MARK:- 实现collectionView的代理方法
extension AmuseMenuView : UICollectionViewDelegate {
func scrollViewDidScroll(_ scrollView: UIScrollView) {
pageControl.currentPage = Int(scrollView.contentOffset.x / kScreenW)
}
}
| mit | ff11418136887df6d16cb69781761963 | 28.75 | 121 | 0.668067 | 4.720661 | false | false | false | false |
tensorflow/swift | Sources/SIL/SILPrinter.swift | 1 | 21968 | // Copyright 2019 The TensorFlow Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
class SILPrinter: Printer {
func print(_ module: Module) {
print(module.functions, "\n\n") { print($0) }
}
func print(_ function: Function) {
print("sil ")
print(function.linkage)
print(whenEmpty: false, "", function.attributes, " ", " ") { print($0) }
print("@")
print(function.name)
print(" : ")
print(function.type)
print(whenEmpty: false, " {\n", function.blocks, "\n", "}") { print($0) }
}
func print(_ block: Block) {
print(block.identifier)
print(whenEmpty: false, "(", block.arguments, ", ", ")") { print($0) }
print(":")
indent()
print(block.operatorDefs) { print("\n"); print($0) }
print("\n")
print(block.terminatorDef)
print("\n")
unindent()
}
func print(_ operatorDef: OperatorDef) {
print(operatorDef.result, " = ") { print($0) }
print(operatorDef.operator)
print(operatorDef.sourceInfo) { print($0) }
}
func print(_ terminatorDef: TerminatorDef) {
print(terminatorDef.terminator)
print(terminatorDef.sourceInfo) { print($0) }
}
func print(_ op: Operator) {
switch op {
case let .allocStack(type, attributes):
print("alloc_stack ")
print(type)
print(whenEmpty: false, ", ", attributes, ", ", "") { print($0) }
case let .apply(nothrow, value, substitutions, arguments, type):
print("apply ")
print(when: nothrow, "[nothrow] ")
print(value)
print(whenEmpty: false, "<", substitutions, ", ", ">") { naked($0) }
print("(", arguments, ", ", ")") { print($0) }
print(" : ")
print(type)
case let .beginAccess(access, enforcement, noNestedConflict, builtin, operand):
print("begin_access ")
print("[")
print(access)
print("] ")
print("[")
print(enforcement)
print("] ")
print(when: noNestedConflict, "[noNestedConflict] ")
print(when: builtin, "[builtin] ")
print(operand)
case let .beginApply(nothrow, value, substitutions, arguments, type):
print("begin_apply ")
print(when: nothrow, "[nothrow] ")
print(value)
print(whenEmpty: false, "<", substitutions, ", ", ">") { naked($0) }
print("(", arguments, ", ", ")") { print($0) }
print(" : ")
print(type)
case let .beginBorrow(operand):
print("begin_borrow ")
print(operand)
case let .builtin(name, operands, type):
print("builtin ")
literal(name)
print("(", operands, ", ", ")") { print($0) }
print(" : ")
print(type)
case let .condFail(operand, message):
print("cond_fail ")
print(operand)
print(", ")
literal(message)
case let .convertEscapeToNoescape(notGuaranteed, escaped, operand, type):
print("convert_escape_to_noescape ")
print(when: notGuaranteed, "[not_guaranteed] ")
print(when: escaped, "[escaped] ")
print(operand)
print(" to ")
print(type)
case let .convertFunction(operand, withoutActuallyEscaping, type):
print("convert_function ")
print(operand)
print(" to ")
print(when: withoutActuallyEscaping, "[without_actually_escaping] ")
print(type)
case let .copyAddr(take, value, initialization, operand):
print("copy_addr ")
print(when: take, "[take] ")
print(value)
print(" to ")
print(when: initialization, "[initialization] ")
print(operand)
case let .copyValue(operand):
print("copy_value ")
print(operand)
case let .deallocStack(operand):
print("dealloc_stack ")
print(operand)
case let .debugValue(operand, attributes):
print("debug_value ")
print(operand)
print(whenEmpty: false, ", ", attributes, ", ", "") { print($0) }
case let .debugValueAddr(operand, attributes):
print("debug_value_addr ")
print(operand)
print(whenEmpty: false, ", ", attributes, ", ", "") { print($0) }
case let .destroyValue(operand):
print("destroy_value ")
print(operand)
case let .destructureTuple(operand):
print("destructure_tuple ")
print(operand)
case let .endAccess(abort, operand):
print("end_access ")
print(when: abort, "[abort] ")
print(operand)
case let .endApply(value):
print("end_apply ")
print(value)
case let .endBorrow(value):
print("end_borrow ")
print(value)
case let .enum(type, declRef, maybeOperand):
print("enum ")
print(type)
print(", ")
print(declRef)
if let operand = maybeOperand {
print(", ")
print(operand)
}
case let .floatLiteral(type, value):
print("float_literal ")
print(type)
print(", 0x")
print(value)
case let .functionRef(name, type):
print("function_ref ")
print("@")
print(name)
print(" : ")
print(type)
case let .globalAddr(name, type):
print("global_addr ")
print("@")
print(name)
print(" : ")
print(type)
case let .indexAddr(addr, index):
print("index_addr ")
print(addr)
print(", ")
print(index)
case let .integerLiteral(type, value):
print("integer_literal ")
print(type)
print(", ")
literal(value)
case let .load(maybeOwnership, operand):
print("load ")
if let ownership = maybeOwnership {
print(ownership)
print(" ")
}
print(operand)
case let .markDependence(operand, on):
print("mark_dependence ")
print(operand)
print(" on ")
print(on)
case let .metatype(type):
print("metatype ")
print(type)
case let .partialApply(calleeGuaranteed, onStack, value, substitutions, arguments, type):
print("partial_apply ")
print(when: calleeGuaranteed, "[callee_guaranteed] ")
print(when: onStack, "[on_stack] ")
print(value)
print(whenEmpty: false, "<", substitutions, ", ", ">") { naked($0) }
print("(", arguments, ", ", ")") { print($0) }
print(" : ")
print(type)
case let .pointerToAddress(operand, strict, type):
print("pointer_to_address ")
print(operand)
print(" to ")
print(when: strict, "[strict] ")
print(type)
case let .releaseValue(operand):
print("release_value ")
print(operand)
case let .retainValue(operand):
print("retain_value ")
print(operand)
case let .selectEnum(operand, cases, type):
print("select_enum ")
print(operand)
print(whenEmpty: false, "", cases, "", "") { print($0) }
print(" : ")
print(type)
case let .store(value, maybeOwnership, operand):
print("store ")
print(value)
print(" to ")
if let ownership = maybeOwnership {
print(ownership)
print(" ")
}
print(operand)
case let .stringLiteral(encoding, value):
print("string_literal ")
print(encoding)
print(" ")
literal(value)
case let .strongRelease(operand):
print("strong_release ")
print(operand)
case let .strongRetain(operand):
print("strong_retain ")
print(operand)
case let .struct(type, operands):
print("struct ")
print(type)
print(" (", operands, ", ", ")") { print($0) }
case let .structElementAddr(operand, declRef):
print("struct_element_addr ")
print(operand)
print(", ")
print(declRef)
case let .structExtract(operand, declRef):
print("struct_extract ")
print(operand)
print(", ")
print(declRef)
case let .thinToThickFunction(operand, type):
print("thin_to_thick_function ")
print(operand)
print(" to ")
print(type)
case let .tuple(elements):
print("tuple ")
print(elements)
case let .tupleExtract(operand, declRef):
print("tuple_extract ")
print(operand)
print(", ")
literal(declRef)
case let .unknown(name):
print(name)
print(" <?>")
case let .witnessMethod(archeType, declRef, declType, type):
print("witness_method ")
print(archeType)
print(", ")
print(declRef)
print(" : ")
naked(declType)
print(" : ")
print(type)
}
}
func print(_ terminator: Terminator) {
switch terminator {
case let .br(label, operands):
print("br ")
print(label)
print(whenEmpty: false, "(", operands, ", ", ")") { print($0) }
case let .condBr(cond, trueLabel, trueOperands, falseLabel, falseOperands):
print("cond_br ")
print(cond)
print(", ")
print(trueLabel)
print(whenEmpty: false, "(", trueOperands, ", ", ")") { print($0) }
print(", ")
print(falseLabel)
print(whenEmpty: false, "(", falseOperands, ", ", ")") { print($0) }
case let .return(operand):
print("return ")
print(operand)
case let .switchEnum(operand, cases):
print("switch_enum ")
print(operand)
print(whenEmpty: false, "", cases, "", "") { print($0) }
case let .unknown(name):
print(name)
print(" <?>")
case .unreachable:
print("unreachable")
}
}
// MARK: Auxiliary data structures
func print(_ access: Access) {
switch access {
case .deinit:
print("deinit")
case .`init`:
print("init")
case .modify:
print("modify")
case .read:
print("read")
}
}
func print(_ argument: Argument) {
print(argument.valueName)
print(" : ")
print(argument.type)
}
func print(_ `case`: Case) {
print(", ")
switch `case` {
case let .case(declRef, result):
print("case ")
print(declRef)
print(": ")
print(result)
case let .default(result):
print("default ")
print(result)
}
}
func print(_ convention: Convention) {
print("(")
switch convention {
case .c:
print("c")
case .method:
print("method")
case .thin:
print("thin")
case let .witnessMethod(type):
print("witness_method: ")
naked(type)
}
print(")")
}
func print(_ attribute: DebugAttribute) {
switch attribute {
case let .argno(name):
print("argno ")
literal(name)
case let .name(name):
print("name ")
literal(name)
case .let:
print("let")
case .var:
print("var")
}
}
func print(_ declKind: DeclKind) {
switch declKind {
case .allocator:
print("allocator")
case .deallocator:
print("deallocator")
case .destroyer:
print("destroyer")
case .enumElement:
print("enumelt")
case .getter:
print("getter")
case .globalAccessor:
print("globalaccessor")
case .initializer:
print("initializer")
case .ivarDestroyer:
print("ivardestroyer")
case .ivarInitializer:
print("ivarinitializer")
case .setter:
print("setter")
}
}
func print(_ declRef: DeclRef) {
print("#")
print(declRef.name.joined(separator: "."))
if let kind = declRef.kind {
print("!")
print(kind)
}
if let level = declRef.level {
print(declRef.kind == nil ? "!" : ".")
literal(level)
}
}
func print(_ encoding: Encoding) {
switch encoding {
case .objcSelector:
print("objcSelector")
case .utf8:
print("utf8")
case .utf16:
print("utf16")
}
}
func print(_ enforcement: Enforcement) {
switch enforcement {
case .dynamic:
print("dynamic")
case .static:
print("static")
case .unknown:
print("unknown")
case .unsafe:
print("unsafe")
}
}
func print(_ attribute: FunctionAttribute) {
switch attribute {
case .alwaysInline:
print("[always_inline]")
case let .differentiable(spec):
print("[differentiable ")
print(spec)
print("]")
case .dynamicallyReplacable:
print("[dynamically_replacable]")
case .noInline:
print("[noinline]")
case .noncanonical(.ownershipSSA):
print("[ossa]")
case .readonly:
print("[readonly]")
case let .semantics(value):
print("[_semantics ")
literal(value)
print("]")
case .serialized:
print("[serialized]")
case .thunk:
print("[thunk]")
case .transparent:
print("[transparent]")
}
}
func print(_ linkage: Linkage) {
switch linkage {
case .hidden:
print("hidden ")
case .hiddenExternal:
print("hidden_external ")
case .private:
print("private ")
case .privateExternal:
print("private_external ")
case .public:
print("")
case .publicExternal:
print("public_external ")
case .publicNonABI:
print("non_abi ")
case .shared:
print("shared ")
case .sharedExternal:
print("shared_external ")
}
}
func print(_ loc: Loc) {
print("loc ")
literal(loc.path)
print(":")
literal(loc.line)
print(":")
literal(loc.column)
}
func print(_ operand: Operand) {
print(operand.value)
print(" : ")
print(operand.type)
}
func print(_ result: Result) {
if result.valueNames.count == 1 {
print(result.valueNames[0])
} else {
print("(", result.valueNames, ", ", ")") { print($0) }
}
}
func print(_ sourceInfo: SourceInfo) {
// NB: The SIL docs say that scope refs precede locations, but this is
// not true once you look at the compiler outputs or its source code.
print(", ", sourceInfo.loc) { print($0) }
print(", scope ", sourceInfo.scopeRef) { print($0) }
}
func print(_ elements: TupleElements) {
switch elements {
case let .labeled(type, values):
print(type)
print(" (", values, ", ", ")") { print($0) }
case let .unlabeled(operands):
print("(", operands, ", ", ")") { print($0) }
}
}
func print(_ type: Type) {
if case let .withOwnership(attr, subtype) = type {
print(attr)
print(" ")
print(subtype)
} else {
print("$")
naked(type)
}
}
func naked(_ type: Type) {
switch type {
case let .addressType(type):
print("*")
naked(type)
case let .attributedType(attrs, type):
print("", attrs, " ", " ") { print($0) }
naked(type)
case .coroutineTokenType:
print("!CoroutineTokenType!")
case let .functionType(params, result):
print("(", params, ", ", ")") { naked($0) }
print(" -> ")
naked(result)
case let .genericType(params, reqs, type):
print("<", params, ", ", "") { print($0) }
print(whenEmpty: false, " where ", reqs, ", ", "") { print($0) }
print(">")
// This is a weird corner case of -emit-sil, so we have to go the extra mile.
if case .genericType = type {
naked(type)
} else {
print(" ")
naked(type)
}
case let .namedType(name):
print(name)
case let .selectType(type, name):
naked(type)
print(".")
print(name)
case .selfType:
print("Self")
case let .specializedType(type, args):
naked(type)
print("<", args, ", ", ">") { naked($0) }
case let .tupleType(params):
print("(", params, ", ", ")") { naked($0) }
case .withOwnership(_, _):
fatalError("Types with ownership should be printed before naked type print!")
}
}
func print(_ attribute: TypeAttribute) {
switch attribute {
case .calleeGuaranteed:
print("@callee_guaranteed")
case let .convention(convention):
print("@convention")
print(convention)
case .guaranteed:
print("@guaranteed")
case .inGuaranteed:
print("@in_guaranteed")
case .in:
print("@in")
case .inout:
print("@inout")
case .noescape:
print("@noescape")
case .out:
print("@out")
case .owned:
print("@owned")
case .thick:
print("@thick")
case .thin:
print("@thin")
case .yieldOnce:
print("@yield_once")
case .yields:
print("@yields")
}
}
func print(_ requirement: TypeRequirement) {
switch requirement {
case let .conformance(lhs, rhs):
naked(lhs)
print(" : ")
naked(rhs)
case let .equality(lhs, rhs):
naked(lhs)
print(" == ")
naked(rhs)
}
}
func print(_ ownership: LoadOwnership) {
switch ownership {
case .copy: print("[copy]")
case .take: print("[take]")
case .trivial: print("[trivial]")
}
}
func print(_ ownership: StoreOwnership) {
switch ownership {
case .`init`: print("[init]")
case .trivial: print("[trivial]")
}
}
}
extension Module: CustomStringConvertible {
public var description: String {
let p = SILPrinter()
p.print(self)
return p.description
}
}
extension Function: CustomStringConvertible {
public var description: String {
let p = SILPrinter()
p.print(self)
return p.description
}
}
extension Block: CustomStringConvertible {
public var description: String {
let p = SILPrinter()
p.print(self)
return p.description
}
}
extension OperatorDef: CustomStringConvertible {
public var description: String {
let p = SILPrinter()
p.print(self)
return p.description
}
}
extension TerminatorDef: CustomStringConvertible {
public var description: String {
let p = SILPrinter()
p.print(self)
return p.description
}
}
extension InstructionDef: CustomStringConvertible {
public var description: String {
switch self {
case let .operator(def): return def.description
case let .terminator(def): return def.description
}
}
}
extension Operator: CustomStringConvertible {
public var description: String {
let p = SILPrinter()
p.print(self)
return p.description
}
}
extension Terminator: CustomStringConvertible {
public var description: String {
let p = SILPrinter()
p.print(self)
return p.description
}
}
extension Instruction: CustomStringConvertible {
public var description: String {
switch self {
case let .operator(def): return def.description
case let .terminator(def): return def.description
}
}
}
| apache-2.0 | c568310c99f324711b4853444e2a6453 | 29.134431 | 97 | 0.496222 | 4.579529 | false | false | false | false |
kripple/bti-watson | ios-app/Carthage/Checkouts/AlamofireObjectMapper/Carthage/Checkouts/ObjectMapper/Carthage/Checkouts/Nimble/Nimble/Matchers/BeGreaterThan.swift | 189 | 1567 | import Foundation
/// A Nimble matcher that succeeds when the actual value is greater than the expected value.
public func beGreaterThan<T: Comparable>(expectedValue: T?) -> NonNilMatcherFunc<T> {
return NonNilMatcherFunc { actualExpression, failureMessage in
failureMessage.postfixMessage = "be greater than <\(stringify(expectedValue))>"
return try actualExpression.evaluate() > expectedValue
}
}
/// A Nimble matcher that succeeds when the actual value is greater than the expected value.
public func beGreaterThan(expectedValue: NMBComparable?) -> NonNilMatcherFunc<NMBComparable> {
return NonNilMatcherFunc { actualExpression, failureMessage in
failureMessage.postfixMessage = "be greater than <\(stringify(expectedValue))>"
let actualValue = try actualExpression.evaluate()
let matches = actualValue != nil && actualValue!.NMB_compare(expectedValue) == NSComparisonResult.OrderedDescending
return matches
}
}
public func ><T: Comparable>(lhs: Expectation<T>, rhs: T) {
lhs.to(beGreaterThan(rhs))
}
public func >(lhs: Expectation<NMBComparable>, rhs: NMBComparable?) {
lhs.to(beGreaterThan(rhs))
}
extension NMBObjCMatcher {
public class func beGreaterThanMatcher(expected: NMBComparable?) -> NMBObjCMatcher {
return NMBObjCMatcher(canMatchNil: false) { actualExpression, failureMessage in
let expr = actualExpression.cast { $0 as? NMBComparable }
return try! beGreaterThan(expected).matches(expr, failureMessage: failureMessage)
}
}
}
| mit | f503c4dcdcd826ff40b9e9847abdc544 | 41.351351 | 123 | 0.730057 | 5.293919 | false | false | false | false |
masters3d/xswift | exercises/word-count/Sources/WordCountExample.swift | 1 | 970 | struct WordCount {
func splitStringToArray(_ inString: String) -> [String] {
return inString.characters.split(whereSeparator: { splitAt($0) }).map { String($0) }
}
func splitAt(_ characterToCompare: Character, charToSplitAt: String = " !&$%^&,:") -> Bool {
for each in charToSplitAt.characters {
if each == characterToCompare {
return true
}
}
return false
}
let words: String
init(words: String) {
self.words = words
}
func count() -> [String: Int] {
var dict = [String: Int]()
let cleanArray = splitStringToArray(words)
cleanArray.forEach { string in
if !string.isEmpty {
if let count = dict[string.lowercased()] {
dict[string.lowercased()] = count + 1
} else { dict[string.lowercased()] = 1
}
}
}
return dict
}
}
| mit | 9a74c52e6752df5ad315fd587ca2e4e4 | 25.944444 | 96 | 0.515464 | 4.470046 | false | false | false | false |
tlax/looper | looper/View/Main/Subclasses/VSpinner.swift | 1 | 1037 | import UIKit
class VSpinner:UIImageView
{
private let kAnimationDuration:TimeInterval = 1
init()
{
super.init(frame:CGRect.zero)
let images:[UIImage] = [
#imageLiteral(resourceName: "assetSpinner0"),
#imageLiteral(resourceName: "assetSpinner1"),
#imageLiteral(resourceName: "assetSpinner2"),
#imageLiteral(resourceName: "assetSpinner3"),
#imageLiteral(resourceName: "assetSpinner4"),
#imageLiteral(resourceName: "assetSpinner5"),
#imageLiteral(resourceName: "assetSpinner6"),
#imageLiteral(resourceName: "assetSpinner7")
]
isUserInteractionEnabled = false
translatesAutoresizingMaskIntoConstraints = false
clipsToBounds = true
animationDuration = kAnimationDuration
animationImages = images
contentMode = UIViewContentMode.center
startAnimating()
}
required init?(coder:NSCoder)
{
return nil
}
}
| mit | f7ca8348e0309597a3c9a187bacc5b10 | 28.628571 | 57 | 0.621986 | 5.95977 | false | false | false | false |
xusader/firefox-ios | Client/Frontend/Reader/ReaderModeStyleViewController.swift | 3 | 14656 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import UIKit
private struct ReaderModeStyleViewControllerUX {
static let RowHeight = 50
static let Width = 270
static let Height = 4 * RowHeight
static let FontTypeRowBackground = UIColor(rgb: 0xfbfbfb)
static let FontTypeTitleFontSansSerif = UIFont(name: "FiraSans", size: 16)
static let FontTypeTitleFontSerif = UIFont(name: "Charis SIL", size: 16)
static let FontTypeTitleSelectedColor = UIColor(rgb: 0x333333)
static let FontTypeTitleNormalColor = UIColor.lightGrayColor() // TODO THis needs to be 44% of 0x333333
static let FontSizeRowBackground = UIColor(rgb: 0xf4f4f4)
static let FontSizeLabelFontSansSerif = UIFont(name: "FiraSans-Book", size: 22)
static let FontSizeLabelFontSerif = UIFont(name: "Charis SIL", size: 22)
static let FontSizeLabelColor = UIColor(rgb: 0x333333)
static let FontSizeButtonTextColorEnabled = UIColor(rgb: 0x333333)
static let FontSizeButtonTextColorDisabled = UIColor.lightGrayColor() // TODO THis needs to be 44% of 0x333333
static let FontSizeButtonTextFont = UIFont(name: "FiraSans-Book", size: 22)
static let ThemeRowBackgroundColor = UIColor.whiteColor()
static let ThemeTitleFontSansSerif = UIFont(name: "FiraSans-Light", size: 15)
static let ThemeTitleFontSerif = UIFont(name: "Charis SIL", size: 15)
static let ThemeTitleColorLight = UIColor(rgb: 0x333333)
static let ThemeTitleColorDark = UIColor.whiteColor()
static let ThemeTitleColorSepia = UIColor(rgb: 0x333333)
static let ThemeBackgroundColorLight = UIColor.whiteColor()
static let ThemeBackgroundColorDark = UIColor.blackColor()
static let ThemeBackgroundColorSepia = UIColor(rgb: 0xf0ece7)
static let BrightnessRowBackground = UIColor(rgb: 0xf4f4f4)
static let BrightnessSliderTintColor = UIColor(rgb: 0xe66000)
static let BrightnessSliderWidth = 140
static let BrightnessIconOffset = 10
}
// MARK: -
protocol ReaderModeStyleViewControllerDelegate {
func readerModeStyleViewController(readerModeStyleViewController: ReaderModeStyleViewController, didConfigureStyle style: ReaderModeStyle)
}
// MARK: -
class ReaderModeStyleViewController: UIViewController {
var delegate: ReaderModeStyleViewControllerDelegate?
var readerModeStyle: ReaderModeStyle = DefaultReaderModeStyle
private var fontTypeButtons: [FontTypeButton]!
private var fontSizeLabel: FontSizeLabel!
private var fontSizeButtons: [FontSizeButton]!
private var themeButtons: [ThemeButton]!
override func viewDidLoad() {
// Our preferred content size has a fixed width and height based on the rows + padding
preferredContentSize = CGSize(width: ReaderModeStyleViewControllerUX.Width, height: ReaderModeStyleViewControllerUX.Height)
popoverPresentationController?.backgroundColor = ReaderModeStyleViewControllerUX.FontTypeRowBackground
// Font type row
let fontTypeRow = UIView()
view.addSubview(fontTypeRow)
fontTypeRow.backgroundColor = ReaderModeStyleViewControllerUX.FontTypeRowBackground
fontTypeRow.snp_makeConstraints { (make) -> () in
make.top.equalTo(self.view)
make.left.right.equalTo(self.view)
make.height.equalTo(ReaderModeStyleViewControllerUX.RowHeight)
}
fontTypeButtons = [
FontTypeButton(fontType: ReaderModeFontType.SansSerif),
FontTypeButton(fontType: ReaderModeFontType.Serif)
]
setupButtons(fontTypeButtons, inRow: fontTypeRow, action: "SELchangeFontType:")
// Font size row
let fontSizeRow = UIView()
view.addSubview(fontSizeRow)
fontSizeRow.backgroundColor = ReaderModeStyleViewControllerUX.FontSizeRowBackground
fontSizeRow.snp_makeConstraints { (make) -> () in
make.top.equalTo(fontTypeRow.snp_bottom)
make.left.right.equalTo(self.view)
make.height.equalTo(ReaderModeStyleViewControllerUX.RowHeight)
}
fontSizeLabel = FontSizeLabel()
fontSizeRow.addSubview(fontSizeLabel)
fontSizeLabel.snp_makeConstraints { (make) -> () in
make.center.equalTo(fontSizeRow)
return
}
fontSizeButtons = [
FontSizeButton(fontSizeAction: FontSizeAction.Smaller),
FontSizeButton(fontSizeAction: FontSizeAction.Bigger)
]
setupButtons(fontSizeButtons, inRow: fontSizeRow, action: "SELchangeFontSize:")
// Theme row
let themeRow = UIView()
view.addSubview(themeRow)
themeRow.snp_makeConstraints { (make) -> () in
make.top.equalTo(fontSizeRow.snp_bottom)
make.left.right.equalTo(self.view)
make.height.equalTo(ReaderModeStyleViewControllerUX.RowHeight)
}
themeButtons = [
ThemeButton(theme: ReaderModeTheme.Light),
ThemeButton(theme: ReaderModeTheme.Dark),
ThemeButton(theme: ReaderModeTheme.Sepia)
]
setupButtons(themeButtons, inRow: themeRow, action: "SELchangeTheme:")
// Brightness row
let brightnessRow = UIView()
view.addSubview(brightnessRow)
brightnessRow.backgroundColor = ReaderModeStyleViewControllerUX.BrightnessRowBackground
brightnessRow.snp_makeConstraints { (make) -> () in
make.top.equalTo(themeRow.snp_bottom)
make.left.right.equalTo(self.view)
make.height.equalTo(ReaderModeStyleViewControllerUX.RowHeight)
}
let slider = UISlider()
brightnessRow.addSubview(slider)
slider.tintColor = ReaderModeStyleViewControllerUX.BrightnessSliderTintColor
slider.addTarget(self, action: "SELchangeBrightness:", forControlEvents: UIControlEvents.ValueChanged)
slider.snp_makeConstraints { make in
make.center.equalTo(brightnessRow.center)
make.width.equalTo(ReaderModeStyleViewControllerUX.BrightnessSliderWidth)
}
let brightnessMinImageView = UIImageView(image: UIImage(named: "brightnessMin"))
brightnessRow.addSubview(brightnessMinImageView)
brightnessMinImageView.snp_makeConstraints { (make) -> () in
make.centerY.equalTo(slider)
make.right.equalTo(slider.snp_left).offset(-ReaderModeStyleViewControllerUX.BrightnessIconOffset)
}
let brightnessMaxImageView = UIImageView(image: UIImage(named: "brightnessMax"))
brightnessRow.addSubview(brightnessMaxImageView)
brightnessMaxImageView.snp_makeConstraints { (make) -> () in
make.centerY.equalTo(slider)
make.left.equalTo(slider.snp_right).offset(ReaderModeStyleViewControllerUX.BrightnessIconOffset)
}
selectFontType(readerModeStyle.fontType)
updateFontSizeButtons()
selectTheme(readerModeStyle.theme)
slider.value = Float(UIScreen.mainScreen().brightness)
}
/// Setup constraints for a row of buttons. Left to right. They are all given the same width.
private func setupButtons(buttons: [UIButton], inRow row: UIView, action: Selector) {
for (idx, button) in enumerate(buttons) {
row.addSubview(button)
button.addTarget(self, action: action, forControlEvents: UIControlEvents.TouchUpInside)
button.snp_makeConstraints { make in
make.top.equalTo(row.snp_top)
if idx == 0 {
make.left.equalTo(row.snp_left)
} else {
make.left.equalTo(buttons[idx - 1].snp_right)
}
make.bottom.equalTo(row.snp_bottom)
make.width.equalTo(self.preferredContentSize.width / CGFloat(buttons.count))
}
}
}
func SELchangeFontType(button: FontTypeButton) {
selectFontType(button.fontType)
delegate?.readerModeStyleViewController(self, didConfigureStyle: readerModeStyle)
}
private func selectFontType(fontType: ReaderModeFontType) {
readerModeStyle.fontType = fontType
for button in fontTypeButtons {
button.selected = (button.fontType == fontType)
}
for button in themeButtons {
button.fontType = fontType
}
fontSizeLabel.fontType = fontType
}
func SELchangeFontSize(button: FontSizeButton) {
switch button.fontSizeAction {
case .Smaller:
readerModeStyle.fontSize = readerModeStyle.fontSize.smaller()
case .Bigger:
readerModeStyle.fontSize = readerModeStyle.fontSize.bigger()
}
updateFontSizeButtons()
delegate?.readerModeStyleViewController(self, didConfigureStyle: readerModeStyle)
}
private func updateFontSizeButtons() {
for button in fontSizeButtons {
switch button.fontSizeAction {
case .Bigger:
button.enabled = !readerModeStyle.fontSize.isLargest()
break
case .Smaller:
button.enabled = !readerModeStyle.fontSize.isSmallest()
break
}
}
}
func SELchangeTheme(button: ThemeButton) {
selectTheme(button.theme)
delegate?.readerModeStyleViewController(self, didConfigureStyle: readerModeStyle)
}
private func selectTheme(theme: ReaderModeTheme) {
readerModeStyle.theme = theme
}
func SELchangeBrightness(slider: UISlider) {
UIScreen.mainScreen().brightness = CGFloat(slider.value)
}
}
// MARK: -
class FontTypeButton: UIButton {
var fontType: ReaderModeFontType = .SansSerif
convenience init(fontType: ReaderModeFontType) {
self.init(frame: CGRectZero)
self.fontType = fontType
setTitleColor(ReaderModeStyleViewControllerUX.FontTypeTitleSelectedColor, forState: UIControlState.Selected)
setTitleColor(ReaderModeStyleViewControllerUX.FontTypeTitleNormalColor, forState: UIControlState.Normal)
backgroundColor = ReaderModeStyleViewControllerUX.FontTypeRowBackground
switch fontType {
case .SansSerif:
setTitle(NSLocalizedString("Sans-serif", comment: "Font type setting in the reading view settings"), forState: UIControlState.Normal)
let f = ReaderModeStyleViewControllerUX.ThemeTitleFontSansSerif
titleLabel?.font = f
case .Serif:
setTitle(NSLocalizedString("Serif", comment: "Font type setting in the reading view settings"), forState: UIControlState.Normal)
let f = ReaderModeStyleViewControllerUX.ThemeTitleFontSerif
titleLabel?.font = f
}
}
}
// MARK: -
enum FontSizeAction {
case Smaller
case Bigger
}
class FontSizeButton: UIButton {
var fontSizeAction: FontSizeAction = .Bigger
convenience init(fontSizeAction: FontSizeAction) {
self.init(frame: CGRectZero)
self.fontSizeAction = fontSizeAction
setTitleColor(ReaderModeStyleViewControllerUX.FontSizeButtonTextColorEnabled, forState: UIControlState.Normal)
setTitleColor(ReaderModeStyleViewControllerUX.FontSizeButtonTextColorDisabled, forState: UIControlState.Disabled)
switch fontSizeAction {
case .Smaller:
let smallerFontLabel = NSLocalizedString("-", comment: "Button for smaller reader font size. Keep this extremely short! This is shown in the reader mode toolbar.")
setTitle(smallerFontLabel, forState: .Normal)
case .Bigger:
let largerFontLabel = NSLocalizedString("+", comment: "Button for larger reader font size. Keep this extremely short! This is shown in the reader mode toolbar.")
setTitle(largerFontLabel, forState: .Normal)
}
// TODO Does this need to change with the selected font type? Not sure if makes sense for just +/-
titleLabel?.font = ReaderModeStyleViewControllerUX.FontSizeButtonTextFont
}
}
// MARK: -
class FontSizeLabel: UILabel {
override init(frame: CGRect) {
super.init(frame: frame)
let fontSizeLabel = NSLocalizedString("Aa", comment: "Button for reader mode font size. Keep this extremely short! This is shown in the reader mode toolbar.")
text = fontSizeLabel
}
required init(coder aDecoder: NSCoder) {
// TODO
fatalError("init(coder:) has not been implemented")
}
var fontType: ReaderModeFontType = .SansSerif {
didSet {
switch fontType {
case .SansSerif:
font = ReaderModeStyleViewControllerUX.FontSizeLabelFontSansSerif
case .Serif:
font = ReaderModeStyleViewControllerUX.FontSizeLabelFontSerif
}
}
}
}
// MARK: -
class ThemeButton: UIButton {
var theme: ReaderModeTheme!
convenience init(theme: ReaderModeTheme) {
self.init(frame: CGRectZero)
self.theme = theme
setTitle(theme.rawValue, forState: UIControlState.Normal)
switch theme {
case .Light:
setTitle(NSLocalizedString("Light", comment: "Light theme setting in Reading View settings"), forState: .Normal)
setTitleColor(ReaderModeStyleViewControllerUX.ThemeTitleColorLight, forState: UIControlState.Normal)
backgroundColor = ReaderModeStyleViewControllerUX.ThemeBackgroundColorLight
case .Dark:
setTitle(NSLocalizedString("Dark", comment: "Dark theme setting in Reading View settings"), forState: .Normal)
setTitleColor(ReaderModeStyleViewControllerUX.ThemeTitleColorDark, forState: UIControlState.Normal)
backgroundColor = ReaderModeStyleViewControllerUX.ThemeBackgroundColorDark
case .Sepia:
setTitle(NSLocalizedString("Sepia", comment: "Sepia theme setting in Reading View settings"), forState: .Normal)
setTitleColor(ReaderModeStyleViewControllerUX.ThemeTitleColorSepia, forState: UIControlState.Normal)
backgroundColor = ReaderModeStyleViewControllerUX.ThemeBackgroundColorSepia
}
}
var fontType: ReaderModeFontType = .SansSerif {
didSet {
switch fontType {
case .SansSerif:
titleLabel?.font = ReaderModeStyleViewControllerUX.ThemeTitleFontSansSerif
case .Serif:
titleLabel?.font = ReaderModeStyleViewControllerUX.ThemeTitleFontSerif
}
}
}
} | mpl-2.0 | f6a17d02acfe2f273f5f06d9333555c8 | 38.828804 | 175 | 0.689956 | 5.464579 | false | false | false | false |
OscarSwanros/swift | test/DebugInfo/test-foundation.swift | 4 | 3190 | // RUN: %target-swift-frontend -emit-ir -g %s -o %t.ll
// RUN: %FileCheck %s --check-prefix IMPORT-CHECK < %t.ll
// RUN: %FileCheck %s --check-prefix LOC-CHECK < %t.ll
// RUN: llc %t.ll -filetype=obj -o %t.o
// RUN: %llvm-dwarfdump %t.o | %FileCheck %s --check-prefix DWARF-CHECK
// DISABLED <rdar://problem/28232630>: %llvm-dwarfdump --verify %t.o
// REQUIRES: OS=macosx
import ObjectiveC
import Foundation
class MyObject : NSObject {
// Ensure we don't emit linetable entries for ObjC thunks.
// LOC-CHECK: define {{.*}} @_T04main8MyObjectC0B3ArrSo7NSArrayCvgTo
// LOC-CHECK: ret {{.*}}, !dbg ![[DBG:.*]]
// LOC-CHECK: ret
var MyArr = NSArray()
// IMPORT-CHECK: filename: "test-foundation.swift"
// IMPORT-CHECK-DAG: [[FOUNDATION:[0-9]+]] = !DIModule({{.*}} name: "Foundation",{{.*}} includePath:
// IMPORT-CHECK-DAG: !DICompositeType(tag: DW_TAG_structure_type, name: "NSArray", scope: ![[NSARRAY:[0-9]+]]
// IMPORT-CHECK-DAG: ![[NSARRAY]] = !DIModule(scope: ![[FOUNDATION:[0-9]+]], name: "NSArray"
// IMPORT-CHECK-DAG: !DIImportedEntity(tag: DW_TAG_imported_module, {{.*}}entity: ![[FOUNDATION]]
func foo(_ obj: MyObject) {
return obj.foo(obj)
}
}
// SANITY-DAG: !DISubprogram(name: "blah",{{.*}} line: [[@LINE+2]],{{.*}} isDefinition: true
extension MyObject {
func blah() {
var _ = MyObject()
}
}
// SANITY-DAG: ![[NSOBJECT:.*]] = !DICompositeType(tag: DW_TAG_structure_type, name: "NSObject",{{.*}} identifier: "_T0So8NSObjectC"
// SANITY-DAG: !DIGlobalVariable(name: "NsObj",{{.*}} line: [[@LINE+1]],{{.*}} type: ![[NSOBJECT]],{{.*}} isDefinition: true
var NsObj: NSObject
NsObj = MyObject()
var MyObj: MyObject
MyObj = NsObj as! MyObject
MyObj.blah()
public func err() {
// DWARF-CHECK: DW_AT_name ("NSError")
// DWARF-CHECK: DW_AT_linkage_name{{.*}}_T0So7NSErrorC
let _ = NSError(domain: "myDomain", code: 4,
userInfo: [AnyHashable("a"):1,
AnyHashable("b"):2,
AnyHashable("c"):3])
}
// LOC-CHECK: define {{.*}}4date
public func date() {
// LOC-CHECK: call {{.*}} @_T0S2SBp21_builtinStringLiteral_Bw17utf8CodeUnitCountBi1_7isASCIItcfC{{.*}}, !dbg ![[L1:.*]]
let d1 = DateFormatter()
d1.dateFormat = "dd. mm. yyyy" // LOC-CHECK: call{{.*}}objc_msgSend{{.*}}, !dbg ![[L2:.*]]
// LOC-CHECK: call {{.*}} @_T0S2SBp21_builtinStringLiteral_Bw17utf8CodeUnitCountBi1_7isASCIItcfC{{.*}}, !dbg ![[L3:.*]]
let d2 = DateFormatter()
d2.dateFormat = "mm dd yyyy" // LOC-CHECK: call{{.*}}objc_msgSend{{.*}}, !dbg ![[L4:.*]]
}
// Make sure we build some witness tables for enums.
func useOptions(_ opt: URL.BookmarkCreationOptions)
-> URL.BookmarkCreationOptions {
return [opt, opt]
}
// LOC-CHECK: ![[THUNK:.*]] = distinct !DISubprogram({{.*}}linkageName: "_T04main8MyObjectC0B3ArrSo7NSArrayCvgTo"
// LOC-CHECK-NOT: line:
// LOC-CHECK-SAME: isDefinition: true
// LOC-CHECK: ![[DBG]] = !DILocation(line: 0, scope: ![[THUNK]])
// These debug locations should all be in ordered by increasing line number.
// LOC-CHECK: ![[L1]] =
// LOC-CHECK: ![[L2]] =
// LOC-CHECK: ![[L3]] =
// LOC-CHECK: ![[L4]] =
| apache-2.0 | 860e6878bf971d4112a284c9eec84244 | 39.379747 | 132 | 0.612539 | 3.281893 | false | false | false | false |
openHPI/xikolo-ios | iOS/ViewControllers/Courses/CourseItemViewController.swift | 1 | 12436 | //
// Created for xikolo-ios under GPL-3.0 license.
// Copyright © HPI. All rights reserved.
//
import BrightFutures
import Common
import UIKit
import CoreData
class CourseItemViewController: UIPageViewController {
private lazy var progressLabel: UILabel = {
let label = UILabel()
label.font = UIFont.boldSystemFont(ofSize: UIFont.smallSystemFontSize)
return label
}()
private lazy var previousItemButton: UIButton = {
let button = UIButton(type: .custom)
button.setImage(R.image.chevronRight(), for: .normal)
button.addTarget(self, action: #selector(showPreviousItem), for: .touchUpInside)
button.imageView?.transform = CGAffineTransform(rotationAngle: CGFloat.pi)
button.imageView?.contentMode = .scaleAspectFit
button.imageEdgeInsets = UIEdgeInsets(top: 8, left: 8, bottom: 8, right: 8)
button.contentVerticalAlignment = .fill
button.contentHorizontalAlignment = .fill
button.translatesAutoresizingMaskIntoConstraints = false
button.isHidden = true
return button
}()
private lazy var nextItemButton: UIButton = {
let button = UIButton(type: .custom)
button.setImage(R.image.chevronRight(), for: .normal)
button.addTarget(self, action: #selector(showNextItem), for: .touchUpInside)
button.imageView?.contentMode = .scaleAspectFit
button.imageEdgeInsets = UIEdgeInsets(top: 8, left: 8, bottom: 8, right: 8)
button.contentVerticalAlignment = .fill
button.contentHorizontalAlignment = .fill
button.translatesAutoresizingMaskIntoConstraints = false
button.isHidden = true
return button
}()
private var previousItem: CourseItem?
private var nextItem: CourseItem?
var currentItem: CourseItem? {
didSet {
self.trackItemVisit()
ErrorManager.shared.remember(self.currentItem?.id as Any, forKey: "item_id")
self.previousItem = self.currentItem?.previousItem
self.nextItem = self.currentItem?.nextItem
self.navigationItem.rightBarButtonItem = self.generateActionMenuButton()
guard self.view.window != nil else { return }
self.updateProgressLabel()
self.updatePreviousAndNextItemButtons()
}
}
override func viewDidLoad() {
super.viewDidLoad()
self.dataSource = self
self.delegate = self
self.navigationItem.rightBarButtonItem = self.generateActionMenuButton()
self.view.backgroundColor = ColorCompatibility.systemBackground
self.navigationItem.titleView = self.progressLabel
guard let item = self.currentItem else { return }
guard let newViewController = self.viewController(for: item) else { return }
self.setViewControllers([newViewController], direction: .forward, animated: false)
self.view.addSubview(self.previousItemButton)
self.view.addSubview(self.nextItemButton)
NSLayoutConstraint.activate([
self.previousItemButton.leadingAnchor.constraint(equalTo: self.view.layoutMarginsGuide.leadingAnchor),
NSLayoutConstraint(item: self.previousItemButton,
attribute: .centerY,
relatedBy: .equal,
toItem: self.view.layoutMarginsGuide,
attribute: .centerY,
multiplier: 1.0,
constant: -32),
self.previousItemButton.widthAnchor.constraint(equalToConstant: 44),
self.previousItemButton.heightAnchor.constraint(equalToConstant: 44),
self.nextItemButton.trailingAnchor.constraint(equalTo: self.view.layoutMarginsGuide.trailingAnchor),
NSLayoutConstraint(item: self.nextItemButton,
attribute: .centerY,
relatedBy: .equal,
toItem: self.view.layoutMarginsGuide,
attribute: .centerY,
multiplier: 1.0,
constant: -32),
self.nextItemButton.widthAnchor.constraint(equalToConstant: 44),
self.nextItemButton.heightAnchor.constraint(equalToConstant: 44),
])
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
self.updatePreviousAndNextItemButtons()
}
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransition(to: size, with: coordinator)
coordinator.animate { _ in
self.updatePreviousAndNextItemButtons()
}
}
func reload(animated: Bool) {
guard let item = self.currentItem else { return }
guard let newViewController = self.viewController(for: item) else { return }
self.setViewControllers([newViewController], direction: .forward, animated: animated)
}
private func viewController(for item: CourseItem) -> CourseItemContentViewController? {
guard !item.isProctoredInProctoredCourse else {
let viewController = R.storyboard.courseLearningsProctored.instantiateInitialViewController()
viewController?.configure(for: item)
return viewController
}
guard item.hasAvailableContent else {
let viewController = R.storyboard.courseLearningsUnavailable.instantiateInitialViewController()
viewController?.configure(for: item)
viewController?.delegate = self
return viewController
}
let viewController: CourseItemContentViewController? = {
switch item.contentType {
case "video":
return R.storyboard.courseLearningsVideo.instantiateInitialViewController()
case "rich_text":
return R.storyboard.courseLearningsRichtext.instantiateInitialViewController()
case "lti_exercise":
return R.storyboard.courseLearningsLTI.instantiateInitialViewController()
case "peer_assessment":
return R.storyboard.courseLearningsPeerAssessment.instantiateInitialViewController()
default:
return R.storyboard.courseLearningsWeb.instantiateInitialViewController()
}
}()
viewController?.configure(for: item)
return viewController
}
@objc private func showPreviousItem() {
guard let item = self.previousItem else { return }
guard let newViewController = self.viewController(for: item) else { return }
self.setViewControllers([newViewController], direction: .reverse, animated: true) { completed in
guard completed else { return }
self.currentItem = item
}
}
@objc private func showNextItem() {
guard let item = self.nextItem else { return }
guard let newViewController = self.viewController(for: item) else { return }
self.setViewControllers([newViewController], direction: .forward, animated: true) { completed in
guard completed else { return }
self.currentItem = item
}
}
private func trackItemVisit() {
guard let item = self.currentItem else { return }
guard !item.isProctoredInProctoredCourse else { return }
guard item.hasAvailableContent else { return }
CourseItemHelper.markAsVisited(item)
LastVisitHelper.recordVisit(for: item)
let context = [
"content_type": item.contentType,
"section_id": item.section?.id,
"course_id": item.section?.course?.id,
]
TrackingHelper.createEvent(.visitedItem, resourceType: .item, resourceId: item.id, on: self, context: context)
}
private func generateActionMenuButton() -> UIBarButtonItem {
var menuActions: [[Action]] = []
if let video = self.currentItem?.content as? Video {
menuActions += [video.actions]
}
menuActions.append([
self.currentItem?.shareAction { [weak self] in self?.shareCourseItem() },
self.currentItem?.openHelpdesk { [weak self] in self?.openHelpdesk() },
].compactMap { $0 })
let button = UIBarButtonItem.circularItem(
with: R.image.navigationBarIcons.dots(),
target: self,
menuActions: menuActions
)
button.isEnabled = true
button.accessibilityLabel = NSLocalizedString(
"accessibility-label.course-item.navigation-bar.item.actions",
comment: "Accessibility label for actions button in navigation bar of the course item view"
)
return button
}
private func updateProgressLabel() {
if let item = self.currentItem, let section = item.section {
let sortedCourseItems = section.items.sorted(by: \.position)
if let index = sortedCourseItems.firstIndex(of: item) {
self.progressLabel.text = "\(index + 1) / \(section.items.count)"
self.progressLabel.sizeToFit()
} else {
self.progressLabel.text = "- / \(section.items.count)"
self.progressLabel.sizeToFit()
}
} else {
self.progressLabel.text = nil
}
}
func updatePreviousAndNextItemButtons() {
let enoughSpaceForButtons: Bool = {
let insets = NSDirectionalEdgeInsets.readableContentInsets(for: self)
return insets.leading >= 84
}()
let childViewControllerIsFullScreen: Bool = {
guard let videoViewController = self.viewControllers?.first as? VideoViewController else { return false }
return videoViewController.videoIsShownInFullScreen
}()
self.previousItemButton.isHidden = !enoughSpaceForButtons || childViewControllerIsFullScreen || self.previousItem == nil
self.nextItemButton.isHidden = !enoughSpaceForButtons || childViewControllerIsFullScreen || self.nextItem == nil
}
private func shareCourseItem() {
guard let item = self.currentItem else { return }
let activityViewController = UIActivityViewController(activityItems: [item], applicationActivities: nil)
activityViewController.popoverPresentationController?.barButtonItem = self.navigationItem.rightBarButtonItem
self.present(activityViewController, animated: trueUnlessReduceMotionEnabled)
}
private func openHelpdesk() {
let helpdeskViewController = R.storyboard.tabAccount.helpdeskViewController().require()
helpdeskViewController.course = self.currentItem?.section?.course
let navigationController = CustomWidthNavigationController(rootViewController: helpdeskViewController)
self.present(navigationController, animated: trueUnlessReduceMotionEnabled)
}
}
extension CourseItemViewController: UIPageViewControllerDataSource {
func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? {
guard let item = self.previousItem else { return nil }
guard let newViewController = self.viewController(for: item) else { return nil }
return newViewController
}
func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? {
guard let item = self.nextItem else { return nil }
guard let newViewController = self.viewController(for: item) else { return nil }
return newViewController
}
}
extension CourseItemViewController: UIPageViewControllerDelegate {
func pageViewController(_ pageViewController: UIPageViewController,
didFinishAnimating finished: Bool,
previousViewControllers: [UIViewController],
transitionCompleted completed: Bool) {
guard finished && completed else {
return
}
guard let currentCourseItemContentViewController = self.viewControllers?.first as? CourseItemContentViewController else {
return
}
self.currentItem = currentCourseItemContentViewController.item
}
}
| gpl-3.0 | fdb7a8c4f8e947b3f017a6900c0cbaf3 | 40.728188 | 149 | 0.656534 | 5.516859 | false | false | false | false |
LeoMobileDeveloper/PullToRefreshKit | Sources/PullToRefreshKit/Classes/Availability.swift | 1 | 8321 | //
// Availability.swift
// PullToRefreshKit
//
// Created by Leo on 2017/11/9.
// Copyright © 2017年 Leo Huang. All rights reserved.
//
import Foundation
import UIKit
public protocol SetUp {}
public extension SetUp where Self: AnyObject {
@discardableResult
@available(*, deprecated, message: "This method will be removed at V 1.0.0")
func SetUp(_ closure: (Self) -> Void) -> Self {
closure(self)
return self
}
}
extension NSObject: SetUp {}
//Header
public extension UIScrollView{
@discardableResult
@available(*, deprecated, message: "Use new API at PullToRefresh.Swift")
func setUpHeaderRefresh(_ action:@escaping ()->())->DefaultRefreshHeader{
let header = DefaultRefreshHeader(frame:CGRect(x: 0,
y: 0,
width: self.frame.width,
height: PullToRefreshKitConst.defaultHeaderHeight))
return setUpHeaderRefresh(header, action: action)
}
@discardableResult
@available(*, deprecated, message: "Use new API at PullToRefresh.Swift")
func setUpHeaderRefresh<T:UIView>(_ header:T,action:@escaping ()->())->T where T:RefreshableHeader{
let oldContain = self.viewWithTag(PullToRefreshKitConst.headerTag)
oldContain?.removeFromSuperview()
let containFrame = CGRect(x: 0, y: -self.frame.height, width: self.frame.width, height: self.frame.height)
let containComponent = RefreshHeaderContainer(frame: containFrame)
if let endDuration = header.durationOfHideAnimation?(){
containComponent.durationOfEndRefreshing = endDuration
}
containComponent.tag = PullToRefreshKitConst.headerTag
containComponent.refreshAction = action
self.addSubview(containComponent)
containComponent.delegate = header
header.autoresizingMask = [.flexibleWidth,.flexibleHeight]
let bounds = CGRect(x: 0,y: containFrame.height - header.frame.height,width: self.frame.width,height: header.frame.height)
header.frame = bounds
containComponent.addSubview(header)
return header
}
@available(*, deprecated, message: "Use new API at PullToRefresh.Swift")
func beginHeaderRefreshing(){
let header = self.viewWithTag(PullToRefreshKitConst.headerTag) as? RefreshHeaderContainer
header?.beginRefreshing()
}
@available(*, deprecated, message: "Use new API at PullToRefresh.Swift")
func endHeaderRefreshing(_ result:RefreshResult = .none,delay:Double = 0.0){
let header = self.viewWithTag(PullToRefreshKitConst.headerTag) as? RefreshHeaderContainer
header?.endRefreshing(result,delay: delay)
}
}
//Footer
public extension UIScrollView{
@discardableResult
@available(*, deprecated, message: "Use new API at PullToRefresh.Swift")
func setUpFooterRefresh(_ action:@escaping ()->())->DefaultRefreshFooter{
let footer = DefaultRefreshFooter(frame: CGRect(x: 0,
y: 0,
width: self.frame.width,
height: PullToRefreshKitConst.defaultFooterHeight))
return setUpFooterRefresh(footer, action: action)
}
@discardableResult
@available(*, deprecated, message: "Use new API at PullToRefresh.Swift")
func setUpFooterRefresh<T:UIView>(_ footer:T,action:@escaping ()->())->T where T:RefreshableFooter{
let oldContain = self.viewWithTag(PullToRefreshKitConst.footerTag)
oldContain?.removeFromSuperview()
let frame = CGRect(x: 0,y: 0,width: self.frame.width, height: PullToRefreshKitConst.defaultFooterHeight)
let containComponent = RefreshFooterContainer(frame: frame)
containComponent.tag = PullToRefreshKitConst.footerTag
containComponent.refreshAction = action
self.insertSubview(containComponent, at: 0)
containComponent.delegate = footer
footer.autoresizingMask = [.flexibleWidth,.flexibleHeight]
footer.frame = containComponent.bounds
containComponent.addSubview(footer)
return footer
}
@available(*, deprecated, message: "Use new API at PullToRefresh.Swift")
func beginFooterRefreshing(){
let footer = self.viewWithTag(PullToRefreshKitConst.footerTag) as? RefreshFooterContainer
if footer?.state == .idle {
footer?.beginRefreshing()
}
}
@available(*, deprecated, message: "Use new API at PullToRefresh.Swift")
func endFooterRefreshing(){
let footer = self.viewWithTag(PullToRefreshKitConst.footerTag) as? RefreshFooterContainer
footer?.endRefreshing()
}
@available(*, deprecated, message: "Use new API at PullToRefresh.Swift")
func setFooterNoMoreData(){
let footer = self.viewWithTag(PullToRefreshKitConst.footerTag) as? RefreshFooterContainer
footer?.endRefreshing()
}
@available(*, deprecated, message: "Use new API at PullToRefresh.Swift")
func resetFooterToDefault(){
let footer = self.viewWithTag(PullToRefreshKitConst.footerTag) as? RefreshFooterContainer
footer?.resetToDefault()
}
@available(*, deprecated, message: "Use new API at PullToRefresh.Swift")
func endFooterRefreshingWithNoMoreData(){
let footer = self.viewWithTag(PullToRefreshKitConst.footerTag) as? RefreshFooterContainer
footer?.endRefreshing()
footer?.updateToNoMoreData()
}
}
//Left
extension UIScrollView{
@discardableResult
@available(*, deprecated, message: "Use new API at PullToRefresh.Swift")
public func setUpLeftRefresh(_ action: @escaping ()->())->DefaultRefreshLeft{
let left = DefaultRefreshLeft(frame: CGRect(x: 0,y: 0,width: PullToRefreshKitConst.defaultLeftWidth, height: self.frame.height))
return setUpLeftRefresh(left, action: action)
}
@discardableResult
@available(*, deprecated, message: "Use new API at PullToRefresh.Swift")
public func setUpLeftRefresh<T:UIView>(_ left:T,action:@escaping ()->())->T where T:RefreshableLeftRight{
let oldContain = self.viewWithTag(PullToRefreshKitConst.leftTag)
oldContain?.removeFromSuperview()
let frame = CGRect(x: -1.0 * PullToRefreshKitConst.defaultLeftWidth,y: 0,width: PullToRefreshKitConst.defaultLeftWidth, height: self.frame.height)
let containComponent = RefreshLeftContainer(frame: frame)
containComponent.tag = PullToRefreshKitConst.leftTag
containComponent.refreshAction = action
self.insertSubview(containComponent, at: 0)
containComponent.delegate = left
left.autoresizingMask = [.flexibleWidth,.flexibleHeight]
left.frame = containComponent.bounds
containComponent.addSubview(left)
return left
}
}
//Right
extension UIScrollView{
@discardableResult
@available(*, deprecated, message: "Use new API at PullToRefresh.Swift")
public func setUpRightRefresh(_ action:@escaping ()->())->DefaultRefreshRight{
let right = DefaultRefreshRight(frame: CGRect(x: 0 ,y: 0 ,width: PullToRefreshKitConst.defaultLeftWidth ,height: self.frame.height ))
return setUpRightRefresh(right, action: action)
}
@discardableResult
@available(*, deprecated, message: "Use new API at PullToRefresh.Swift")
public func setUpRightRefresh<T:UIView>(_ right:T,action:@escaping ()->())->T where T:RefreshableLeftRight{
let oldContain = self.viewWithTag(PullToRefreshKitConst.rightTag)
oldContain?.removeFromSuperview()
let frame = CGRect(x: 0 ,y: 0 ,width: PullToRefreshKitConst.defaultLeftWidth ,height: self.frame.height )
let containComponent = RefreshRightContainer(frame: frame)
containComponent.tag = PullToRefreshKitConst.rightTag
containComponent.refreshAction = action
self.insertSubview(containComponent, at: 0)
containComponent.delegate = right
right.autoresizingMask = [.flexibleWidth,.flexibleHeight]
right.frame = containComponent.bounds
containComponent.addSubview(right)
return right
}
}
| mit | 9092d6c6414e1f02ff889ac41ac96a2b | 44.703297 | 154 | 0.67925 | 5.205257 | false | false | false | false |
xiabob/ZhiHuDaily | ZhiHuDaily/ZhiHuDaily/Frameworks/XBCycleView/XBImageDownloader.swift | 3 | 3546 | //
// XBImageDownloader.swift
// XBCycleView
//
// Created by xiabob on 16/6/13.
// Copyright © 2016年 xiabob. All rights reserved.
//
import UIKit
public typealias finishClosure = (_ image: UIImage?) -> ()
open class XBImageDownloader: NSObject {
fileprivate lazy var imageCache: NSCache<AnyObject, UIImage> = {
let cache = NSCache<AnyObject, UIImage>()
cache.countLimit = 10
return cache
}()
fileprivate lazy var imageCacheDir: String = {
var dirString = ""
if let dir = NSSearchPathForDirectoriesInDomains(.cachesDirectory,
.userDomainMask,
true).last {
dirString = dir + "/XBImageDownloaderCache"
}
return dirString
}()
override init() {
super.init()
commonInit()
}
fileprivate func commonInit() {
let isCacheDirExist = FileManager.default.fileExists(atPath: imageCacheDir)
if !isCacheDirExist {
do {
try FileManager.default.createDirectory(atPath: imageCacheDir, withIntermediateDirectories: true, attributes: nil)
} catch {
print("XBImageDownloaderCache dir create error")
}
}
}
fileprivate func getImageFromLocal(_ url: String) -> UIImage? {
let path = imageCacheDir + "/" + url.xb_MD5
if let data = try? Data(contentsOf: URL(fileURLWithPath: path)) {
return UIImage(data: data)
} else {
return nil
}
}
open func getImageWithUrl(urlString url: String, completeClosure closure: @escaping finishClosure) {
//first get image from memory
if let image = imageCache.object(forKey: url as AnyObject) {
closure(image)
return
}
//second get image from local
if let image = getImageFromLocal(url) {
//save to memory
imageCache.setObject(image, forKey: url as AnyObject)
closure(image)
return
}
//last get image from network
let queue = DispatchQueue(label: "com.xiabob.XBCycleView", attributes: DispatchQueue.Attributes.concurrent)
queue.async { [unowned self] in
if let imageUrl = URL(string: url) {
if let imageData = try? Data(contentsOf: imageUrl) {
//save to disk
try? imageData.write(to: URL(fileURLWithPath: self.imageCacheDir + "/" + url.xb_MD5), options: [.atomic])
let image = UIImage(data: imageData)
if image != nil {
//save to memory
self.imageCache.setObject(image!, forKey: url as AnyObject)
}
DispatchQueue.main.async(execute: {
closure(image)
})
return
}
}
}
}
open func clearCachedImages() {
do {
let paths = try FileManager.default.contentsOfDirectory(atPath: imageCacheDir)
for path in paths {
try FileManager.default.removeItem(atPath: imageCacheDir + "/" + path)
}
} catch {
print("XBImageDownloaderCache dir remove error")
}
}
}
| mit | f6c06e4a49028f4ba656cd6aad99b878 | 31.209091 | 131 | 0.520181 | 5.351964 | false | false | false | false |
watson-developer-cloud/ios-sdk | Sources/DiscoveryV1/Models/AggregationResult.swift | 1 | 1811 | /**
* (C) Copyright IBM Corp. 2018, 2020.
*
* 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
/**
Aggregation results for the specified query.
*/
public struct AggregationResult: Codable, Equatable {
/**
Key that matched the aggregation type.
*/
public var key: String?
/**
Number of matching results.
*/
public var matchingResults: Int?
/**
Aggregations returned in the case of chained aggregations.
*/
public var aggregations: [QueryAggregation]?
// Map each property name to the key that shall be used for encoding/decoding.
private enum CodingKeys: String, CodingKey {
case key = "key"
case matchingResults = "matching_results"
case aggregations = "aggregations"
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
if let keyAsString = try? container.decode(String.self, forKey: .key) { key = keyAsString }
if let keyAsInt = try? container.decode(Int.self, forKey: .key) { key = "\(keyAsInt)" }
matchingResults = try container.decodeIfPresent(Int.self, forKey: .matchingResults)
aggregations = try container.decodeIfPresent([QueryAggregation].self, forKey: .aggregations)
}
}
| apache-2.0 | bd11b8afa73730f2090d6da0a3d3229c | 33.169811 | 100 | 0.692435 | 4.406326 | false | false | false | false |
dreamsxin/swift | test/SILGen/implicitly_unwrapped_optional.swift | 2 | 2404 | // RUN: %target-swift-frontend -emit-silgen %s | FileCheck %s
func foo(f f: (() -> ())!) {
var f: (() -> ())! = f
f?()
}
// CHECK: sil hidden @{{.*}}foo{{.*}} : $@convention(thin) (@owned ImplicitlyUnwrappedOptional<() -> ()>) -> () {
// CHECK: bb0([[T0:%.*]] : $ImplicitlyUnwrappedOptional<() -> ()>):
// CHECK: [[F:%.*]] = alloc_box $ImplicitlyUnwrappedOptional<() -> ()>
// CHECK-NEXT: [[PF:%.*]] = project_box [[F]]
// CHECK: store [[T0]] to [[PF]]
// CHECK: [[T1:%.*]] = select_enum_addr [[PF]]
// CHECK-NEXT: cond_br [[T1]], bb1, bb3
// If it does, project and load the value out of the implicitly unwrapped
// optional...
// CHECK: bb1:
// CHECK-NEXT: [[FN0_ADDR:%.*]] = unchecked_take_enum_data_addr [[PF]]
// CHECK-NEXT: [[FN0:%.*]] = load [[FN0_ADDR]]
// ...unnecessarily reabstract back to () -> ()...
// CHECK: [[T0:%.*]] = function_ref @_TTRXFo_iT__iT__XFo___ : $@convention(thin) (@owned @callee_owned (@in ()) -> @out ()) -> ()
// CHECK-NEXT: [[FN1:%.*]] = partial_apply [[T0]]([[FN0]])
// .... then call it
// CHECK-NEXT: apply [[FN1]]()
// CHECK: br bb2
// (first nothing block)
// CHECK: bb3:
// CHECK-NEXT: enum $Optional<()>, #Optional.none!enumelt
// CHECK-NEXT: br bb2
// The rest of this is tested in optional.swift
func wrap<T>(x x: T) -> T! { return x }
// CHECK-LABEL: sil hidden @_TF29implicitly_unwrapped_optional16wrap_then_unwrap
func wrap_then_unwrap<T>(x x: T) -> T {
// CHECK: [[FORCE:%.*]] = function_ref @_TFs45_stdlib_ImplicitlyUnwrappedOptional_unwrappedurFGSQx_x
// CHECK: apply [[FORCE]]<{{.*}}>(%0, {{%.*}})
return wrap(x: x)!
}
// CHECK-LABEL: sil hidden @_TF29implicitly_unwrapped_optional10tuple_bindFT1xGSQTSiSS___GSqSS_ : $@convention(thin) (@owned ImplicitlyUnwrappedOptional<(Int, String)>) -> @owned Optional<String> {
func tuple_bind(x x: (Int, String)!) -> String? {
return x?.1
// CHECK: cond_br {{%.*}}, [[NONNULL:bb[0-9]+]], [[NULL:bb[0-9]+]]
// CHECK: [[NONNULL]]:
// CHECK: [[STRING:%.*]] = tuple_extract {{%.*}} : $(Int, String), 1
// CHECK-NOT: release_value [[STRING]]
}
// CHECK-LABEL: sil hidden @_TF29implicitly_unwrapped_optional31tuple_bind_implicitly_unwrappedFT1xGSQTSiSS___SS
func tuple_bind_implicitly_unwrapped(x x: (Int, String)!) -> String {
return x.1
}
func return_any() -> AnyObject! { return nil }
func bind_any() {
let object : AnyObject? = return_any()
}
| apache-2.0 | 3383b8531802fcb9bfb77718b4e23626 | 41.175439 | 197 | 0.591514 | 3.196809 | false | false | false | false |
Hamuko/Nullpo | Nullpo/PreferenceController.swift | 1 | 2347 | import Cocoa
class PreferenceController: NSWindowController {
@IBOutlet weak var backgroundLinkCheckbox: NSButton!
@IBOutlet weak var uploaderList: NSPopUpButton!
@IBOutlet weak var concurrentStepper: NSStepper!
dynamic var concurrentUploadCount = 4
convenience init() {
self.init(windowNibName: "PreferenceController")
}
override func windowDidLoad() {
super.windowDidLoad()
populateUploaderList()
loadUserPreferences()
}
/// Opening links in background was changed via the checkbox.
@IBAction func changedBackgroundLinks(sender: AnyObject) {
let defaults: NSUserDefaults = NSUserDefaults.standardUserDefaults()
let openLinksInBackground: Bool = Bool(backgroundLinkCheckbox.state)
defaults.setBool(openLinksInBackground, forKey: "OpenLinksInBackground")
}
@IBAction func changedConcurrentUploadCount(sender: AnyObject) {
let defaults: NSUserDefaults = NSUserDefaults.standardUserDefaults()
defaults.setInteger(sender.integerValue, forKey: "ConcurrentUploadJobs")
}
/// Uploader was changed using the pop-up button.
@IBAction func changedUploader(sender: AnyObject) {
let defaults: NSUserDefaults = NSUserDefaults.standardUserDefaults()
let selectedUploader: String = uploaderList.selectedItem!.title
defaults.setObject(selectedUploader, forKey: "Uploader")
}
/// Populate the settings window with NSUserDefaults values.
func loadUserPreferences() {
let defaults: NSUserDefaults = NSUserDefaults.standardUserDefaults()
var concurrentUploads: Int = defaults.integerForKey("ConcurrentUploadJobs")
let openLinksInBackground: Bool = defaults.boolForKey("OpenLinksInBackground")
let uploaderName: String = defaults.objectForKey("Uploader") as? String ?? "Uguu"
if concurrentUploads <= 0 || concurrentUploads > 64 {
concurrentUploads = 1
}
backgroundLinkCheckbox.state = Int(openLinksInBackground)
concurrentUploadCount = concurrentUploads
uploaderList.selectItem(uploaderList.itemWithTitle(uploaderName))
}
/// Add keys from Uploaders.plist to the pop-up button.
func populateUploaderList() {
uploaderList.addItemsWithTitles(Array(UploadGroup.uploaders.keys))
}
}
| apache-2.0 | 9f48ad89fc25f4d07d79bddbbb9fb180 | 38.116667 | 89 | 0.722199 | 5.227171 | false | false | false | false |
couchbase/couchbase-lite-ios | Swift/CollectionConfiguration.swift | 1 | 3555 | //
// CollectionConfiguration.swift
// CouchbaseLite
//
// Copyright (c) 2017 Couchbase, Inc 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
/// The collection configuration that can be configured specifically for the replication.
public struct CollectionConfiguration {
/// The custom conflict resolver function. If this value is nil, the default conflict resolver will be used..
public var conflictResolver: ConflictResolverProtocol?
/// Filter function for validating whether the documents can be pushed to the remote endpoint.
/// Only documents of which the function returns true are replicated.
public var pushFilter: ReplicationFilter?
/// Filter function for validating whether the documents can be pulled from the remote endpoint.
/// Only documents of which the function returns true are replicated.
public var pullFilter: ReplicationFilter?
/// Channels filter for specifying the channels for the pull the replicator will pull from. For any
/// collections that do not have the channels filter specified, all accessible channels will be pulled. Push
/// replicator will ignore this filter.
public var channels: Array<String>?
/// Document IDs filter to limit the documents in the collection to be replicated with the remote endpoint.
/// If not specified, all docs in the collection will be replicated.
public var documentIDs: Array<String>?
public init() {
self.init(config: nil)
}
// MARK: internal
init(config: CollectionConfiguration?) {
if let config = config {
self.conflictResolver = config.conflictResolver
self.pushFilter = config.pushFilter
self.pullFilter = config.pullFilter
self.channels = config.channels
self.documentIDs = config.documentIDs
}
}
func toImpl(_ collection: Collection) -> CBLCollectionConfiguration {
let c = CBLCollectionConfiguration()
c.channels = self.channels
c.documentIDs = self.documentIDs
if let pushFilter = self.filter(push: true, collection: collection) {
c.pushFilter = pushFilter
}
if let pullFilter = self.filter(push: false, collection: collection) {
c.pullFilter = pullFilter
}
if let resolver = self.conflictResolver {
c.setConflictResolverUsing { (conflict) -> CBLDocument? in
return resolver.resolve(conflict: Conflict(impl: conflict, collection: collection))?.impl
}
}
return c
}
func filter(push: Bool, collection: Collection) -> ((CBLDocument, CBLDocumentFlags) -> Bool)? {
guard let f = push ? self.pushFilter : self.pullFilter else {
return nil
}
return { (doc, flags) in
return f(Document(doc, collection: collection), DocumentFlags(rawValue: Int(flags.rawValue)))
}
}
}
| apache-2.0 | 05b84818c20de6f39dbf1a7c946dcfb4 | 38.065934 | 113 | 0.673136 | 4.843324 | false | true | false | false |
jdkelley/Udacity-VirtualTourist | VirtualTourist/VirtualTourist/FlickrClient.swift | 1 | 7256 | //
// FlickrClient.swift
// VirtualTourist
//
// Created by Joshua Kelley on 10/19/16.
// Copyright © 2016 Joshua Kelley. All rights reserved.
//
import Foundation
import UIKit
class FlickrClient {
// MARK: - Singleton
/// A shared and threadsafe instance of FlickrClient
static let sharedInstance = FlickrClient()
private init() {}
// MARK: Search By Location
func imageSearchByLocation() {
// get lat and long
let lat = 36.2
let lon = 81.7
// get urls
taskForGet(latitude: lat, longitude: lon) { (data, error) in
if let error = error {
if error is ImageDownloadError {
} else if error is GetRequestError {
} else if error is URLRequestParseToJSONError {
}
} else {
guard let result = data as? [String: Any] else {
let notDictionary = FlickrDeserializationError(kind: .resultNotDictionary, message: "Results could not be cast as the expected JSON object.", data: data)
return
}
guard let photosObject = result[ResponseKeys.photos] as? [String: Any] else {
let noPhotosResult = FlickrDeserializationError(kind: .photosResultObjectNotResolvable, message: "Photos Object Does Not Exist.", data: result)
return
}
guard let photoArray = photosObject[ResponseKeys.photo] as? [[String: Any]] else {
let photoObjectArrayDNE = FlickrDeserializationError(kind: .photoDictionaryDoesNotExist, message: "Dictionary of photo objects does not exist.", data: photosObject)
return
}
let array: [String] = photoArray.flatMap {
guard let urlString = $0[FlickrClient.ResponseKeys.url_m] as? String else {
return nil
}
return urlString
}
// Do something with the array of urls
}
}
}
// MARK: Task For GET
func taskForGet(latitude: Double, longitude: Double, completionHandlerForGet: @escaping CompletionHandlerForGet) -> URLSessionDataTask {
let url = flickrUrl(latitude: latitude, longitude: longitude)
let request = URLRequest(url: url)
let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
guard error == nil else {
let getError = GetRequestError(kind: .errorInResponse, message: "There was an error with your request.", url: url.absoluteString, errorMessage: "\(error!)")
completionHandlerForGet(nil, getError)
return
}
guard let statusCode = (response as? HTTPURLResponse)?.statusCode, statusCode >= 200 && statusCode < 300 else {
let getError = GetRequestError(kind: .non200Response, message: "Request returned something other than a 2xx response.", url: url.absoluteString, errorMessage: "")
completionHandlerForGet(nil, getError)
return
}
guard let unwrappedData = data else {
let getError = GetRequestError(kind: .noData, message: "No Data was returned from your request!", url: url.absoluteString, errorMessage: "")
completionHandlerForGet(nil, getError)
return
}
self.convert(data: unwrappedData, with: completionHandlerForGet)
}
task.resume()
return task
}
func convert(data: Data, with: CompletionHandlerForGet) {
var parsedResult: Any!
do {
parsedResult = try JSONSerialization.jsonObject(with: data, options: .allowFragments)
} catch {
let deserializeError = URLRequestParseToJSONError(kind: .unparsableToJSON, message: "Could not parse the data as JSON.", data: data)
with(nil, deserializeError)
return
}
with(parsedResult, nil)
}
func fetchImageFor(url: URL, completion: @escaping DownloadedImageHandler) {
}
}
// MARK: - Convenience
extension FlickrClient {
/// Builds a URL to request a latitude/longitude search from Flickr.
///
/// - parameter latitude: The latitude to search at.
/// - parameter longitude: The longitude to search at.
///
/// - returns: A valid URL.
fileprivate func flickrUrl(latitude: Double, longitude: Double) -> URL {
let parameters: [String: Any] = [
ParameterKeys.method : ParameterValues.searchMethod,
ParameterKeys.apiKey : AppConstants.FlickrAPIKey,
ParameterKeys.safeSearch : ParameterValues.safeSearch,
ParameterKeys.extras : ParameterValues.extras,
ParameterKeys.format : ParameterValues.format,
ParameterKeys.nojsoncallback : ParameterValues.nojsoncallback,
ParameterKeys.bbox : bboxString(latitude: latitude, longitude: longitude),
ParameterKeys.lat : latitude,
ParameterKeys.lon : longitude
]
return flickrUrlFrom(parameters: parameters)
}
/// Builds a valid `URL` instance from query parameters and url components.
///
/// - parameter parameters: This is a `[String: Any]` dictionary that holds the key-value pairs that will be `URLQueryItems`.
///
/// - returns: A valid URL.
fileprivate func flickrUrlFrom(parameters: [String: Any]) -> URL {
var components = URLComponents()
components.scheme = Constants.apiScheme
components.host = Constants.apiHost
components.path = Constants.apiPath
components.queryItems = [URLQueryItem]()
for (key, value) in parameters {
let queryItem = URLQueryItem(name: key, value: "\(value)")
components.queryItems!.append(queryItem)
}
return components.url!
}
/// `bboxString` creates a url-safe bounding box parameter.
///
/// - parameter latitude: The center coordinate's latitude of the bounding box
/// - parameter longitude: The center coordinate's longitude of the bounding box
///
/// - returns: A string describing the bounding box ready to be passed as a url parameter.
fileprivate func bboxString(latitude: Double, longitude: Double) -> String {
let minLon = max(longitude - Constants.searchBBoxHalfWidth, Constants.searchLonRange.0)
let minLat = max(latitude - Constants.searchBBoxHalfHeight,Constants.searchLatRange.0)
let maxLon = min(longitude + Constants.searchBBoxHalfWidth,Constants.searchLonRange.1)
let maxLat = min(latitude + Constants.searchBBoxHalfHeight, Constants.searchLatRange.1)
return "\(minLon),\(minLat),\(maxLon),\(maxLat)"
}
}
| mit | 57e19c037004065ffafca7697c5d402b | 39.305556 | 184 | 0.588973 | 5.152699 | false | false | false | false |
slavapestov/swift | test/SILGen/writeback_conflict_diagnostics.swift | 7 | 4944 | // RUN: %target-swift-frontend %s -o /dev/null -emit-silgen -verify
struct MutatorStruct {
mutating func f(inout x : MutatorStruct) {}
}
var global_property : MutatorStruct { get {} set {} }
var global_int_property : Int {
get { return 42 }
set {}
}
struct StructWithProperty {
var computed_int : Int {
get { return 42 }
set {}
}
var stored_int = 0
var computed_struct : MutatorStruct { get {} set {} }
}
var global_struct_property : StructWithProperty
var c_global_struct_property : StructWithProperty { get {} set {} }
func testInOutAlias() {
var x = 42
swap(&x, // expected-note {{previous aliasing argument}}
&x) // expected-error {{inout arguments are not allowed to alias each other}}
swap(&global_struct_property, // expected-note {{previous aliasing argument}}
&global_struct_property) // expected-error {{inout arguments are not allowed to alias each other}}
}
func testWriteback() {
var a = StructWithProperty()
a.computed_struct . // expected-note {{concurrent writeback occurred here}}
f(&a.computed_struct) // expected-error {{inout writeback to computed property 'computed_struct' occurs in multiple arguments to call, introducing invalid aliasing}}
swap(&global_struct_property.stored_int,
&global_struct_property.stored_int) // ok
swap(&global_struct_property.computed_int, // expected-note {{concurrent writeback occurred here}}
&global_struct_property.computed_int) // expected-error {{inout writeback to computed property 'computed_int' occurs in multiple arguments to call, introducing invalid aliasing}}
swap(&a.computed_int, // expected-note {{concurrent writeback occurred here}}
&a.computed_int) // expected-error {{inout writeback to computed property 'computed_int' occurs in multiple arguments to call, introducing invalid aliasing}}
global_property.f(&global_property) // expected-error {{inout writeback to computed property 'global_property' occurs in multiple arguments to call, introducing invalid aliasing}} expected-note {{concurrent writeback occurred here}}
a.computed_struct.f(&a.computed_struct) // expected-error {{inout writeback to computed property 'computed_struct' occurs in multiple arguments to call, introducing invalid aliasing}} expected-note {{concurrent writeback occurred here}}
}
func testComputedStructWithProperty() {
swap(&c_global_struct_property.stored_int, &c_global_struct_property.stored_int) // expected-error {{inout writeback to computed property 'c_global_struct_property' occurs in multiple arguments to call, introducing invalid aliasing}} expected-note {{concurrent writeback occurred here}}
var c_local_struct_property : StructWithProperty { get {} set {} }
swap(&c_local_struct_property.stored_int, &c_local_struct_property.stored_int) // expected-error {{inout writeback to computed property 'c_local_struct_property' occurs in multiple arguments to call, introducing invalid aliasing}} expected-note {{concurrent writeback occurred here}}
swap(&c_local_struct_property.stored_int, &c_global_struct_property.stored_int) // ok
}
var global_array : [[Int]]
func testMultiArray(i : Int, j : Int, array : [[Int]]) {
var array = array
swap(&array[i][j],
&array[i][i])
swap(&array[0][j],
&array[0][i])
swap(&global_array[0][j],
&global_array[0][i])
// TODO: This is obviously the same writeback problem, but isn't detectable
// with the current level of sophistication in SILGen.
swap(&array[1+0][j], &array[1+0][i])
swap(&global_array[0][j], &array[j][i]) // ok
}
struct ArrayWithoutAddressors<T> {
subscript(i: Int) -> T {
get { return value }
set {}
}
var value: T
}
var global_array_without_addressors: ArrayWithoutAddressors<ArrayWithoutAddressors<Int>>
func testMultiArrayWithoutAddressors(
i: Int, j: Int, array: ArrayWithoutAddressors<ArrayWithoutAddressors<Int>>
) {
var array = array
swap(&array[i][j], // expected-note {{concurrent writeback occurred here}}
&array[i][i]) // expected-error {{inout writeback through subscript occurs in multiple arguments to call, introducing invalid aliasing}}
swap(&array[0][j], // expected-note {{concurrent writeback occurred here}}
&array[0][i]) // expected-error {{inout writeback through subscript occurs in multiple arguments to call, introducing invalid aliasing}}
swap(&global_array_without_addressors[0][j], // expected-note {{concurrent writeback occurred here}}
&global_array_without_addressors[0][i]) // expected-error {{inout writeback through subscript occurs in multiple arguments to call, introducing invalid aliasing}}
// TODO: This is obviously the same writeback problem, but isn't detectable
// with the current level of sophistication in SILGen.
swap(&array[1+0][j], &array[1+0][i])
swap(&global_array_without_addressors[0][j], &array[j][i]) // ok
}
| apache-2.0 | 3b7b2c032332025bcc2d0da81b70eda8 | 42.752212 | 290 | 0.713794 | 3.902131 | false | false | false | false |
mrgerych/Cuckoo | Tests/Matching/ParameterMatcherTest.swift | 2 | 859 | //
// ParameterMatcherTest.swift
// Cuckoo
//
// Created by Filip Dolnik on 05.07.16.
// Copyright © 2016 Brightify. All rights reserved.
//
import XCTest
import Cuckoo
class ParameterMatcherTest: XCTestCase {
func testMatches() {
let matcher = ParameterMatcher { $0 == 5 }
XCTAssertTrue(matcher.matches(5))
XCTAssertFalse(matcher.matches(4))
}
func testOr() {
let matcher = ParameterMatcher { $0 == 5 }.or(ParameterMatcher { $0 == 4 })
XCTAssertTrue(matcher.matches(5))
XCTAssertTrue(matcher.matches(4))
XCTAssertFalse(matcher.matches(3))
}
func testAnd() {
let matcher = ParameterMatcher { $0 > 3 }.and(ParameterMatcher { $0 < 5 })
XCTAssertTrue(matcher.matches(4))
XCTAssertFalse(matcher.matches(3))
}
} | mit | f5604d15faada44ec7c894e454f904ec | 23.542857 | 83 | 0.602564 | 4.4 | false | true | false | false |
vbicer/RealmStore | Carthage/Checkouts/realm-cocoa/Realm/Tests/Swift/SwiftObjectInterfaceTests.swift | 2 | 11354 | ////////////////////////////////////////////////////////////////////////////
//
// Copyright 2014 Realm Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////
import XCTest
import Realm
import Foundation
class OuterClass {
class InnerClass {
}
}
class SwiftStringObjectSubclass : SwiftStringObject {
@objc dynamic var stringCol2 = ""
}
class SwiftSelfRefrencingSubclass: SwiftStringObject {
@objc dynamic var objects = RLMArray<SwiftSelfRefrencingSubclass>(objectClassName: SwiftSelfRefrencingSubclass.className())
}
class SwiftDefaultObject: RLMObject {
@objc dynamic var intCol = 1
@objc dynamic var boolCol = true
override class func defaultPropertyValues() -> [AnyHashable : Any]? {
return ["intCol": 2]
}
}
class SwiftOptionalNumberObject: RLMObject {
@objc dynamic var intCol: NSNumber? = 1
@objc dynamic var floatCol: NSNumber? = 2.2 as Float as NSNumber
@objc dynamic var doubleCol: NSNumber? = 3.3
@objc dynamic var boolCol: NSNumber? = true
}
class SwiftObjectInterfaceTests: RLMTestCase {
// Swift models
func testSwiftObject() {
let realm = realmWithTestPath()
realm.beginWriteTransaction()
let obj = SwiftObject()
realm.add(obj)
obj.boolCol = true
obj.intCol = 1234
obj.floatCol = 1.1
obj.doubleCol = 2.2
obj.stringCol = "abcd"
obj.binaryCol = "abcd".data(using: String.Encoding.utf8)
obj.dateCol = Date(timeIntervalSince1970: 123)
obj.objectCol = SwiftBoolObject()
obj.objectCol.boolCol = true
obj.arrayCol.add(obj.objectCol)
try! realm.commitWriteTransaction()
let data = "abcd".data(using: String.Encoding.utf8)
let firstObj = SwiftObject.allObjects(in: realm).firstObject() as! SwiftObject
XCTAssertEqual(firstObj.boolCol, true, "should be true")
XCTAssertEqual(firstObj.intCol, 1234, "should be 1234")
XCTAssertEqual(firstObj.floatCol, Float(1.1), "should be 1.1")
XCTAssertEqual(firstObj.doubleCol, 2.2, "should be 2.2")
XCTAssertEqual(firstObj.stringCol, "abcd", "should be abcd")
XCTAssertEqual(firstObj.binaryCol!, data!)
XCTAssertEqual(firstObj.dateCol, Date(timeIntervalSince1970: 123), "should be epoch + 123")
XCTAssertEqual(firstObj.objectCol.boolCol, true, "should be true")
XCTAssertEqual(obj.arrayCol.count, UInt(1), "array count should be 1")
XCTAssertEqual(obj.arrayCol.firstObject()!.boolCol, true, "should be true")
}
func testDefaultValueSwiftObject() {
let realm = realmWithTestPath()
realm.beginWriteTransaction()
realm.add(SwiftObject())
try! realm.commitWriteTransaction()
let data = "a".data(using: String.Encoding.utf8)
let firstObj = SwiftObject.allObjects(in: realm).firstObject() as! SwiftObject
XCTAssertEqual(firstObj.boolCol, false, "should be false")
XCTAssertEqual(firstObj.intCol, 123, "should be 123")
XCTAssertEqual(firstObj.floatCol, Float(1.23), "should be 1.23")
XCTAssertEqual(firstObj.doubleCol, 12.3, "should be 12.3")
XCTAssertEqual(firstObj.stringCol, "a", "should be a")
XCTAssertEqual(firstObj.binaryCol!, data!)
XCTAssertEqual(firstObj.dateCol, Date(timeIntervalSince1970: 1), "should be epoch + 1")
XCTAssertEqual(firstObj.objectCol.boolCol, false, "should be false")
XCTAssertEqual(firstObj.arrayCol.count, UInt(0), "array count should be zero")
}
func testMergedDefaultValuesSwiftObject() {
let realm = self.realmWithTestPath()
realm.beginWriteTransaction()
_ = SwiftDefaultObject.create(in: realm, withValue: NSDictionary())
try! realm.commitWriteTransaction()
let object = SwiftDefaultObject.allObjects(in: realm).firstObject() as! SwiftDefaultObject
XCTAssertEqual(object.intCol, 2, "defaultPropertyValues should override native property default value")
XCTAssertEqual(object.boolCol, true, "native property default value should be used if defaultPropertyValues doesn't contain that key")
}
func testSubclass() {
// test className methods
XCTAssertEqual("SwiftStringObject", SwiftStringObject.className())
XCTAssertEqual("SwiftStringObjectSubclass", SwiftStringObjectSubclass.className())
let realm = RLMRealm.default()
realm.beginWriteTransaction()
_ = SwiftStringObject.createInDefaultRealm(withValue: ["string"])
_ = SwiftStringObjectSubclass.createInDefaultRealm(withValue: ["string", "string2"])
try! realm.commitWriteTransaction()
// ensure creation in proper table
XCTAssertEqual(UInt(1), SwiftStringObjectSubclass.allObjects().count)
XCTAssertEqual(UInt(1), SwiftStringObject.allObjects().count)
try! realm.transaction {
// create self referencing subclass
let sub = SwiftSelfRefrencingSubclass.createInDefaultRealm(withValue: ["string", []])
let sub2 = SwiftSelfRefrencingSubclass()
sub.objects.add(sub2)
}
}
func testOptionalNSNumberProperties() {
let realm = realmWithTestPath()
let no = SwiftOptionalNumberObject()
XCTAssertEqual([.int, .float, .double, .bool], no.objectSchema.properties.map { $0.type })
XCTAssertEqual(1, no.intCol!)
XCTAssertEqual(2.2 as Float as NSNumber, no.floatCol!)
XCTAssertEqual(3.3, no.doubleCol!)
XCTAssertEqual(true, no.boolCol!)
try! realm.transaction {
realm.add(no)
no.intCol = nil
no.floatCol = nil
no.doubleCol = nil
no.boolCol = nil
}
XCTAssertNil(no.intCol)
XCTAssertNil(no.floatCol)
XCTAssertNil(no.doubleCol)
XCTAssertNil(no.boolCol)
try! realm.transaction {
no.intCol = 1.1
no.floatCol = 2.2 as Float as NSNumber
no.doubleCol = 3.3
no.boolCol = false
}
XCTAssertEqual(1, no.intCol!)
XCTAssertEqual(2.2 as Float as NSNumber, no.floatCol!)
XCTAssertEqual(3.3, no.doubleCol!)
XCTAssertEqual(false, no.boolCol!)
}
func testOptionalSwiftProperties() {
let realm = realmWithTestPath()
try! realm.transaction { realm.add(SwiftOptionalObject()) }
let firstObj = SwiftOptionalObject.allObjects(in: realm).firstObject() as! SwiftOptionalObject
XCTAssertNil(firstObj.optObjectCol)
XCTAssertNil(firstObj.optStringCol)
XCTAssertNil(firstObj.optNSStringCol)
XCTAssertNil(firstObj.optBinaryCol)
XCTAssertNil(firstObj.optDateCol)
try! realm.transaction {
firstObj.optObjectCol = SwiftBoolObject()
firstObj.optObjectCol!.boolCol = true
firstObj.optStringCol = "Hi!"
firstObj.optNSStringCol = "Hi!"
firstObj.optBinaryCol = Data(bytes: "hi", count: 2)
firstObj.optDateCol = Date(timeIntervalSinceReferenceDate: 10)
}
XCTAssertTrue(firstObj.optObjectCol!.boolCol)
XCTAssertEqual(firstObj.optStringCol!, "Hi!")
XCTAssertEqual(firstObj.optNSStringCol!, "Hi!")
XCTAssertEqual(firstObj.optBinaryCol!, Data(bytes: "hi", count: 2))
XCTAssertEqual(firstObj.optDateCol!, Date(timeIntervalSinceReferenceDate: 10))
try! realm.transaction {
firstObj.optObjectCol = nil
firstObj.optStringCol = nil
firstObj.optNSStringCol = nil
firstObj.optBinaryCol = nil
firstObj.optDateCol = nil
}
XCTAssertNil(firstObj.optObjectCol)
XCTAssertNil(firstObj.optStringCol)
XCTAssertNil(firstObj.optNSStringCol)
XCTAssertNil(firstObj.optBinaryCol)
XCTAssertNil(firstObj.optDateCol)
}
func testSwiftClassNameIsDemangled() {
XCTAssertEqual(SwiftObject.className(), "SwiftObject", "Calling className() on Swift class should return demangled name")
}
// Objective-C models
// Note: Swift doesn't support custom accessor names
// so we test to make sure models with custom accessors can still be accessed
func testCustomAccessors() {
let realm = realmWithTestPath()
realm.beginWriteTransaction()
let ca = CustomAccessorsObject.create(in: realm, withValue: ["name", 2])
XCTAssertEqual(ca.name!, "name", "name property should be name.")
ca.age = 99
XCTAssertEqual(ca.age, Int32(99), "age property should be 99")
try! realm.commitWriteTransaction()
}
func testClassExtension() {
let realm = realmWithTestPath()
realm.beginWriteTransaction()
let bObject = BaseClassStringObject()
bObject.intCol = 1
bObject.stringCol = "stringVal"
realm.add(bObject)
try! realm.commitWriteTransaction()
let objectFromRealm = BaseClassStringObject.allObjects(in: realm)[0] as! BaseClassStringObject
XCTAssertEqual(objectFromRealm.intCol, Int32(1), "Should be 1")
XCTAssertEqual(objectFromRealm.stringCol!, "stringVal", "Should be stringVal")
}
func testCreateOrUpdate() {
let realm = RLMRealm.default()
realm.beginWriteTransaction()
_ = SwiftPrimaryStringObject.createOrUpdateInDefaultRealm(withValue: ["string", 1])
let objects = SwiftPrimaryStringObject.allObjects();
XCTAssertEqual(objects.count, UInt(1), "Should have 1 object");
XCTAssertEqual((objects[0] as! SwiftPrimaryStringObject).intCol, 1, "Value should be 1");
_ = SwiftPrimaryStringObject.createOrUpdateInDefaultRealm(withValue: ["stringCol": "string2", "intCol": 2])
XCTAssertEqual(objects.count, UInt(2), "Should have 2 objects")
_ = SwiftPrimaryStringObject.createOrUpdateInDefaultRealm(withValue: ["string", 3])
XCTAssertEqual(objects.count, UInt(2), "Should have 2 objects")
XCTAssertEqual((objects[0] as! SwiftPrimaryStringObject).intCol, 3, "Value should be 3");
try! realm.commitWriteTransaction()
}
// if this fails (and you haven't changed the test module name), the checks
// for swift class names and the demangling logic need to be updated
func testNSStringFromClassDemangledTopLevelClassNames() {
XCTAssertEqual(NSStringFromClass(OuterClass.self), "Tests.OuterClass")
}
// if this fails (and you haven't changed the test module name), the prefix
// check in RLMSchema initialization needs to be updated
func testNestedClassNameMangling() {
XCTAssertEqual(NSStringFromClass(OuterClass.InnerClass.self), "_TtCC5Tests10OuterClass10InnerClass")
}
}
| mit | 28589d9fd1011d52caf5b262184a625a | 38.699301 | 142 | 0.66743 | 4.908776 | false | true | false | false |
kstaring/swift | test/Constraints/ErrorBridging.swift | 4 | 1950 | // RUN: %target-swift-frontend %clang-importer-sdk -parse %s -verify
// REQUIRES: objc_interop
import Foundation
enum FooError: HairyError, Runcible {
case A
var hairiness: Int { return 0 }
func runce() {}
}
protocol HairyError : Error {
var hairiness: Int { get }
}
protocol Runcible {
func runce()
}
let foo = FooError.A
let error: Error = foo
let subError: HairyError = foo
let compo: HairyError & Runcible = foo
// Error-conforming concrete or existential types can be coerced explicitly
// to NSError.
let ns1 = foo as NSError
let ns2 = error as NSError
let ns3 = subError as NSError
var ns4 = compo as NSError
// NSError conversion must be explicit.
// TODO: fixit to insert 'as NSError'
ns4 = compo // expected-error{{cannot assign value of type 'HairyError & Runcible' to type 'NSError'}}
let e1 = ns1 as? FooError
let e1fix = ns1 as FooError // expected-error{{did you mean to use 'as!'}} {{17-19=as!}}
let esub = ns1 as Error
let esub2 = ns1 as? Error // expected-warning{{conditional cast from 'NSError' to 'Error' always succeeds}}
// SR-1562 / rdar://problem/26370984
enum MyError : Error {
case failed
}
func concrete1(myError: MyError) -> NSError {
return myError as NSError
}
func concrete2(myError: MyError) -> NSError {
return myError // expected-error{{cannot convert return expression of type 'MyError' to return type 'NSError'}}
}
func generic<T : Error>(error: T) -> NSError {
return error as NSError
}
extension Error {
var asNSError: NSError {
return self as NSError
}
var asNSError2: NSError {
return self // expected-error{{cannot convert return expression of type 'Self' to return type 'NSError'}}
}
}
// rdar://problem/27543121
func throwErrorCode() throws {
throw FictionalServerError.meltedDown // expected-error{{thrown error code type 'FictionalServerError.Code' does not conform to 'Error'; construct an 'FictionalServerError' instance}}{{29-29=(}}{{40-40=)}}
}
| apache-2.0 | 22d2b32d7e5d3ff70adaedc7548536ae | 25 | 207 | 0.713333 | 3.584559 | false | false | false | false |
yuriy-tolstoguzov/ScaledCenterCarousel | Swift/Example/ScaledCenterCarouselSwiftExample/ScaledCenterCarouselSwiftExample/ViewController.swift | 1 | 1118 | //
// ViewController.swift
// ScaledCenterCarouselSwiftExample
//
// Created by Yuriy Tolstoguzov on 10/20/19.
// Copyright © 2019 Yuriy Tolstoguzov. All rights reserved.
//
import UIKit
import ScaledCenterCarousel
class ViewController: UIViewController, ScaledCenterCarouselPaginatorDelegate {
@IBOutlet weak var collectionView: UICollectionView?
let collectionViewDataSource = CarouselDataSource()
lazy var paginator = ScaledCenterCarouselPaginator(collectionView: collectionView!, delegate: self)
override func viewDidLoad() {
super.viewDidLoad()
guard let collectionView = collectionView else { return }
collectionView.dataSource = collectionViewDataSource
paginator = ScaledCenterCarouselPaginator(collectionView: collectionView,
delegate: self)
}
// MARK: - CarouselCenterPagerDelegate
func carousel(_ collectionView: UICollectionView, didSelectElementAt index: UInt) {
}
func carousel(_ collectionView: UICollectionView, didScrollTo visibleCells: [UICollectionViewCell]) {
}
}
| mit | ea66021185c1298e3c8d359ef2085da4 | 32.848485 | 105 | 0.725157 | 5.502463 | false | false | false | false |
paleksandrs/APCoreDataKit | APCoreDataKit/NSManagedObjectContext+StackSetup.swift | 1 | 1401 | //
// Created by Aleksandrs Proskurins
//
// License
// Copyright © 2016 Aleksandrs Proskurins
// Released under an MIT license: http://opensource.org/licenses/MIT
//
import CoreData
public extension NSManagedObjectContext {
public convenience init(model: ManagedObjectModel, storeType: PersistentStoreType, concurrencyType: NSManagedObjectContextConcurrencyType = .mainQueueConcurrencyType) {
self.init(concurrencyType: concurrencyType)
persistentStoreCoordinator = getPersistentStoreCoordinator(withModel: model, storeType: storeType)
}
fileprivate func getPersistentStoreCoordinator(withModel model: ManagedObjectModel, storeType: PersistentStoreType) -> NSPersistentStoreCoordinator{
let coordinator = NSPersistentStoreCoordinator(managedObjectModel: model.managedObjectModel)
let url = storeType.storePath()
do {
try coordinator.addPersistentStore(ofType: storeType.type, configurationName: nil, at: url as URL?, options: nil)
} catch {
fatalError("*** Failed to initialize the application's saved data ***")
}
return coordinator
}
func child() -> NSManagedObjectContext {
let child = NSManagedObjectContext(concurrencyType: .privateQueueConcurrencyType)
child.parent = self
return child
}
}
| mit | 33e6f2ccaaeac3322a7ea1db68da3df5 | 34 | 172 | 0.700714 | 6.222222 | false | false | false | false |
mightydeveloper/swift | validation-test/compiler_crashers_fixed/0794-swift-typebase-isspecialized.swift | 13 | 988 | // RUN: not %target-swift-frontend %s -parse
// Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
func e<l {
enum e {
func p() { p
d> Bool {
}
protocol f : b { func b
}
func a<g>func s<s : m, v : m u v.v == s> (m: v) {
}
func s<v l k : a {
}
protocol g {
}
struct n : g {
}
func i<h : h, f : g m f.n == h> (g: f) {
}
func i<n : g m n.n = o) {
}
}
k e.w == l> {
}
func p(c: Any, m: Any) -> (((Any, Any) -> Any) -> Any) {
struct d<f : e, g: e where g.h == f.h> {{
}
struct B<T : A> {
}
protocol C {
ty }
}
struct d<f : e, g: e where g.h ==ay) {
}
}
extension NSSet {
convenience init<T>(array: Array<T>) {
}
}
class A {
class k {
func l((Any, k))(m }
}
func j<f: l: e -> e = {
{
l) {
m }
}
protocol k {
}
class e: k{ clq) {
}
}
T) {
}
}
}
class A {
class func a() -> Self {
}
}
func b<T>(t: AnyObject.Type) -> T! {
}
class A {
}
class k: h{ class func r {}
var k = 1
| apache-2.0 | a9c09e496b59c253701959d70d6ca950 | 12.915493 | 87 | 0.530364 | 2.230248 | false | false | false | false |
yutmr/Refresher | Sources/Refresher.swift | 1 | 3334 | //
// Refresher.swift
//
// Created by Yu Tamura on 2016/06/05.
// Copyright © 2016 Yu Tamura. All rights reserved.
//
import UIKit
@objc public enum RefreshState: Int {
case stable, refreshing, ready
}
@objc public protocol RefresherDelegate {
/// Notice current refresh state.
/// - parameter refreshView: A view for display refresh state.
/// - parameter state: Current refreesh state.
/// - parameter percent: Percent of reached refresh threshold.
func updateRefreshView(refreshView: UIView, state: RefreshState, percent: Float)
/// Notify refresh timing.
func startRefreshing()
}
@objcMembers
final public class Refresher: NSObject {
private let refreshView: UIView
private let scrollView: UIScrollView
public weak var delegate: RefresherDelegate?
public private(set) var state: RefreshState = .stable {
didSet (oldValue) {
let percent = Float(-scrollView.contentOffset.y / refreshView.frame.height)
delegate?.updateRefreshView(refreshView: refreshView, state: state, percent: percent)
if oldValue != .refreshing && state == .refreshing {
delegate?.startRefreshing()
}
}
}
public var animateDuration: TimeInterval = 0.3
private var isDragging = false
public init(refreshView: UIView, scrollView: UIScrollView) {
refreshView.frame = CGRect(x: 0, y: -refreshView.frame.height, width: scrollView.frame.width, height: refreshView.frame.height)
scrollView.addSubview(refreshView)
self.refreshView = refreshView
self.scrollView = scrollView
super.init()
scrollView.addObserver(self, forKeyPath: "contentOffset", options: [.new], context: nil)
}
deinit {
scrollView.removeObserver(self, forKeyPath: "contentOffset")
}
override public func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
guard let scrollView = object as? UIScrollView else {
return
}
if isDragging && !scrollView.isDragging {
didEndDragging()
}
isDragging = scrollView.isDragging
didScroll()
}
private func didScroll() {
let height = refreshView.frame.height
let offsetY = scrollView.contentOffset.y
switch state {
case .stable:
// Switch state if below threshold
state = (height < -offsetY) ? .ready : .stable
case .ready:
// Switch state if above threshold
state = (height > -offsetY) ? .stable : .ready
case .refreshing:
// Set contentInset to refreshView visible
UIView.animate(withDuration: animateDuration) { [weak self] in
self?.scrollView.contentInset
= UIEdgeInsets(top: height, left: 0, bottom: 0, right: 0)
}
}
}
private func didEndDragging() {
if state == .ready {
// Start Refreshing
state = .refreshing
}
}
public func finishRefreshing() {
// End Refreshing
state = .stable
UIView.animate(withDuration: animateDuration) {
self.scrollView.contentInset = .zero
}
}
}
| mit | e81f6e9ea8a0f7601215e4a23e0a24b2 | 28.758929 | 158 | 0.625563 | 4.937778 | false | false | false | false |
erkekin/FormSpeech | FormSpeech/FormSpeech.swift | 1 | 3434 | //
// FormSpeech.swift
// FormSpeech
//
// Created by Erk Ekin on 16/11/2016.
// Copyright © 2016 Erk Ekin. All rights reserved.
//
import Foundation
typealias Pair = [Field:String]
protocol Iteratable {}
protocol FormSpeechDelegate {
func valueParsed(parser: Parser, forValue value:String, andKey key:Field)
}
class Parser {
var delegate:FormSpeechDelegate?
let words = Field.rawValues()
var iteration = 0
var text = ""{
didSet{
let secondIndex = iteration + 1
let secondWord:String? = secondIndex == words.count ? nil: words[secondIndex]
let first = words[iteration]
let second = secondWord
if let value = text.getSubstring(substring1: first, substring2: second),
let key = Field(rawValue: first){
let value = value.trimmingCharacters(in: NSCharacterSet.whitespacesAndNewlines)
iteration += secondIndex == words.count ? 0 : 1
delegate?.valueParsed(parser: self, forValue: value, andKey: key)
}
}
}
}
extension RawRepresentable where Self: RawRepresentable {
static func iterateEnum<T: Hashable>(_: T.Type) -> AnyIterator<T> {
var i = 0
return AnyIterator {
let next = withUnsafePointer(to: &i) {
$0.withMemoryRebound(to: T.self, capacity: 1) { $0.pointee }
}
if next.hashValue != i { return nil }
i += 1
return next
}
}
}
extension Iteratable where Self: RawRepresentable, Self: Hashable {
static func hashValues() -> AnyIterator<Self> {
return iterateEnum(self)
}
static func rawValues() -> [Self.RawValue] {
return hashValues().map({$0.rawValue})
}
}
extension String{
func getSubstring(substring1: String, substring2:String?) -> String?{
guard let range1 = self.range(of: substring1) else{return nil}
let lo = self.index(range1.upperBound, offsetBy: 0)
if let sub = substring2 {
if let range2 = self.range(of: sub){
let hi = self.index(range2.lowerBound, offsetBy: 0)
let subRange = lo ..< hi
return self[subRange]
}else{
return nil
}
}else {
let hi = self.endIndex
let subRange = lo ..< hi
return self[subRange]
}
}
// func parse() -> Pair?{ need for a full sentence parse.
//
// let words = Field.rawValues()
// var output:Pair = [:]
//
// for (index, word) in words.enumerated() {
//
// let secondIndex = index + 1
// let secondWord:String? = secondIndex == words.count ? nil: words[secondIndex]
//
// if let value = getSubstring(substring1: word, substring2: secondWord),
// let key = Field(rawValue: word){
//
// output[key] = value.trimmingCharacters(in: NSCharacterSet.whitespacesAndNewlines)
//
// }else {
// return nil
// }
// }
//
// return output.count == 0 ? nil:output
//
// }
}
| gpl-3.0 | 31db21d99c8be48351cc6a120208aac3 | 26.031496 | 99 | 0.518788 | 4.51117 | false | false | false | false |
qq456cvb/DeepLearningKitForiOS | DeepLearningKitFortvOS/DeepLearningKitFortvOS/MetalUtilityFunctions.swift | 7 | 7757 | //
// MetalUtilFunctions.swift
// MemkiteMetal
//
// Created by Amund Tveit & Torb Morland on 24/11/15.
// Copyright © 2015 Memkite. All rights reserved.
//
import Foundation
import Metal
func createComplexNumbersArray(count: Int) -> [MetalComplexNumberType] {
let zeroComplexNumber = MetalComplexNumberType()
return [MetalComplexNumberType](count: count, repeatedValue: zeroComplexNumber)
}
func createFloatNumbersArray(count: Int) -> [Float] {
return [Float](count: count, repeatedValue: 0.0)
}
func createFloatMetalBuffer(var vector: [Float], let metalDevice:MTLDevice) -> MTLBuffer {
let byteLength = vector.count*sizeof(Float) // future: MTLResourceStorageModePrivate
return metalDevice.newBufferWithBytes(&vector, length: byteLength, options: MTLResourceOptions.CPUCacheModeDefaultCache)
}
func createComplexMetalBuffer(var vector:[MetalComplexNumberType], let metalDevice:MTLDevice) -> MTLBuffer {
let byteLength = vector.count*sizeof(MetalComplexNumberType) // or size of and actual 1st element object?
return metalDevice.newBufferWithBytes(&vector, length: byteLength, options: MTLResourceOptions.CPUCacheModeDefaultCache)
}
func createShaderParametersMetalBuffer(var shaderParameters:MetalShaderParameters, metalDevice:MTLDevice) -> MTLBuffer {
let byteLength = sizeof(MetalShaderParameters)
return metalDevice.newBufferWithBytes(&shaderParameters, length: byteLength, options: MTLResourceOptions.CPUCacheModeDefaultCache)
}
func createMatrixShaderParametersMetalBuffer(var params: MetalMatrixVectorParameters, metalDevice: MTLDevice) -> MTLBuffer {
let byteLength = sizeof(MetalMatrixVectorParameters)
return metalDevice.newBufferWithBytes(¶ms, length: byteLength, options: MTLResourceOptions.CPUCacheModeDefaultCache)
}
func createPoolingParametersMetalBuffer(var params: MetalPoolingParameters, metalDevice: MTLDevice) -> MTLBuffer {
let byteLength = sizeof(MetalPoolingParameters)
return metalDevice.newBufferWithBytes(¶ms, length: byteLength, options: MTLResourceOptions.CPUCacheModeDefaultCache)
}
func createConvolutionParametersMetalBuffer(var params: MetalConvolutionParameters, metalDevice: MTLDevice) -> MTLBuffer {
let byteLength = sizeof(MetalConvolutionParameters)
return metalDevice.newBufferWithBytes(¶ms, length: byteLength, options: MTLResourceOptions.CPUCacheModeDefaultCache)
}
func createTensorDimensionsVectorMetalBuffer(var vector: [MetalTensorDimensions], metalDevice: MTLDevice) -> MTLBuffer {
let byteLength = vector.count * sizeof(MetalTensorDimensions)
return metalDevice.newBufferWithBytes(&vector, length: byteLength, options: MTLResourceOptions.CPUCacheModeDefaultCache)
}
func setupShaderInMetalPipeline(shaderName:String, metalDefaultLibrary:MTLLibrary, metalDevice:MTLDevice) -> (shader:MTLFunction!,
computePipelineState:MTLComputePipelineState!,
computePipelineErrors:NSErrorPointer!) {
let shader = metalDefaultLibrary.newFunctionWithName(shaderName)
let computePipeLineDescriptor = MTLComputePipelineDescriptor()
computePipeLineDescriptor.computeFunction = shader
// var computePipelineErrors = NSErrorPointer()
// let computePipelineState:MTLComputePipelineState = metalDevice.newComputePipelineStateWithFunction(shader!, completionHandler: {(})
let computePipelineErrors = NSErrorPointer()
var computePipelineState:MTLComputePipelineState? = nil
do {
computePipelineState = try metalDevice.newComputePipelineStateWithFunction(shader!)
} catch {
print("catching..")
}
return (shader, computePipelineState, computePipelineErrors)
}
func createMetalBuffer(var vector:[Float], metalDevice:MTLDevice) -> MTLBuffer {
let byteLength = vector.count*sizeof(Float)
return metalDevice.newBufferWithBytes(&vector, length: byteLength, options: MTLResourceOptions.CPUCacheModeDefaultCache)
}
func preLoadMetalShaders(metalDevice: MTLDevice, metalDefaultLibrary: MTLLibrary) {
let shaders = ["avg_pool", "max_pool", "rectifier_linear", "convolution_layer", "im2col"]
for shader in shaders {
setupShaderInMetalPipeline(shader, metalDefaultLibrary: metalDefaultLibrary,metalDevice: metalDevice) // TODO: this returns stuff
}
}
func createOrReuseFloatMetalBuffer(name:String, data: [Float], inout cache:[Dictionary<String,MTLBuffer>], layer_number:Int, metalDevice:MTLDevice) -> MTLBuffer {
var result:MTLBuffer
if let tmpval = cache[layer_number][name] {
print("found key = \(name) in cache")
result = tmpval
} else {
print("didnt find key = \(name) in cache")
result = createFloatMetalBuffer(data, metalDevice: metalDevice)
cache[layer_number][name] = result
// print("DEBUG: cache = \(cache)")
}
return result
}
func createOrReuseConvolutionParametersMetalBuffer(name:String,
data: MetalConvolutionParameters,
inout cache:[Dictionary<String,MTLBuffer>], layer_number: Int, metalDevice: MTLDevice) -> MTLBuffer {
var result:MTLBuffer
if let tmpval = cache[layer_number][name] {
print("found key = \(name) in cache")
result = tmpval
} else {
print("didnt find key = \(name) in cache")
result = createConvolutionParametersMetalBuffer(data, metalDevice: metalDevice)
cache[layer_number][name] = result
//print("DEBUG: cache = \(cache)")
}
return result
}
func createOrReuseTensorDimensionsVectorMetalBuffer(name:String,
data:[MetalTensorDimensions],inout cache:[Dictionary<String,MTLBuffer>], layer_number: Int, metalDevice: MTLDevice) -> MTLBuffer {
var result:MTLBuffer
if let tmpval = cache[layer_number][name] {
print("found key = \(name) in cache")
result = tmpval
} else {
print("didnt find key = \(name) in cache")
result = createTensorDimensionsVectorMetalBuffer(data, metalDevice: metalDevice)
cache[layer_number][name] = result
//print("DEBUG: cache = \(cache)")
}
return result
}
//
//let sizeParamMetalBuffer = createShaderParametersMetalBuffer(size_params, metalDevice: metalDevice)
//let poolingParamMetalBuffer = createPoolingParametersMetalBuffer(pooling_params, metalDevice: metalDevice)
func createOrReuseShaderParametersMetalBuffer(name:String,
data:MetalShaderParameters,inout cache:[Dictionary<String,MTLBuffer>], layer_number: Int, metalDevice: MTLDevice) -> MTLBuffer {
var result:MTLBuffer
if let tmpval = cache[layer_number][name] {
// print("found key = \(name) in cache")
result = tmpval
} else {
// print("didnt find key = \(name) in cache")
result = createShaderParametersMetalBuffer(data, metalDevice: metalDevice)
cache[layer_number][name] = result
//print("DEBUG: cache = \(cache)")
}
return result
}
func createOrReusePoolingParametersMetalBuffer(name:String,
data:MetalPoolingParameters,inout cache:[Dictionary<String,MTLBuffer>], layer_number: Int, metalDevice: MTLDevice) -> MTLBuffer {
var result:MTLBuffer
if let tmpval = cache[layer_number][name] {
// print("found key = \(name) in cache")
result = tmpval
} else {
// print("didnt find key = \(name) in cache")
result = createPoolingParametersMetalBuffer(data, metalDevice: metalDevice)
cache[layer_number][name] = result
//print("DEBUG: cache = \(cache)")
}
return result
}
| apache-2.0 | 42a1ea290e9a91c465c693812bb143cf | 43.83237 | 162 | 0.716864 | 5.184492 | false | false | false | false |
netguru/inbbbox-ios | Unit Tests/AutoScrollableShotsDataSourceSpec.swift | 1 | 3800 | //
// AutoScrollableShotsDataSourceSpec.swift
// Inbbbox
//
// Created by Patryk Kaczmarek on 30/12/15.
// Copyright © 2015 Netguru Sp. z o.o. All rights reserved.
//
import Quick
import Nimble
@testable import Inbbbox
class AutoScrollableShotsDataSourceSpec: QuickSpec {
override func spec() {
var sut: AutoScrollableShotsDataSource!
describe("when initializing with content and collection view") {
var collectionView: UICollectionView!
let content = [
UIImage.referenceImageWithColor(.green),
UIImage.referenceImageWithColor(.yellow),
UIImage.referenceImageWithColor(.red)
]
beforeEach {
collectionView = UICollectionView(frame: CGRect(x: 0, y: 0, width: 100, height: 200), collectionViewLayout: UICollectionViewFlowLayout())
sut = AutoScrollableShotsDataSource(collectionView: collectionView, content: content)
}
afterEach {
sut = nil
collectionView = nil
}
it("collection view should be same") {
expect(sut!.collectionView).to(equal(collectionView))
}
it("collection view datasource should be properly set") {
expect(sut.collectionView.dataSource!) === sut
}
it("collection view delegate should be properly set") {
expect(sut.collectionView.delegate!) === sut
}
it("collection view item size should be correct") {
expect(sut.itemSize).to(equal(CGSize(width: 100, height: 100)))
}
it("collection view should have exactly 1 section") {
expect(sut.collectionView.numberOfSections).to(equal(1))
}
it("collection view should have proper cell class") {
let indexPath = IndexPath(item: 0, section: 0)
expect(sut.collectionView.dataSource!.collectionView(sut.collectionView, cellForItemAt: indexPath)).to(beAKindOf(AutoScrollableCollectionViewCell.self))
}
describe("and showing content") {
context("with preparing for animation") {
beforeEach {
sut.prepareForAnimation()
}
it("collection view should have exactly 1 section") {
expect(sut.collectionView.numberOfItems(inSection: 0)).to(equal(7))
}
it("extended content should be 2") {
expect(sut.extendedScrollableItemsCount).to(equal(2))
}
}
context("without preparing for animation") {
it("collection view should have exactly 1 section") {
expect(sut.collectionView.numberOfItems(inSection: 0)).to(equal(content.count))
}
}
context("for first cell") {
it("image should be same as first in content") {
let indexPath = IndexPath(item: 0, section: 0)
let cell = sut.collectionView.dataSource!.collectionView(sut.collectionView, cellForItemAt: indexPath) as! AutoScrollableCollectionViewCell
expect(cell.imageView.image).to(equal(content.first!))
}
}
}
}
}
}
| gpl-3.0 | ace8f4b769d07bec2e6b1e5d14cb952b | 37.373737 | 168 | 0.511714 | 6.0784 | false | false | false | false |
ndleon09/TopApps | TopApps/AppTableViewCell.swift | 1 | 1232 | //
// AppTableViewCell.swift
// TopApps
//
// Created by Nelson Dominguez on 24/04/16.
// Copyright © 2016 Nelson Dominguez. All rights reserved.
//
import Foundation
import UIKit
import BothamUI
import AlamofireImage
class AppTableViewCell: UITableViewCell, BothamViewCell
{
func configure(forItem item: App) {
let size: CGSize = CGSize(width: 50.0, height: 50.0)
let radius: CGFloat = 8.0
let filter = AspectScaledToFillSizeWithRoundedCornersFilter(size: size, radius: radius)
let placeholder = UIImage(named: "placeholder")?.af_imageAspectScaled(toFit: size).af_imageRounded(withCornerRadius: radius)
if let image = item.image {
imageView?.af_setImage(withURL: URL(string: image)!, placeholderImage: placeholder, filter: filter, progress: nil, progressQueue: DispatchQueue.main, imageTransition: .crossDissolve(0.4), runImageTransitionIfCached: false, completion: nil)
} else {
imageView?.image = placeholder
}
textLabel?.text = item.name
detailTextLabel?.numberOfLines = 0
detailTextLabel?.text = item.category
accessibilityLabel = "\(item.id)-Identifier"
}
}
| mit | 6cf2951e78c3a939bbc105c57c4add6f | 33.194444 | 251 | 0.674249 | 4.716475 | false | false | false | false |
rmnblm/Mapbox-iOS-Examples | src/Examples/ClusteringViewController.swift | 1 | 3292 | //
// ClusteringViewController.swift
// Mapbox-iOS-Examples
//
// Created by Roman Blum on 21.09.16.
// Copyright © 2016 rmnblm. All rights reserved.
//
import UIKit
import Mapbox
let kClusterZoomLevel: Float = 11
let kSourceName = "mcdonalds"
let kIconName = "Pin"
let kLayerName = "restaurants"
let kLayerClusterName = "restaurants-cluster"
let kLayerPointCountName = "restaurants-cluster-pointcount"
class ClusteringViewController: UIViewController, MGLMapViewDelegate {
@IBOutlet var mapView: MGLMapView!
let layerNames = [kLayerClusterName, kLayerPointCountName, kLayerName]
func mapViewDidFinishLoadingMap(_ mapView: MGLMapView) {
mapView.style?.setImage(#imageLiteral(resourceName: "Pin"), forName: kIconName)
var options = [MGLShapeSourceOption : Any]()
options[.clustered] = true
options[.clusterRadius] = 100
options[.maximumZoomLevelForClustering] = kClusterZoomLevel
let sourceURL = Bundle.main.url(forResource: kSourceName, withExtension: "geojson")!
let source = MGLShapeSource(identifier: kSourceName, url: sourceURL, options: options)
mapView.style?.addSource(source)
let circles = MGLCircleStyleLayer(identifier: kLayerClusterName, source: source)
circles.circleStrokeColor = MGLStyleValue(rawValue: UIColor.white)
circles.circleStrokeWidth = MGLStyleValue(rawValue: 1)
circles.circleColor = MGLStyleValue(
interpolationMode: .interval,
sourceStops: [
0: MGLStyleValue(rawValue: UIColor(colorLiteralRed: 76/255.0, green: 217/255.0, blue: 100/255.0, alpha: 1)),
100: MGLStyleValue(rawValue: UIColor(colorLiteralRed: 255/255.0, green: 204/255.0, blue: 0/255.0, alpha: 1)),
300: MGLStyleValue(rawValue: UIColor(colorLiteralRed: 255/255.0, green: 149/255.0, blue: 0/255.0, alpha: 1)),
1000: MGLStyleValue(rawValue: UIColor(colorLiteralRed: 255/255.0, green: 59/255.0, blue: 48/255.0, alpha: 1))],
attributeName: "point_count",
options: nil)
circles.circleRadius = MGLStyleValue(
interpolationMode: .interval,
sourceStops: [
0: MGLStyleValue(rawValue: 12),
100: MGLStyleValue(rawValue: 15),
300: MGLStyleValue(rawValue: 18),
1000: MGLStyleValue(rawValue: 20)],
attributeName: "point_count",
options: nil)
circles.predicate = NSPredicate(format: "%K == YES", argumentArray: ["cluster"])
mapView.style?.addLayer(circles)
var symbols = MGLSymbolStyleLayer(identifier: kLayerPointCountName, source: source)
symbols.text = MGLStyleValue(rawValue: "{point_count}")
symbols.textColor = MGLStyleValue(rawValue: UIColor.white)
mapView.style?.addLayer(symbols)
symbols = MGLSymbolStyleLayer(identifier: kLayerName, source: source)
symbols.iconImageName = MGLStyleValue.init(rawValue: NSString(string: kIconName))
symbols.iconAllowsOverlap = MGLStyleValue(rawValue: NSNumber(value: true))
symbols.predicate = NSPredicate(format: "%K != YES", argumentArray: ["cluster"])
mapView.style?.addLayer(symbols)
}
}
| mit | 675d7b18cc78b7d0db33aa6f9ead3ca0 | 44.708333 | 127 | 0.669401 | 4.393858 | false | false | false | false |
twtstudio/WePeiYang-iOS | WePeiYang/Read/View/Search.swift | 1 | 7755 | //
// Search.swift
// YouTube
//
// Created by Haik Aslanyan on 7/4/16.
// Copyright © 2016 Haik Aslanyan. All rights reserved.
//
protocol SearchDelegate {
func hideSearchView(status : Bool)
func saveResult(result: [Librarian.SearchResult])
}
import UIKit
enum LabelContent: String {
case NotFound = "没有找到相关书籍👀"
case Morning = "早上好~ (。・∀・)ノ゙"
case Afternoon = "下午好~ (๑•̀ㅂ•́)و✧"
case Evening = "晚上好~ <(  ̄^ ̄)"
}
class Search: UIView, UITableViewDelegate, UITableViewDataSource, UITextFieldDelegate {
var result: [Librarian.SearchResult] = []
//MARK: Properties
let label = UILabel()
var notFoundView:UIView!
let statusView: UIView = {
let st = UIView.init(frame: UIApplication.sharedApplication().statusBarFrame)
st.backgroundColor = UIColor.blackColor()
st.alpha = 0.15
return st
}()
lazy var searchView: UIView = {
let sv = UIView.init(frame: CGRect.init(x: 0, y: 0, width: self.frame.width, height: 68))
sv.backgroundColor = UIColor.whiteColor()
sv.alpha = 0
return sv
}()
lazy var backgroundView: UIView = {
let bv = UIView.init(frame: self.frame)
bv.backgroundColor = UIColor.blackColor()
bv.alpha = 0
return bv
}()
lazy var backButton: UIButton = {
let bb = UIButton.init(frame: CGRect.init(x: 0, y: 20, width: 48, height: 48))
bb.setBackgroundImage(UIImage.init(named: "back"), forState: [])
bb.addTarget(self, action: #selector(Search.dismiss), forControlEvents: .TouchUpInside)
return bb
}()
lazy var searchField: UITextField = {
let sf = UITextField.init(frame: CGRect.init(x: 48, y: 20, width: self.frame.width - 50, height: 48))
sf.placeholder = "查询书籍在馆记录"
sf.autocapitalizationType = .None
sf.clearsOnBeginEditing = true
sf.returnKeyType = .Go
// sf.keyboardAppearance = UIKeyboardAppearance.Dark
return sf
}()
lazy var tableView: UITableView = {
let tv: UITableView = UITableView.init(frame: CGRect.init(x: 0, y: 68, width: self.frame.width, height: self.frame.height - 68))
return tv
}()
var items = [String]()
var delegate:SearchDelegate?
//MARK: Methods
func customization() {
self.addSubview(self.backgroundView)
self.backgroundView.addGestureRecognizer(UITapGestureRecognizer.init(target: self, action: #selector(Search.dismiss)))
self.addSubview(self.searchView)
self.searchView.addSubview(self.searchField)
self.searchView.addSubview(self.backButton)
self.tableView.delegate = self
self.tableView.dataSource = self
self.tableView.tableFooterView = UIView()
self.tableView.backgroundColor = UIColor.clearColor()
self.searchField.delegate = self
self.addSubview(self.statusView)
self.addSubview(self.tableView)
self.tableView.estimatedRowHeight = 80
self.tableView.rowHeight = UITableViewAutomaticDimension
notFoundView = UIView(frame: CGRect.init(x: 0, y: 68, width: self.frame.width, height: 50))
notFoundView.backgroundColor = UIColor.whiteColor()
notFoundView.addSubview(self.label)
self.addSubview(notFoundView)
//UIApplication.sharedApplication().keyWindow?.addSubview(notFoundView)
self.label.sizeToFit()
self.label.snp_makeConstraints { make in
make.center.equalTo(notFoundView)
}
self.refreshLabel()
}
func refreshLabel() {
let date = NSDate()
let timeFormatter = NSDateFormatter()
timeFormatter.dateFormat = "HH"
let strNowTime = timeFormatter.stringFromDate(date) as String
let hour = Int(strNowTime)!
var str: LabelContent = .Morning
switch hour {
case 5...11:
str = .Morning
case 12...18:
str = .Afternoon
case 19...24, 0...4:
str = .Evening
default:
break;
}
label.text = str.rawValue
}
func animate() {
UIView.animateWithDuration(0.2, animations: {
self.backgroundView.alpha = 0.5
self.searchView.alpha = 1
// self.searchField.becomeFirstResponder()
})
}
func dismiss() {
self.searchField.text = ""
self.items.removeAll()
self.tableView.removeFromSuperview()
// self.notFoundView.removeFromSuperview()
// 没有动画
// UIView.animateWithDuration(0.0, animations: {
// self.backgroundView.alpha = 0
// self.searchView.alpha = 0
self.searchField.resignFirstResponder()
self.searchView.removeFromSuperview()
self.removeFromSuperview()
// }, completion: {(Bool) in
self.delegate?.hideSearchView(true)
// })
}
//MARK: 搜索
func textFieldShouldReturn(textField: UITextField) -> Bool {
guard let str = textField.text else {
return true
}
//self.notFoundView.removeFromSuperview()
result.removeAll()
self.tableView.reloadData()
Librarian.searchBook(withString: str) { searchResult in
self.result = searchResult
self.delegate?.saveResult(self.result)
if self.result.count == 0 {
self.tableView.tableHeaderView = self.notFoundView
self.label.text = LabelContent.NotFound.rawValue
self.notFoundView.frame = CGRectMake(0, 68, self.frame.width, 50)
//self.addSubview(self.notFoundView)
}
self.searchField.resignFirstResponder()
//UIApplication.sharedApplication().keyWindow?.addSubview(self.notFoundView)
self.tableView.reloadData()
}
return true
}
func textFieldShouldBeginEditing(textField: UITextField) -> Bool {
self.result.removeAll()
self.tableView.reloadData()
self.notFoundView.frame = CGRectMake(0, 0, 0, 0)
label.text = ""
return true
}
//MARK: TableView Delegates and Datasources
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
//
return result.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = SearchResultCell(model: result[indexPath.row])
return cell
}
func scrollViewWillBeginDragging(scrollView: UIScrollView) {
self.searchField.resignFirstResponder()
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
self.tableView.deselectRowAtIndexPath(indexPath, animated: true)
let vc = BookDetailViewController(bookID: "\(result[indexPath.row].bookID)")
self.removeFromSuperview()
//print(self.tableView.contentOffset)
// only push once
if !(UIViewController.currentViewController().navigationController?.topViewController is BookDetailViewController){
UIViewController.currentViewController().navigationController?.showViewController(vc, sender: nil)
}
// UIViewController.currentViewController().navigationController?.pushViewController(vc, animated: true)
}
//MARK: Inits
override init(frame: CGRect) {
super.init(frame: frame)
customization()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
}
| mit | 0fba4266ddab06b7e858ff718ff962aa | 33.818182 | 136 | 0.625979 | 4.61168 | false | false | false | false |
tuanan94/FRadio-ios | SwiftRadioUITests/SwiftRadioUITests.swift | 1 | 4865 | //
// SwiftRadioUITests.swift
// SwiftRadioUITests
//
// Created by Jonah Stiennon on 12/3/15.
// Copyright © 2015 CodeMarket.io. All rights reserved.
//
import XCTest
class SwiftRadioUITests: XCTestCase {
let app = XCUIApplication()
let stations = XCUIApplication().cells
let hamburgerMenu = XCUIApplication().navigationBars["Swift Radio"].buttons["icon hamburger"]
let pauseButton = XCUIApplication().buttons["btn pause"]
let playButton = XCUIApplication().buttons["btn play"]
let volume = XCUIApplication().sliders.element(boundBy: 0)
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
// In UI tests it is usually best to stop immediately when a failure occurs.
continueAfterFailure = false
// UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method.
XCUIApplication().launch()
// wait for the main view to load
self.expectation(
for: NSPredicate(format: "self.count > 0"),
evaluatedWith: stations,
handler: nil)
self.waitForExpectations(timeout: 10.0, handler: nil)
// In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func assertStationsPresent() {
let numStations:UInt = 4
XCTAssertEqual(stations.count, Int(numStations))
let texts = stations.staticTexts.count
XCTAssertEqual(texts, Int(numStations * 2))
}
func assertHamburgerContent() {
XCTAssertTrue(app.staticTexts["Created by: Matthew Fecher"].exists)
}
func assertAboutContent() {
XCTAssertTrue(app.buttons["email me"].exists)
XCTAssertTrue(app.buttons["matthewfecher.com"].exists)
}
func assertPaused() {
XCTAssertFalse(pauseButton.isEnabled)
XCTAssertTrue(playButton.isEnabled)
XCTAssertTrue(app.staticTexts["Station Paused..."].exists);
}
func assertPlaying() {
XCTAssertTrue(pauseButton.isEnabled)
XCTAssertFalse(playButton.isEnabled)
XCTAssertFalse(app.staticTexts["Station Paused..."].exists);
}
func assertStationOnMenu(_ stationName:String) {
let button = app.buttons["nowPlaying"];
let label:String = button.label
if label != "" {
XCTAssertTrue(label.contains(stationName))
} else {
XCTAssertTrue(false)
}
}
func assertStationInfo() {
let textView = app.textViews.element(boundBy: 0)
if let value = textView.value {
XCTAssertGreaterThan((value as AnyObject).length, 10)
} else {
XCTAssertTrue(false)
}
}
func waitForStationToLoad() {
self.expectation(
for: NSPredicate(format: "exists == 0"),
evaluatedWith: app.staticTexts["Loading Station..."],
handler: nil)
self.waitForExpectations(timeout: 25.0, handler: nil)
}
func testMainStationsView() {
// Use recording to get started writing UI tests.
// Use XCTAssert and related functions to verify your tests produce the correct results.
assertStationsPresent()
hamburgerMenu.tap()
assertHamburgerContent()
app.buttons["About"].tap()
assertAboutContent()
app.buttons["Okay"].tap()
app.buttons["btn close"].tap()
assertStationsPresent()
let firstStation = stations.element(boundBy: 0)
let stationName:String = firstStation.children(matching: .staticText).element(boundBy: 0).label
assertStationOnMenu("Choose")
firstStation.tap()
waitForStationToLoad();
pauseButton.tap()
assertPaused()
playButton.tap()
assertPlaying()
app.navigationBars["Sub Pop Radio"].buttons["Back"].tap()
assertStationOnMenu(stationName)
app.navigationBars["Swift Radio"].buttons["btn nowPlaying"].tap()
waitForStationToLoad()
volume.adjust(toNormalizedSliderPosition: 0.2)
volume.adjust(toNormalizedSliderPosition: 0.8)
volume.adjust(toNormalizedSliderPosition: 0.5)
app.buttons["More Info"].tap()
assertStationInfo()
app.buttons["Okay"].tap()
app.buttons["logo"].tap()
assertAboutContent()
app.buttons["Okay"].tap()
}
}
| mit | 1aa4a5b3f6d1d50b0385f4d92148b1df | 33.48227 | 182 | 0.628959 | 4.866867 | false | true | false | false |
kousun12/RxSwift | RxSwift/Disposables/CompositeDisposable.swift | 8 | 3481 | //
// CompositeDisposable.swift
// Rx
//
// Created by Krunoslav Zaher on 2/20/15.
// Copyright (c) 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
/**
Represents a group of disposable resources that are disposed together.
*/
public class CompositeDisposable : DisposeBase, Disposable, Cancelable {
public typealias DisposeKey = Bag<Disposable>.KeyType
private var _lock = SpinLock()
// state
private var _disposables: Bag<Disposable>? = Bag()
public var disposed: Bool {
get {
_lock.lock(); defer { _lock.unlock() }
return _disposables == nil
}
}
public override init() {
}
/**
Initializes a new instance of composite disposable with the specified number of disposables.
*/
public init(_ disposable1: Disposable, _ disposable2: Disposable) {
_disposables!.insert(disposable1)
_disposables!.insert(disposable2)
}
/**
Initializes a new instance of composite disposable with the specified number of disposables.
*/
public init(_ disposable1: Disposable, _ disposable2: Disposable, _ disposable3: Disposable) {
_disposables!.insert(disposable1)
_disposables!.insert(disposable2)
_disposables!.insert(disposable3)
}
/**
Initializes a new instance of composite disposable with the specified number of disposables.
*/
public init(disposables: [Disposable]) {
for disposable in disposables {
_disposables!.insert(disposable)
}
}
/**
Adds a disposable to the CompositeDisposable or disposes the disposable if the CompositeDisposable is disposed.
- parameter disposable: Disposable to add.
- returns: Key that can be used to remove disposable from composite disposable. In case dispose bag was already
disposed `nil` will be returned.
*/
public func addDisposable(disposable: Disposable) -> DisposeKey? {
let key = _addDisposable(disposable)
if key == nil {
disposable.dispose()
}
return key
}
private func _addDisposable(disposable: Disposable) -> DisposeKey? {
_lock.lock(); defer { _lock.unlock() }
return _disposables?.insert(disposable)
}
/**
- returns: Gets the number of disposables contained in the `CompositeDisposable`.
*/
public var count: Int {
get {
_lock.lock(); defer { _lock.unlock() }
return _disposables?.count ?? 0
}
}
/**
Removes and disposes the disposable identified by `disposeKey` from the CompositeDisposable.
- parameter disposeKey: Key used to identify disposable to be removed.
*/
public func removeDisposable(disposeKey: DisposeKey) {
_removeDisposable(disposeKey)?.dispose()
}
private func _removeDisposable(disposeKey: DisposeKey) -> Disposable? {
_lock.lock(); defer { _lock.unlock() }
return _disposables?.removeKey(disposeKey)
}
/**
Disposes all disposables in the group and removes them from the group.
*/
public func dispose() {
if let disposables = _dispose() {
disposeAllIn(disposables)
}
}
private func _dispose() -> Bag<Disposable>? {
_lock.lock(); defer { _lock.unlock() }
let disposeBag = _disposables
_disposables = nil
return disposeBag
}
} | mit | 39e5ffe8b6b6606c58cf428c59a58f10 | 27.540984 | 115 | 0.626544 | 4.937589 | false | false | false | false |
XiaHaozheJose/swift3_wb | sw3_wb/sw3_wb/Classes/Tools/Extension/UIColor-Extension.swift | 1 | 2538 | //
// UIColor-Extension.swift
// pageView
//
// Copyright © 2017年 浩哲 夏. All rights reserved.
//
import Foundation
import UIKit
// MARK: - 随机颜色
extension UIColor{
class func randomColor()->UIColor{
return UIColor.init(red: CGFloat(arc4random_uniform(256))/255.0, green: CGFloat(arc4random_uniform(256))/255.0, blue: CGFloat(arc4random_uniform(256))/255.0, alpha: 1.0)
}
// MARK: - RGB值
convenience init(r:CGFloat,g:CGFloat,b:CGFloat,alpha:CGFloat = 1.0) {
self.init(red: r/255.0, green: g/255.0, blue: b/255.0, alpha: alpha)
}
// MARK: - 处理16进制
convenience init?(hexString:String) {
//处理16进制 0x 0X #
guard hexString.characters.count > 6 else {return nil }
var hexTempString = hexString.uppercased() as NSString
//判断0X
if hexTempString.hasPrefix("0X") || hexTempString.hasPrefix("##"){
hexTempString = hexTempString.substring(from: 2) as NSString
// hexTempString = hexTempString.substring(from: hexTempString.index(hexString.startIndex, offsetBy: 2))
}
//判断#
if hexTempString.hasPrefix("#"){
hexTempString = hexTempString.substring(from: 1) as NSString
}
//截取R:FF G:00 B:11
var range = NSRange.init(location: 0, length: 2)
let rHex = hexTempString.substring(with: range)
var red : UInt32 = 0
Scanner(string: rHex).scanHexInt32(&red)
range.location = 2
let gHex = hexTempString.substring(with: range)
var green : UInt32 = 0
Scanner(string: gHex).scanHexInt32(&green)
range.location = 4
let bHex = hexTempString.substring(with: range)
var blue : UInt32 = 0
Scanner(string: bHex).scanHexInt32(&blue)
self.init(r: CGFloat(red), g: CGFloat(green), b: CGFloat(blue))
}
}
// MARK: - 从颜色中获取RGB
extension UIColor{
///通过RGB值通道 获取RGB
func getRGBWithRGBColor()->(CGFloat,CGFloat,CGFloat){
guard let cmps = cgColor.components else {
fatalError("MUST BE RGB COLOR")
}
return (cmps[0] * 255,cmps[1] * 255,cmps[2] * 255)
}
///通过颜色直接获取RGB
func getRGBWithColor()->(CGFloat,CGFloat,CGFloat){
var red : CGFloat = 0
var green : CGFloat = 0
var blue : CGFloat = 0
getRed(&red, green: &green, blue: &blue, alpha: nil)
return (red * 255, green * 255, blue * 255)
}
}
| mit | 6cb7478be61c55b29ade7d95f8dd87e9 | 33.492958 | 177 | 0.604328 | 3.710606 | false | false | false | false |
EugeneVegner/sws-copyleaks-sdk-test | Example/PlagiarismChecker/MainViewController.swift | 1 | 5931 | /*
* The MIT License(MIT)
*
* Copyright(c) 2016 Copyleaks LTD (https://copyleaks.com)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*/
import UIKit
import PlagiarismChecker
class MainViewController: UIViewController {
//@IBOutlet weak var navigationItem: UINavigationItem!
@IBOutlet weak var activityIndicator: UIActivityIndicatorView!
var currentProcess: AnyObject?
override func viewDidLoad() {
super.viewDidLoad()
self.navigationItem.backBarButtonItem = nil
self.navigationItem.leftBarButtonItem = nil
self.navigationItem.title = "Main"
}
//createByUrl
@IBAction func createByUrlAction(sender: AnyObject) {
if activityIndicator.isAnimating() {
return
}
activityIndicator.startAnimating()
let cloud = CopyleaksCloud(.Businesses)
cloud.allowPartialScan = true
cloud.createByUrl(NSURL(string: "https://google.com")!) { (result) in
self.activityIndicator.stopAnimating()
self.showProcessResult(result)
}
}
@IBAction func createByTextAction(sender: AnyObject) {
if activityIndicator.isAnimating() {
return
}
activityIndicator.startAnimating()
let cloud = CopyleaksCloud(.Businesses)
cloud.createByText("Test me") { (result) in
self.activityIndicator.stopAnimating()
self.showProcessResult(result)
}
}
@IBAction func createByFileAction(sender: AnyObject) {
if activityIndicator.isAnimating() {
return
}
activityIndicator.startAnimating()
let imagePath: String = NSBundle.mainBundle().pathForResource("doc_test", ofType: "txt")!
let cloud = CopyleaksCloud(.Businesses)
cloud.allowPartialScan = true
cloud.createByFile(fileURL: NSURL(string: imagePath)!, language: "English") { (result) in
self.activityIndicator.stopAnimating()
self.showProcessResult(result)
}
}
@IBAction func createByOCRAction(sender: AnyObject) {
if activityIndicator.isAnimating() {
return
}
activityIndicator.startAnimating()
let imagePath: String = NSBundle.mainBundle().pathForResource("ocr_test", ofType: "png")!
let cloud = CopyleaksCloud(.Businesses)
cloud.allowPartialScan = true
cloud.createByOCR(fileURL: NSURL(string: imagePath)!, language: "English") { (result) in
self.activityIndicator.stopAnimating()
self.showProcessResult(result)
}
}
@IBAction func countCreditsAction(sender: AnyObject) {
if activityIndicator.isAnimating() {
return
}
activityIndicator.startAnimating()
let cloud = CopyleaksCloud(.Businesses)
cloud.countCredits { (result) in
self.activityIndicator.stopAnimating()
if result.isSuccess {
let val = result.value?["Amount"] as? Int ?? 0
Alert("Amount", message: "\(val)")
}
else {
Alert("Error", message: result.error?.localizedFailureReason ?? "Unknown error")
}
}
}
@IBAction func logoutAction(sender: AnyObject) {
Copyleaks.logout {
self.navigationController?.popViewControllerAnimated(true)
}
}
// MARK: - helpers
func showProcessResult(result: PlagiarismChecker.CopyleaksResult<AnyObject, NSError>) {
currentProcess = nil
if result.isSuccess {
currentProcess = result.value
self.performSegueWithIdentifier("showDetails", sender: nil)
}
else {
Alert("Error", message: result.error?.localizedFailureReason ?? "Unknown error")
}
}
// MARK: - Memory
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "showDetails" {
if let
processId: String = currentProcess?["ProcessId"] as? String,
created: String = currentProcess?["CreationTimeUTC"] as? String {
let vc: ProcessDetailsViewController = segue.destinationViewController as! ProcessDetailsViewController
vc.processId = processId
vc.processCreated = created
vc.processStatus = "Progress"
} else {
Alert("Error", message: "No process data")
}
}
}
}
| mit | e40dad569c8cc08f4420a749ab7f34a0 | 31.233696 | 119 | 0.622661 | 5.309758 | false | false | false | false |
ctinnell/swift-reflection | SwiftReflect.playground/section-1.swift | 1 | 591 | // Playground - noun: a place where people can play
import UIKit
class animal {
let animalName: String
let color: String
init(animalName: String, color: String) {
self.animalName = animalName
self.color = color
}
}
let dog = animal(animalName: "Fido", color: "white")
let dogProperties = reflect(dog)
dogProperties.count
for index in 0...dogProperties.count-1 {
let (name, child) = dogProperties[0]
if child.valueType is String.Type {
println("\(name) is a string")
}
else {
println("It isn't a string")
}
}
| mit | 377a8f0c864b1312fbb956d247898823 | 16.909091 | 52 | 0.626058 | 3.648148 | false | false | false | false |
javibm/fastlane | fastlane/swift/LaneFileProtocol.swift | 1 | 3735 | //
// LaneFileProtocol.swift
// FastlaneSwiftRunner
//
// Created by Joshua Liebowitz on 8/4/17.
// Copyright © 2017 Joshua Liebowitz. All rights reserved.
//
import Foundation
public protocol LaneFileProtocol: class {
var fastlaneVersion: String { get }
static func runLane(named: String)
func recordLaneDescriptions()
func beforeAll()
func afterAll(currentLane: String)
func onError(currentLane: String, errorInfo: String)
}
public extension LaneFileProtocol {
var fastlaneVersion: String { return "" } // default "" because that means any is fine
func beforeAll() { } // no op by default
func afterAll(currentLane: String) { } // no op by default
func onError(currentLane: String, errorInfo: String) {} // no op by default
func recordLaneDescriptions() { } // no op by default
}
@objcMembers
public class LaneFile: NSObject, LaneFileProtocol {
private(set) static var fastfileInstance: Fastfile?
// Called before any lane is executed.
private func setupAllTheThings() {
// Step 1, add lange descriptions
(self as! Fastfile).recordLaneDescriptions()
// Step 2, run beforeAll() function
LaneFile.fastfileInstance!.beforeAll()
}
public static var lanes: [String : String] {
var laneToMethodName: [String : String] = [:]
var methodCount: UInt32 = 0
let methodList = class_copyMethodList(self, &methodCount)
for i in 0..<Int(methodCount) {
let selName = sel_getName(method_getName(methodList![i]))
let name = String(cString: selName)
let lowercasedName = name.lowercased()
guard lowercasedName.hasSuffix("lane") else {
continue
}
laneToMethodName[lowercasedName] = name
let lowercasedNameNoLane = String(lowercasedName.prefix(lowercasedName.count - 4))
laneToMethodName[lowercasedNameNoLane] = name
}
return laneToMethodName
}
public static func loadFastfile() {
if self.fastfileInstance == nil {
let fastfileType: AnyObject.Type = NSClassFromString(self.className())!
let fastfileAsNSObjectType: NSObject.Type = fastfileType as! NSObject.Type
let currentFastfileInstance: Fastfile? = fastfileAsNSObjectType.init() as? Fastfile
self.fastfileInstance = currentFastfileInstance
}
}
public static func runLane(named: String) {
log(message: "Running lane: \(named)")
self.loadFastfile()
guard let fastfileInstance: Fastfile = self.fastfileInstance else {
let message = "Unable to instantiate class named: \(self.className())"
log(message: message)
fatalError(message)
}
// call all methods that need to be called before we start calling lanes
fastfileInstance.setupAllTheThings()
let currentLanes = self.lanes
let lowerCasedLaneRequested = named.lowercased()
guard let laneMethod = currentLanes[lowerCasedLaneRequested] else {
let message = "unable to find lane named: \(named)"
log(message: message)
fatalError(message)
}
// We need to catch all possible errors here and display a nice message
_ = fastfileInstance.perform(NSSelectorFromString(laneMethod))
// only call on success
fastfileInstance.afterAll(currentLane: named)
log(message: "Done running lane: \(named) 🚀")
}
}
// Please don't remove the lines below
// They are used to detect outdated files
// FastlaneRunnerAPIVersion [0.9.1]
| mit | 6c7b1f9e4e019ff8205ef43d027a08dd | 35.223301 | 95 | 0.641919 | 4.594828 | false | false | false | false |
think-dev/MadridBUS | MadridBUS/Source/Data/Network/StringRequest.swift | 1 | 848 | import Foundation
import Alamofire
import ObjectMapper
class StringRequest: Request {
typealias ResponseType = String
var group: DispatchGroup = DispatchGroup()
var stringURL: String
var method: HTTPMethod
var parameter: Mappable
var encoding: ParameterEncoding?
var response: Response<ResponseType>
var skippableKey: String?
required init(url: String, method: HTTPMethod, parameter: Mappable, encoding: ParameterEncoding?, skippableKey: String?) {
self.stringURL = url
self.method = method
self.parameter = parameter
self.response = Response<ResponseType>()
self.encoding = encoding
self.skippableKey = skippableKey
}
func addSuccessResponse(_ data: Data) {
response.dataResponse = String(data: data, encoding: .utf8)
}
}
| mit | 23961884170125fa07767d6d20d2b09f | 28.241379 | 126 | 0.682783 | 4.959064 | false | false | false | false |
zbw209/- | StudyNotes/Pods/Alamofire/Source/Protector.swift | 5 | 5274 | //
// Protector.swift
//
// Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/)
//
// 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
// MARK: -
/// An `os_unfair_lock` wrapper.
final class UnfairLock {
private let unfairLock: os_unfair_lock_t
init() {
unfairLock = .allocate(capacity: 1)
unfairLock.initialize(to: os_unfair_lock())
}
deinit {
unfairLock.deinitialize(count: 1)
unfairLock.deallocate()
}
private func lock() {
os_unfair_lock_lock(unfairLock)
}
private func unlock() {
os_unfair_lock_unlock(unfairLock)
}
/// Executes a closure returning a value while acquiring the lock.
///
/// - Parameter closure: The closure to run.
///
/// - Returns: The value the closure generated.
func around<T>(_ closure: () -> T) -> T {
lock(); defer { unlock() }
return closure()
}
/// Execute a closure while acquiring the lock.
///
/// - Parameter closure: The closure to run.
func around(_ closure: () -> Void) {
lock(); defer { unlock() }
return closure()
}
}
/// A thread-safe wrapper around a value.
final class Protector<T> {
private let lock = UnfairLock()
private var value: T
init(_ value: T) {
self.value = value
}
/// The contained value. Unsafe for anything more than direct read or write.
var directValue: T {
get { return lock.around { value } }
set { lock.around { value = newValue } }
}
/// Synchronously read or transform the contained value.
///
/// - Parameter closure: The closure to execute.
///
/// - Returns: The return value of the closure passed.
func read<U>(_ closure: (T) -> U) -> U {
return lock.around { closure(self.value) }
}
/// Synchronously modify the protected value.
///
/// - Parameter closure: The closure to execute.
///
/// - Returns: The modified value.
@discardableResult
func write<U>(_ closure: (inout T) -> U) -> U {
return lock.around { closure(&self.value) }
}
}
extension Protector where T: RangeReplaceableCollection {
/// Adds a new element to the end of this protected collection.
///
/// - Parameter newElement: The `Element` to append.
func append(_ newElement: T.Element) {
write { (ward: inout T) in
ward.append(newElement)
}
}
/// Adds the elements of a sequence to the end of this protected collection.
///
/// - Parameter newElements: The `Sequence` to append.
func append<S: Sequence>(contentsOf newElements: S) where S.Element == T.Element {
write { (ward: inout T) in
ward.append(contentsOf: newElements)
}
}
/// Add the elements of a collection to the end of the protected collection.
///
/// - Parameter newElements: The `Collection` to append.
func append<C: Collection>(contentsOf newElements: C) where C.Element == T.Element {
write { (ward: inout T) in
ward.append(contentsOf: newElements)
}
}
}
extension Protector where T == Data? {
/// Adds the contents of a `Data` value to the end of the protected `Data`.
///
/// - Parameter data: The `Data` to be appended.
func append(_ data: Data) {
write { (ward: inout T) in
ward?.append(data)
}
}
}
extension Protector where T == Request.MutableState {
/// Attempts to transition to the passed `State`.
///
/// - Parameter state: The `State` to attempt transition to.
///
/// - Returns: Whether the transition occurred.
func attemptToTransitionTo(_ state: Request.State) -> Bool {
return lock.around {
guard value.state.canTransitionTo(state) else { return false }
value.state = state
return true
}
}
/// Perform a closure while locked with the provided `Request.State`.
///
/// - Parameter perform: The closure to perform while locked.
func withState(perform: (Request.State) -> Void) {
lock.around { perform(value.state) }
}
}
| mit | df89a3d6813e3fabd73168641f1559eb | 30.580838 | 88 | 0.624763 | 4.246377 | false | false | false | false |
vlaminck/LD33 | LD33/LD33/MyUtils.swift | 1 | 2396 | //
// MyUtils.swift
// ZombieConga
//
// Created by Main Account on 10/22/14.
// Copyright (c) 2014 Razeware LLC. All rights reserved.
//
import Foundation
import CoreGraphics
func + (left: CGPoint, right: CGPoint) -> CGPoint {
return CGPoint(x: left.x + right.x, y: left.y + right.y)
}
func += (inout left: CGPoint, right: CGPoint) {
left = left + right
}
func - (left: CGPoint, right: CGPoint) -> CGPoint {
return CGPoint(x: left.x - right.x, y: left.y - right.y)
}
func -= (inout left: CGPoint, right: CGPoint) {
left = left - right
}
func * (left: CGPoint, right: CGPoint) -> CGPoint {
return CGPoint(x: left.x * right.x, y: left.y * right.y)
}
func *= (inout left: CGPoint, right: CGPoint) {
left = left * right
}
func * (point: CGPoint, scalar: CGFloat) -> CGPoint {
return CGPoint(x: point.x * scalar, y: point.y * scalar)
}
func *= (inout point: CGPoint, scalar: CGFloat) {
point = point * scalar
}
func / (left: CGPoint, right: CGPoint) -> CGPoint {
return CGPoint(x: left.x / right.x, y: left.y / right.y)
}
func /= (inout left: CGPoint, right: CGPoint) {
left = left / right
}
func / (point: CGPoint, scalar: CGFloat) -> CGPoint {
return CGPoint(x: point.x / scalar, y: point.y / scalar)
}
func /= (inout point: CGPoint, scalar: CGFloat) {
point = point / scalar
}
#if !(arch(x86_64) || arch(arm64))
func atan2(y: CGFloat, x: CGFloat) -> CGFloat {
return CGFloat(atan2f(Float(y), Float(x)))
}
func sqrt(a: CGFloat) -> CGFloat {
return CGFloat(sqrtf(Float(a)))
}
#endif
extension CGPoint {
func length() -> CGFloat {
return sqrt(x*x + y*y)
}
func normalized() -> CGPoint {
return self / length()
}
var angle: CGFloat {
return atan2(y, x)
}
}
let π = CGFloat(M_PI)
func shortestAngleBetween(angle1: CGFloat,
angle2: CGFloat) -> CGFloat {
let twoπ = π * 2.0
var angle = (angle2 - angle1) % twoπ
if (angle >= π) {
angle = angle - twoπ
}
if (angle <= -π) {
angle = angle + twoπ
}
return angle
}
extension CGFloat {
func sign() -> CGFloat {
return (self >= 0.0) ? 1.0 : -1.0
}
}
extension CGFloat {
static func random() -> CGFloat {
return CGFloat(Float(arc4random()) / Float(UInt32.max))
}
static func random(min min: CGFloat, max: CGFloat) -> CGFloat {
assert(min < max)
return CGFloat.random() * (max - min) + min
}
} | mit | b32a35950fe3042abc5ebc90c18bff33 | 19.773913 | 65 | 0.612228 | 3.057618 | false | false | false | false |
tgrf/swiftBluetoothSerial | Classes/BluetoothSerial.swift | 1 | 10504 | //
// BluetoothSerial.swift (originally DZBluetoothSerialHandler.swift)
// HM10 Serial
//
// Created by Alex on 09-08-15.
// Copyright (c) 2015 Balancing Rock. All rights reserved.
//
// IMPORTANT: Don't forget to set the variable 'writeType' or else the whole thing might not work.
//
import UIKit
import CoreBluetooth
/// Global serial handler, don't forget to initialize it with init(delgate:)
var serial: BluetoothSerial!
// Delegate functions
public protocol BluetoothSerialDelegate {
// ** Required **
/// Called when de state of the CBCentralManager changes (e.g. when bluetooth is turned on/off)
func serialDidChangeState()
/// Called when a peripheral disconnected
func serialDidDisconnect(_ peripheral: CBPeripheral, error: NSError?)
// ** Optionals **
/// Called when a message is received
func serialDidReceiveString(_ message: String)
/// Called when a message is received
func serialDidReceiveBytes(_ bytes: [UInt8])
/// Called when a message is received
func serialDidReceiveData(_ data: Data)
/// Called when the RSSI of the connected peripheral is read
func serialDidReadRSSI(_ rssi: NSNumber)
/// Called when a new peripheral is discovered while scanning. Also gives the RSSI (signal strength)
func serialDidDiscoverPeripheral(_ peripheral: CBPeripheral, RSSI: NSNumber?)
/// Called when a peripheral is connected (but not yet ready for cummunication)
func serialDidConnect(_ peripheral: CBPeripheral)
/// Called when a pending connection failed
func serialDidFailToConnect(_ peripheral: CBPeripheral, error: NSError?)
/// Called when a peripheral is ready for communication
func serialIsReady(_ peripheral: CBPeripheral)
}
// Make some of the delegate functions optional
public extension BluetoothSerialDelegate {
func serialDidReceiveString(_ message: String) {}
func serialDidReceiveBytes(_ bytes: [UInt8]) {}
func serialDidReceiveData(_ data: Data) {}
func serialDidReadRSSI(_ rssi: NSNumber) {}
func serialDidDiscoverPeripheral(_ peripheral: CBPeripheral, RSSI: NSNumber?) {}
func serialDidConnect(_ peripheral: CBPeripheral) {}
func serialDidFailToConnect(_ peripheral: CBPeripheral, error: NSError?) {}
func serialIsReady(_ peripheral: CBPeripheral) {}
}
public final class BluetoothSerial: NSObject {
//MARK: Variables
/// The delegate object the BluetoothDelegate methods will be called upon
public var delegate: BluetoothSerialDelegate!
/// The CBCentralManager this bluetooth serial handler uses for... well, everything really
var centralManager: CBCentralManager!
/// The peripheral we're trying to connect to (nil if none)
public var pendingPeripheral: CBPeripheral?
/// The connected peripheral (nil if none is connected)
public var connectedPeripheral: CBPeripheral?
/// The characteristic 0xFFE1 we need to write to, of the connectedPeripheral
weak var writeCharacteristic: CBCharacteristic?
/// Whether this serial is ready to send and receive data
public var isReady: Bool {
get {
return centralManager.state == .poweredOn &&
connectedPeripheral != nil &&
writeCharacteristic != nil
}
}
/// Whether to write to the HM10 with or without response.
/// Legit HM10 modules (from JNHuaMao) require 'Write without Response',
/// while fake modules (e.g. from Bolutek) require 'Write with Response'.
public var writeType: CBCharacteristicWriteType = .withoutResponse
//MARK: functions
/// Always use this to initialize an instance
public init(delegate: BluetoothSerialDelegate) {
super.init()
self.delegate = delegate
centralManager = CBCentralManager(delegate: self, queue: nil)
}
/// Start scanning for peripherals
public func startScan() {
guard centralManager.state == .poweredOn else { return }
// start scanning for peripherals with correct service UUID
let uuid = CBUUID(string: "FFE0")
centralManager.scanForPeripherals(withServices: [uuid], options: nil)
// retrieve peripherals that are already connected
// see this stackoverflow question http://stackoverflow.com/questions/13286487
let peripherals = centralManager.retrieveConnectedPeripherals(withServices: [uuid])
for peripheral in peripherals {
delegate.serialDidDiscoverPeripheral(peripheral, RSSI: nil)
}
}
/// Stop scanning for peripherals
public func stopScan() {
centralManager.stopScan()
}
/// Try to connect to the given peripheral
public func connectToPeripheral(_ peripheral: CBPeripheral) {
pendingPeripheral = peripheral
centralManager.connect(peripheral, options: nil)
}
/// Disconnect from the connected peripheral or stop connecting to it
public func disconnect() {
if let p = connectedPeripheral {
centralManager.cancelPeripheralConnection(p)
} else if let p = pendingPeripheral {
centralManager.cancelPeripheralConnection(p) //TODO: Test whether its neccesary to set p to nil
}
}
/// The didReadRSSI delegate function will be called after calling this function
public func readRSSI() {
guard isReady else { return }
connectedPeripheral!.readRSSI()
}
/// Send a string to the device
public func sendMessageToDevice(_ message: String) {
guard isReady else { return }
if let data = message.data(using: String.Encoding.utf8) {
connectedPeripheral!.writeValue(data, for: writeCharacteristic!, type: writeType)
}
}
/// Send an array of bytes to the device
public func sendBytesToDevice(_ bytes: [UInt8]) {
guard isReady else { return }
let data = Data(bytes: UnsafePointer<UInt8>(bytes), count: bytes.count)
connectedPeripheral!.writeValue(data, for: writeCharacteristic!, type: writeType)
}
/// Send data to the device
public func sendDataToDevice(_ data: Data) {
guard isReady else { return }
connectedPeripheral!.writeValue(data, for: writeCharacteristic!, type: writeType)
}
}
extension BluetoothSerial: CBCentralManagerDelegate, CBPeripheralDelegate {
//MARK: CBCentralManagerDelegate functions
public func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber) {
// just send it to the delegate
delegate.serialDidDiscoverPeripheral(peripheral, RSSI: RSSI)
}
public func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) {
// set some stuff right
peripheral.delegate = self
pendingPeripheral = nil
connectedPeripheral = peripheral
// send it to the delegate
delegate.serialDidConnect(peripheral)
// Okay, the peripheral is connected but we're not ready yet!
// First get the 0xFFE0 service
// Then get the 0xFFE1 characteristic of this service
// Subscribe to it & create a weak reference to it (for writing later on),
// and then we're ready for communication
peripheral.discoverServices([CBUUID(string: "FFE0")])
}
public func centralManager(_ central: CBCentralManager, didDisconnectPeripheral peripheral: CBPeripheral, error: Error?) {
connectedPeripheral = nil
pendingPeripheral = nil
// send it to the delegate
delegate.serialDidDisconnect(peripheral, error: error as NSError?)
}
public func centralManager(_ central: CBCentralManager, didFailToConnect peripheral: CBPeripheral, error: Error?) {
pendingPeripheral = nil
// just send it to the delegate
delegate.serialDidFailToConnect(peripheral, error: error as NSError?)
}
public func centralManagerDidUpdateState(_ central: CBCentralManager) {
// note that "didDisconnectPeripheral" won't be called if BLE is turned off while connected
connectedPeripheral = nil
pendingPeripheral = nil
// send it to the delegate
delegate.serialDidChangeState()
}
//MARK: CBPeripheralDelegate functions
public func peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: Error?) {
// discover the 0xFFE1 characteristic for all services (though there should only be one)
for service in peripheral.services! {
peripheral.discoverCharacteristics([CBUUID(string: "FFE1")], for: service)
}
}
public func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, error: Error?) {
// check whether the characteristic we're looking for (0xFFE1) is present - just to be sure
for characteristic in service.characteristics! {
if characteristic.uuid == CBUUID(string: "FFE1") {
// subscribe to this value (so we'll get notified when there is serial data for us..)
peripheral.setNotifyValue(true, for: characteristic)
// keep a reference to this characteristic so we can write to it
writeCharacteristic = characteristic
// notify the delegate we're ready for communication
delegate.serialIsReady(peripheral)
}
}
}
public func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?) {
// notify the delegate in different ways
// if you don't use one of these, just comment it (for optimum efficiency :])
let data = characteristic.value
guard data != nil else { return }
// first the data
delegate.serialDidReceiveData(data!)
// then the string
if let str = String(data: data!, encoding: String.Encoding.utf8) {
delegate.serialDidReceiveString(str)
} else {
//print("Received an invalid string!") uncomment for debugging
}
// now the bytes array
var bytes = [UInt8](repeating: 0, count: data!.count / MemoryLayout<UInt8>.size)
(data! as NSData).getBytes(&bytes, length: data!.count)
delegate.serialDidReceiveBytes(bytes)
}
public func peripheral(_ peripheral: CBPeripheral, didReadRSSI RSSI: NSNumber, error: Error?) {
delegate.serialDidReadRSSI(RSSI)
}
}
| mit | 53195261d14d97c639be29d31e4fdba4 | 36.648746 | 155 | 0.687167 | 5.225871 | false | false | false | false |
ChristianDeckert/CDTools | CDTools/Foundation/CDAppCache.swift | 1 | 6106 | //
// CDAppCache.swift
// CDTools
//
// Created by Christian Deckert on 06.07.16.
// Copyright © 2016 Christian Deckert. All rights reserved.
//
import Foundation
// MARK: - CDAppCache: a simple singelton to cache and persist stuff
public typealias WatchAppCacheObserverCallback = (_ object: AnyObject?, _ key: String) -> Void
let _appCacheInstance = CDAppCache()
open class CDAppCache {
fileprivate var cache = Dictionary<String, AnyObject>()
open var suitName: String? = nil {
didSet {
if let suitName = self.suitName {
userDefaults = UserDefaults(suiteName: suitName)!
} else {
userDefaults = UserDefaults.standard
}
}
}
open var userDefaults: UserDefaults = UserDefaults.standard
open static func sharedCache() -> CDAppCache {
return _appCacheInstance
}
open func clear() {
_appCacheInstance.clear()
}
open func add(objectToCache object: AnyObject, forKey: String) -> Bool {
cache[forKey] = object
notifyObservers(forKey)
return true
}
open func objectForKey(_ key: String) -> AnyObject? {
return cache[key]
}
open func stringForKey(_ key: String) -> String? {
return objectForKey(key) as? String
}
open func integerForKey(_ key: String) -> Int? {
return objectForKey(key) as? Int
}
open func doubleForKey(_ key: String) -> Double? {
return objectForKey(key) as? Double
}
open func dictionaryForKey(_ key: String) -> Dictionary<String, AnyObject>? {
return objectForKey(key) as? Dictionary<String, AnyObject>
}
open func remove(_ key: String) {
cache[key] = nil
notifyObservers(key)
}
// MARK: - Oberserver
fileprivate var observers = Array<_WatchAppCacheObserver>()
// MARK: Private Helper Class _WatchAppCacheObserver
fileprivate class _WatchAppCacheObserver: NSObject {
weak var observer: NSObject?
var keys = Array<String>()
var callback: WatchAppCacheObserverCallback? = nil
func isObservingKey(_ key: String) -> Bool {
for k in keys {
if key == k {
return true
}
}
return false
}
init(observer: NSObject) {
self.observer = observer
}
}
open func addObserver(_ observer: NSObject, forKeys keys: Array<String>, callback: @escaping WatchAppCacheObserverCallback) {
let (internalObserverIndex, internalObserver) = findObserver(observer)
let newObserver: _WatchAppCacheObserver
if let internalObserver = internalObserver {
newObserver = internalObserver
} else {
newObserver = _WatchAppCacheObserver(observer: observer)
}
newObserver.keys.append(contentsOf: keys)
newObserver.callback = callback
if -1 == internalObserverIndex {
self.observers.append(newObserver)
self.notifyObserver(newObserver, keys: keys)
}
}
open func removeObserver(_ observer: NSObject) -> Bool {
let (internalObserverIndex, _) = findObserver(observer)
if -1 != internalObserverIndex {
self.observers.remove(at: internalObserverIndex)
return true
}
return false
}
fileprivate func findObserver(_ observer: NSObject) -> (Int, _WatchAppCacheObserver?) {
for (index, o) in self.observers.enumerated() {
if let obs = o.observer, obs == observer {
return (index, o)
}
}
return (-1, nil)
}
fileprivate func notifyObservers(_ key: String) {
for internalObserver in self.observers {
self.notifyObserver(internalObserver, key: key)
}
}
fileprivate func notifyObserver(_ observer: _WatchAppCacheObserver, keys: [String]) {
for key in keys {
self.notifyObserver(observer, key: key)
}
}
fileprivate func notifyObserver(_ observer: _WatchAppCacheObserver, key: String) {
if observer.isObservingKey(key) {
observer.callback?(self.objectForKey(key), key)
}
}
}
public extension CDAppCache {
public func persistObject(objectToPersist object: AnyObject, forKey key: String) {
userDefaults.set(object, forKey: key)
userDefaults.synchronize()
}
public func persistImage(imageToPersist image: UIImage, forKey: String) {
let persistBase64: (Data) -> Void = { (imageData) in
let base64image = imageData.base64EncodedString(options: NSData.Base64EncodingOptions())
self.userDefaults.set(base64image, forKey: forKey)
self.userDefaults.synchronize()
}
if let imageData = UIImagePNGRepresentation(image) {
persistBase64(imageData)
} else if let imageData = UIImageJPEGRepresentation(image, 1.0) {
persistBase64(imageData)
}
}
public func unpersistImage(_ forKey: String) {
self.removePersistedObject(forKey)
}
public func removePersistedObject(_ forKey: String) {
userDefaults.removeObject(forKey: forKey)
userDefaults.synchronize()
}
public func persistedObject(_ forKey: String) -> AnyObject? {
return userDefaults.object(forKey: forKey) as AnyObject
}
public func persistedImage(_ forKey: String) -> UIImage? {
if let base64string = persistedObject(forKey) as? String {
if let imageData = Data.init(base64Encoded: base64string, options: NSData.Base64DecodingOptions()) {
return UIImage(data: imageData)
}
}
return nil
}
public func persistedInt(_ forKey: String) -> Int? {
return persistedObject(forKey) as? Int
}
}
| mit | 5102a54ebdb466cc23d049c099953fb3 | 29.073892 | 129 | 0.598853 | 4.903614 | false | false | false | false |
Incipia/Goalie | Goalie/GoalieKerningButton.swift | 1 | 5617 | //
// GoalieKerningButton.swift
// Goalie
//
// Created by Gregory Klein on 1/2/16.
// Copyright © 2016 Incipia. All rights reserved.
//
import UIKit
/***
IMPORTANT NOTE: This class is meant to be used for labels in a storyboard or XIB file
***/
class GoalieKerningButton: UIButton
{
required init?(coder aDecoder: NSCoder)
{
super.init(coder: aDecoder)
guard let label = titleLabel else { return }
let paragraphStyle: NSMutableParagraphStyle = NSParagraphStyle.default.mutableCopy() as! NSMutableParagraphStyle
paragraphStyle.alignment = NSTextAlignment.center
let attributes = [
NSFontAttributeName : label.font,
NSForegroundColorAttributeName : label.textColor,
NSKernAttributeName : 3,
NSParagraphStyleAttributeName : paragraphStyle
] as [String : Any]
let highlightedAttributes = [
NSFontAttributeName : label.font,
NSForegroundColorAttributeName : label.textColor.withAlphaComponent(0.5),
NSKernAttributeName : 3,
NSParagraphStyleAttributeName : paragraphStyle
] as [String : Any]
let attributedString = NSAttributedString(string: label.text ?? "", attributes: attributes)
let highlightedAttributedString = NSAttributedString(string: label.text ?? "", attributes: highlightedAttributes)
UIView.performWithoutAnimation { () -> Void in
self.setAttributedTitle(attributedString, for: UIControlState())
self.setAttributedTitle(highlightedAttributedString, for: .highlighted)
}
}
func updateText(_ text: String, color: UIColor)
{
guard let label = titleLabel else { return }
let attributes = [
NSFontAttributeName : label.font,
NSForegroundColorAttributeName : color,
NSKernAttributeName : 3,
] as [String : Any]
let highlightedAttributes = [
NSFontAttributeName : label.font,
NSForegroundColorAttributeName : label.textColor.withAlphaComponent(0.5),
NSKernAttributeName : 3,
] as [String : Any]
let attributedString = NSAttributedString(string: text, attributes: attributes)
let highlightedAttributedString = NSAttributedString(string: text, attributes: highlightedAttributes)
UIView.performWithoutAnimation { () -> Void in
self.setAttributedTitle(attributedString, for: UIControlState())
self.setAttributedTitle(highlightedAttributedString, for: .highlighted)
self.layoutIfNeeded()
}
}
func updateText(_ text: String)
{
guard let label = titleLabel else { return }
let attributes = [
NSFontAttributeName : label.font,
NSForegroundColorAttributeName : label.textColor,
NSKernAttributeName : 1.5,
] as [String : Any]
let highlightedAttributes = [
NSFontAttributeName : label.font,
NSForegroundColorAttributeName : label.textColor.withAlphaComponent(0.5),
NSKernAttributeName : 1.5,
] as [String : Any]
let attributedString = NSAttributedString(string: text, attributes: attributes)
let highlightedAttributedString = NSAttributedString(string: text, attributes: highlightedAttributes)
UIView.performWithoutAnimation { () -> Void in
self.setAttributedTitle(attributedString, for: UIControlState())
self.setAttributedTitle(highlightedAttributedString, for: .highlighted)
self.layoutIfNeeded()
}
}
func updateTextColor(_ color: UIColor)
{
guard let label = titleLabel else { return }
guard let text = label.text else { return }
let attributes = [
NSFontAttributeName : label.font,
NSForegroundColorAttributeName : color,
NSKernAttributeName : 3
] as [String : Any]
let highlightedAttributes = [
NSFontAttributeName : label.font,
NSForegroundColorAttributeName : label.textColor.withAlphaComponent(0.5),
NSKernAttributeName : 3
] as [String : Any]
let attributedString = NSAttributedString(string: text, attributes: attributes)
let highlightedAttributedString = NSAttributedString(string: text, attributes: highlightedAttributes)
UIView.performWithoutAnimation { () -> Void in
self.setAttributedTitle(attributedString, for: UIControlState())
self.setAttributedTitle(highlightedAttributedString, for: .highlighted)
self.layoutIfNeeded()
}
}
func updateKerningValue(_ value: CGFloat)
{
guard let label = titleLabel else { return }
guard let text = label.text else { return }
let attributes = [
NSFontAttributeName : label.font,
NSForegroundColorAttributeName : label.textColor,
NSKernAttributeName : value
] as [String : Any]
let highlightedAttributes = [
NSFontAttributeName : label.font,
NSForegroundColorAttributeName : label.textColor.withAlphaComponent(0.5),
NSKernAttributeName : value
] as [String : Any]
let attributedString = NSAttributedString(string: text, attributes: attributes)
let highlightedAttributedString = NSAttributedString(string: text, attributes: highlightedAttributes)
UIView.performWithoutAnimation { () -> Void in
self.setAttributedTitle(attributedString, for: UIControlState())
self.setAttributedTitle(highlightedAttributedString, for: .highlighted)
self.layoutIfNeeded()
}
}
}
| apache-2.0 | a4091d22b0510bad587aa1dd0083ffce | 36.44 | 119 | 0.672009 | 5.807653 | false | false | false | false |
syershov/omim | iphone/Maps/UI/PlacePage/PlacePageLayout/Content/Cian/PPCianCarouselCell.swift | 1 | 3412 | @objc(MWMPPCianCarouselCell)
final class PPCianCarouselCell: MWMTableViewCell {
@IBOutlet private weak var title: UILabel! {
didSet {
title.text = L("subtitle_rent")
title.font = UIFont.bold14()
title.textColor = UIColor.blackSecondaryText()
}
}
@IBOutlet private weak var more: UIButton! {
didSet {
more.setImage(#imageLiteral(resourceName: "logo_cian"), for: .normal)
more.titleLabel?.font = UIFont.regular17()
more.setTitleColor(UIColor.linkBlue(), for: .normal)
}
}
@IBOutlet private weak var collectionView: UICollectionView!
var data: [CianItemModel]? {
didSet {
updateCollectionView { [weak self] in
self?.collectionView.reloadSections(IndexSet(integer: 0))
}
}
}
fileprivate let kMaximumNumberOfElements = 5
fileprivate var delegate: MWMPlacePageButtonsProtocol?
func config(delegate d: MWMPlacePageButtonsProtocol?) {
delegate = d
collectionView.contentOffset = .zero
collectionView.delegate = self
collectionView.dataSource = self
collectionView.register(cellClass: CianElement.self)
collectionView.reloadData()
isSeparatorHidden = true
backgroundColor = UIColor.clear
}
fileprivate func isLastCell(_ indexPath: IndexPath) -> Bool {
return indexPath.item == collectionView.numberOfItems(inSection: indexPath.section) - 1
}
override func didMoveToSuperview() {
super.didMoveToSuperview()
updateCollectionView(nil)
}
private func updateCollectionView(_ updates: (() -> Void)?) {
guard let sv = superview else { return }
let layout = collectionView.collectionViewLayout as! UICollectionViewFlowLayout
let screenSize = { sv.size.width - layout.sectionInset.left - layout.sectionInset.right }
let itemHeight: CGFloat = 136
let itemWidth: CGFloat
if let data = data {
if data.isEmpty {
itemWidth = screenSize()
} else {
itemWidth = 160
}
} else {
itemWidth = screenSize()
}
layout.itemSize = CGSize(width: itemWidth, height: itemHeight)
collectionView.performBatchUpdates(updates, completion: nil)
}
@IBAction
fileprivate func onMore() {
delegate?.openSponsoredURL(nil)
}
}
extension PPCianCarouselCell: UICollectionViewDelegate, UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withCellClass: CianElement.self,
indexPath: indexPath) as! CianElement
if let data = data {
if data.isEmpty {
cell.state = .error(onButtonAction: onMore)
} else {
let model = isLastCell(indexPath) ? nil : data[indexPath.item]
cell.state = .offer(model: model,
onButtonAction: { [unowned self] model in
self.delegate?.openSponsoredURL(model?.pageURL)
})
}
} else {
cell.state = .pending(onButtonAction: onMore)
}
return cell
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
if let data = data {
if data.isEmpty {
return 1
} else {
return min(data.count, kMaximumNumberOfElements) + 1
}
} else {
return 1
}
}
}
| apache-2.0 | 96074782072ce5fe2fae036ee81b41e4 | 31.188679 | 119 | 0.661489 | 4.792135 | false | false | false | false |
RobotPajamas/ble113-ota-ios | ble113-ota/DeviceListViewController.swift | 1 | 3111 | //
// ViewController.swift
// ble113-ota
//
// Created by Suresh Joshi on 2016-06-13.
// Copyright © 2016 Robot Pajamas. All rights reserved.
//
import UIKit
import LGBluetooth
class DeviceListViewController: UITableViewController {
private static let cellIdentifier = "cellIdentifier"
var scannedPeripherals = [BluegigaPeripheral]()
override func viewDidLoad() {
super.viewDidLoad()
setupUi()
initCoreBluetooth()
}
func setupUi() {
self.refreshControl = UIRefreshControl()
self.refreshControl!.attributedTitle = NSAttributedString(string: "Pull to refresh")
self.refreshControl!.addTarget(self, action: #selector(DeviceListViewController.scanForDevices), forControlEvents: UIControlEvents.ValueChanged)
self.tableView.addSubview(refreshControl!)
}
// This is a nothing function, strictly here to initialize CoreBluetooth
func initCoreBluetooth() {
let callback: LGCentralManagerDiscoverPeripheralsCallback = {
peripherals in
NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: #selector(DeviceListViewController.scanForDevices), userInfo: nil, repeats: false)
}
LGCentralManager.sharedInstance().scanForPeripheralsByInterval(1, completion: callback)
}
// The bulk of the advertising data is done here
func scanForDevices() {
let callback: LGCentralManagerDiscoverPeripheralsCallback = {
peripherals in
self.refreshControl!.endRefreshing()
for peripheral in peripherals {
let p = peripheral as! LGPeripheral
if p.name?.lowercaseString.containsString("robot pajamas") == true {
let bluegigaPeripheral = BluegigaPeripheral(fromPeripheral: p)
self.scannedPeripherals.append(bluegigaPeripheral)
}
}
self.tableView.reloadData()
}
print("Start scanning...")
scannedPeripherals.removeAll()
LGCentralManager.sharedInstance().scanForPeripheralsByInterval(5, completion: callback)
}
// MARK: UITableViewDataSource methods
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return scannedPeripherals.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(DeviceListViewController.cellIdentifier)
let peripheral = scannedPeripherals[indexPath.row]
cell!.textLabel?.text = peripheral.name
return cell!
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "goToFirmwareUpdate" {
let path = self.tableView.indexPathForSelectedRow!
let peripheral = scannedPeripherals[path.row]
let destination = segue.destinationViewController as! FirmwareUpdateViewController
destination.peripheral = peripheral
}
}
}
| mit | 9a4b12a9a9e960acbc920e0d709dbb6d | 36.02381 | 162 | 0.689711 | 5.514184 | false | false | false | false |
njdehoog/Spelt | Sources/Spelt/SiteServer.swift | 1 | 894 | import GCDWebServers
public class SiteServer {
private lazy var server = GCDWebServer()!
let directoryPath: String
let indexFilename: String
public init(directoryPath: String, indexFilename: String = "index.html") {
self.directoryPath = directoryPath
self.indexFilename = indexFilename
// log only warnings, errors and exceptions
GCDWebServer.setLogLevel(3)
server.addGETHandler(forBasePath: "/", directoryPath: directoryPath, indexFilename: indexFilename , cacheAge: 0, allowRangeRequests: true)
}
deinit {
server.stop()
}
open func run() throws {
try server.run(options: [:])
}
open func start(port: Int = 0) throws -> (URL, UInt) {
try server.start(options: [GCDWebServerOption_Port : port])
return (server.serverURL!, server.port)
}
}
| mit | 95ea0b09c7e0711b076bd177444653f7 | 28.8 | 146 | 0.635347 | 4.680628 | false | false | false | false |
XWJACK/Music | Music/Modules/Player/PlayerModel.swift | 1 | 965 | //
// PlayerModel.swift
// Music
//
// Created by Jack on 3/16/17.
// Copyright © 2017 Jack. All rights reserved.
//
import UIKit
//struct MusicPlayerResponse {
//
// struct Music {
//// var data = Data()
// var response: ((Data) -> ())? = nil
// var progress: ((Progress) -> ())? = nil
//
// init(response: ((Data) -> ())? = nil,
// progress: ((Progress) -> ())? = nil) {
//
// self.response = response
// self.progress = progress
// }
// }
//
// struct Lyric {
// var success: ((String) -> ())? = nil
// init(success: ((String) -> ())? = nil) {
//
// self.success = success
// }
// }
//
// var music: Music
// var lyric: Lyric
//
// var failed: ((Error) -> ())? = nil
//
// init(music: Music, lyric: Lyric) {
// self.music = music
// self.lyric = lyric
// }
//}
| mit | 2c72f03c43f823af494cdb481132b789 | 21.418605 | 53 | 0.429461 | 3.370629 | false | false | false | false |
shajrawi/swift | stdlib/public/core/UTF8.swift | 1 | 12373 | //===--- UTF8.swift -------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
extension Unicode {
@_frozen
public enum UTF8 {
case _swift3Buffer(Unicode.UTF8.ForwardParser)
}
}
extension Unicode.UTF8 {
/// Returns the number of code units required to encode the given Unicode
/// scalar.
///
/// Because a Unicode scalar value can require up to 21 bits to store its
/// value, some Unicode scalars are represented in UTF-8 by a sequence of up
/// to 4 code units. The first code unit is designated a *lead* byte and the
/// rest are *continuation* bytes.
///
/// let anA: Unicode.Scalar = "A"
/// print(anA.value)
/// // Prints "65"
/// print(UTF8.width(anA))
/// // Prints "1"
///
/// let anApple: Unicode.Scalar = "🍎"
/// print(anApple.value)
/// // Prints "127822"
/// print(UTF8.width(anApple))
/// // Prints "4"
///
/// - Parameter x: A Unicode scalar value.
/// - Returns: The width of `x` when encoded in UTF-8, from `1` to `4`.
@_alwaysEmitIntoClient
public static func width(_ x: Unicode.Scalar) -> Int {
switch x.value {
case 0..<0x80: return 1
case 0x80..<0x0800: return 2
case 0x0800..<0x1_0000: return 3
default: return 4
}
}
}
extension Unicode.UTF8 : _UnicodeEncoding {
public typealias CodeUnit = UInt8
public typealias EncodedScalar = _ValidUTF8Buffer
@inlinable
public static var encodedReplacementCharacter : EncodedScalar {
return EncodedScalar.encodedReplacementCharacter
}
@inline(__always)
@inlinable
public static func _isScalar(_ x: CodeUnit) -> Bool {
return isASCII(x)
}
/// Returns whether the given code unit represents an ASCII scalar
@_alwaysEmitIntoClient
@inline(__always)
public static func isASCII(_ x: CodeUnit) -> Bool {
return x & 0b1000_0000 == 0
}
@inline(__always)
@inlinable
public static func decode(_ source: EncodedScalar) -> Unicode.Scalar {
switch source.count {
case 1:
return Unicode.Scalar(_unchecked: source._biasedBits &- 0x01)
case 2:
let bits = source._biasedBits &- 0x0101
var value = (bits & 0b0_______________________11_1111__0000_0000) &>> 8
value |= (bits & 0b0________________________________0001_1111) &<< 6
return Unicode.Scalar(_unchecked: value)
case 3:
let bits = source._biasedBits &- 0x010101
var value = (bits & 0b0____________11_1111__0000_0000__0000_0000) &>> 16
value |= (bits & 0b0_______________________11_1111__0000_0000) &>> 2
value |= (bits & 0b0________________________________0000_1111) &<< 12
return Unicode.Scalar(_unchecked: value)
default:
_internalInvariant(source.count == 4)
let bits = source._biasedBits &- 0x01010101
var value = (bits & 0b0_11_1111__0000_0000__0000_0000__0000_0000) &>> 24
value |= (bits & 0b0____________11_1111__0000_0000__0000_0000) &>> 10
value |= (bits & 0b0_______________________11_1111__0000_0000) &<< 4
value |= (bits & 0b0________________________________0000_0111) &<< 18
return Unicode.Scalar(_unchecked: value)
}
}
@inline(__always)
@inlinable
public static func encode(
_ source: Unicode.Scalar
) -> EncodedScalar? {
var c = source.value
if _fastPath(c < (1&<<7)) {
return EncodedScalar(_containing: UInt8(c))
}
var o = c & 0b0__0011_1111
c &>>= 6
o &<<= 8
if _fastPath(c < (1&<<5)) {
return EncodedScalar(_biasedBits: (o | c) &+ 0b0__1000_0001__1100_0001)
}
o |= c & 0b0__0011_1111
c &>>= 6
o &<<= 8
if _fastPath(c < (1&<<4)) {
return EncodedScalar(
_biasedBits: (o | c) &+ 0b0__1000_0001__1000_0001__1110_0001)
}
o |= c & 0b0__0011_1111
c &>>= 6
o &<<= 8
return EncodedScalar(
_biasedBits: (o | c ) &+ 0b0__1000_0001__1000_0001__1000_0001__1111_0001)
}
@inlinable
@inline(__always)
public static func transcode<FromEncoding : _UnicodeEncoding>(
_ content: FromEncoding.EncodedScalar, from _: FromEncoding.Type
) -> EncodedScalar? {
if _fastPath(FromEncoding.self == UTF16.self) {
let c = _identityCast(content, to: UTF16.EncodedScalar.self)
var u0 = UInt16(truncatingIfNeeded: c._storage)
if _fastPath(u0 < 0x80) {
return EncodedScalar(_containing: UInt8(truncatingIfNeeded: u0))
}
var r = UInt32(u0 & 0b0__11_1111)
r &<<= 8
u0 &>>= 6
if _fastPath(u0 < (1&<<5)) {
return EncodedScalar(
_biasedBits: (UInt32(u0) | r) &+ 0b0__1000_0001__1100_0001)
}
r |= UInt32(u0 & 0b0__11_1111)
r &<<= 8
if _fastPath(u0 & (0xF800 &>> 6) != (0xD800 &>> 6)) {
u0 &>>= 6
return EncodedScalar(
_biasedBits: (UInt32(u0) | r) &+ 0b0__1000_0001__1000_0001__1110_0001)
}
}
else if _fastPath(FromEncoding.self == UTF8.self) {
return _identityCast(content, to: UTF8.EncodedScalar.self)
}
return encode(FromEncoding.decode(content))
}
@_fixed_layout
public struct ForwardParser {
public typealias _Buffer = _UIntBuffer<UInt8>
@inline(__always)
@inlinable
public init() { _buffer = _Buffer() }
public var _buffer: _Buffer
}
@_fixed_layout
public struct ReverseParser {
public typealias _Buffer = _UIntBuffer<UInt8>
@inline(__always)
@inlinable
public init() { _buffer = _Buffer() }
public var _buffer: _Buffer
}
}
extension UTF8.ReverseParser : Unicode.Parser, _UTFParser {
public typealias Encoding = Unicode.UTF8
@inline(__always)
@inlinable
public func _parseMultipleCodeUnits() -> (isValid: Bool, bitCount: UInt8) {
_internalInvariant(_buffer._storage & 0x80 != 0) // this case handled elsewhere
if _buffer._storage & 0b0__1110_0000__1100_0000
== 0b0__1100_0000__1000_0000 {
// 2-byte sequence. Top 4 bits of decoded result must be nonzero
let top4Bits = _buffer._storage & 0b0__0001_1110__0000_0000
if _fastPath(top4Bits != 0) { return (true, 2*8) }
}
else if _buffer._storage & 0b0__1111_0000__1100_0000__1100_0000
== 0b0__1110_0000__1000_0000__1000_0000 {
// 3-byte sequence. The top 5 bits of the decoded result must be nonzero
// and not a surrogate
let top5Bits = _buffer._storage & 0b0__1111__0010_0000__0000_0000
if _fastPath(
top5Bits != 0 && top5Bits != 0b0__1101__0010_0000__0000_0000) {
return (true, 3*8)
}
}
else if _buffer._storage & 0b0__1111_1000__1100_0000__1100_0000__1100_0000
== 0b0__1111_0000__1000_0000__1000_0000__1000_0000 {
// Make sure the top 5 bits of the decoded result would be in range
let top5bits = _buffer._storage
& 0b0__0111__0011_0000__0000_0000__0000_0000
if _fastPath(
top5bits != 0
&& top5bits <= 0b0__0100__0000_0000__0000_0000__0000_0000
) { return (true, 4*8) }
}
return (false, _invalidLength() &* 8)
}
/// Returns the length of the invalid sequence that ends with the LSB of
/// buffer.
@inline(never)
@usableFromInline
internal func _invalidLength() -> UInt8 {
if _buffer._storage & 0b0__1111_0000__1100_0000
== 0b0__1110_0000__1000_0000 {
// 2-byte prefix of 3-byte sequence. The top 5 bits of the decoded result
// must be nonzero and not a surrogate
let top5Bits = _buffer._storage & 0b0__1111__0010_0000
if top5Bits != 0 && top5Bits != 0b0__1101__0010_0000 { return 2 }
}
else if _buffer._storage & 0b1111_1000__1100_0000
== 0b1111_0000__1000_0000
{
// 2-byte prefix of 4-byte sequence
// Make sure the top 5 bits of the decoded result would be in range
let top5bits = _buffer._storage & 0b0__0111__0011_0000
if top5bits != 0 && top5bits <= 0b0__0100__0000_0000 { return 2 }
}
else if _buffer._storage & 0b0__1111_1000__1100_0000__1100_0000
== 0b0__1111_0000__1000_0000__1000_0000 {
// 3-byte prefix of 4-byte sequence
// Make sure the top 5 bits of the decoded result would be in range
let top5bits = _buffer._storage & 0b0__0111__0011_0000__0000_0000
if top5bits != 0 && top5bits <= 0b0__0100__0000_0000__0000_0000 {
return 3
}
}
return 1
}
@inline(__always)
@inlinable
public func _bufferedScalar(bitCount: UInt8) -> Encoding.EncodedScalar {
let x = UInt32(truncatingIfNeeded: _buffer._storage.byteSwapped)
let shift = 32 &- bitCount
return Encoding.EncodedScalar(_biasedBits: (x &+ 0x01010101) &>> shift)
}
}
extension Unicode.UTF8.ForwardParser : Unicode.Parser, _UTFParser {
public typealias Encoding = Unicode.UTF8
@inline(__always)
@inlinable
public func _parseMultipleCodeUnits() -> (isValid: Bool, bitCount: UInt8) {
_internalInvariant(_buffer._storage & 0x80 != 0) // this case handled elsewhere
if _buffer._storage & 0b0__1100_0000__1110_0000
== 0b0__1000_0000__1100_0000 {
// 2-byte sequence. At least one of the top 4 bits of the decoded result
// must be nonzero.
if _fastPath(_buffer._storage & 0b0_0001_1110 != 0) { return (true, 2*8) }
}
else if _buffer._storage & 0b0__1100_0000__1100_0000__1111_0000
== 0b0__1000_0000__1000_0000__1110_0000 {
// 3-byte sequence. The top 5 bits of the decoded result must be nonzero
// and not a surrogate
let top5Bits = _buffer._storage & 0b0___0010_0000__0000_1111
if _fastPath(top5Bits != 0 && top5Bits != 0b0___0010_0000__0000_1101) {
return (true, 3*8)
}
}
else if _buffer._storage & 0b0__1100_0000__1100_0000__1100_0000__1111_1000
== 0b0__1000_0000__1000_0000__1000_0000__1111_0000 {
// 4-byte sequence. The top 5 bits of the decoded result must be nonzero
// and no greater than 0b0__0100_0000
let top5bits = UInt16(_buffer._storage & 0b0__0011_0000__0000_0111)
if _fastPath(
top5bits != 0
&& top5bits.byteSwapped <= 0b0__0000_0100__0000_0000
) { return (true, 4*8) }
}
return (false, _invalidLength() &* 8)
}
/// Returns the length of the invalid sequence that starts with the LSB of
/// buffer.
@inline(never)
@usableFromInline
internal func _invalidLength() -> UInt8 {
if _buffer._storage & 0b0__1100_0000__1111_0000
== 0b0__1000_0000__1110_0000 {
// 2-byte prefix of 3-byte sequence. The top 5 bits of the decoded result
// must be nonzero and not a surrogate
let top5Bits = _buffer._storage & 0b0__0010_0000__0000_1111
if top5Bits != 0 && top5Bits != 0b0__0010_0000__0000_1101 { return 2 }
}
else if _buffer._storage & 0b0__1100_0000__1111_1000
== 0b0__1000_0000__1111_0000
{
// Prefix of 4-byte sequence. The top 5 bits of the decoded result
// must be nonzero and no greater than 0b0__0100_0000
let top5bits = UInt16(_buffer._storage & 0b0__0011_0000__0000_0111)
if top5bits != 0 && top5bits.byteSwapped <= 0b0__0000_0100__0000_0000 {
return _buffer._storage & 0b0__1100_0000__0000_0000__0000_0000
== 0b0__1000_0000__0000_0000__0000_0000 ? 3 : 2
}
}
return 1
}
@inlinable
public func _bufferedScalar(bitCount: UInt8) -> Encoding.EncodedScalar {
let x = UInt32(_buffer._storage) &+ 0x01010101
return _ValidUTF8Buffer(_biasedBits: x & ._lowBits(bitCount))
}
}
| apache-2.0 | 12e3a90f0f3abf77728615b88fe38186 | 36.828746 | 83 | 0.574535 | 3.691435 | false | false | false | false |
doncl/shortness-of-pants | BBPTable/BBPTable/BBPTableViewController.swift | 1 | 7746 | //
// ViewController.swift
// BBPTable
//
// Created by Don Clore on 8/3/15.
// Copyright (c) 2015 Beer Barrel Poker Studios. All rights reserved.
//
import UIKit
enum TableLoadMode {
case defaultView
case createView
}
class BBPTableViewController: UIViewController, UICollectionViewDataSource,
UICollectionViewDelegate {
//MARK: properties
var tableProperties: TableProperties?
var model: BBPTableModel?
var nonFixedView: UICollectionView?
var fixedView: UICollectionView?
var fixedModel: BBPTableModel?
var nonFixedModel: BBPTableModel?
var loadMode: TableLoadMode
var viewWidth: CGFloat?
//MARK: Initialization
init(loadMode: TableLoadMode) {
self.loadMode = loadMode
super.init(nibName: nil, bundle: nil)
}
convenience init(loadMode: TableLoadMode, width: CGFloat) {
self.init(loadMode: loadMode)
viewWidth = width
}
required init?(coder aDecoder: NSCoder) {
loadMode = .defaultView
super.init(coder: aDecoder)
}
override func loadView() {
BBPTableCell.initializeCellProperties(tableProperties!)
BBPTableModel.buildFixedAndNonFixedModels(model!, fixedColumnModel: &fixedModel,
nonFixedColumnModel: &nonFixedModel,
fixedColumnCount: tableProperties!.fixedColumns!)
let fixedLayout = BBPTableLayout()
fixedLayout.calculateCellSizes(fixedModel!)
let nonFixedLayout = BBPTableLayout()
nonFixedLayout.calculateCellSizes(nonFixedModel!)
if loadMode == .defaultView {
super.loadView() // Go ahead and call superclass to get a plain vanilla UIView.
} else {
let frame = CGRect(x: 0, y:0, width:viewWidth!, height: fixedLayout.tableHeight!)
self.view = UIView(frame: frame)
}
fixedView = createCollectionView(view, layout: fixedLayout, x: 0.0,
width: fixedLayout.tableWidth!, fixed: true)
let nonFixedX = view.frame.origin.x + fixedLayout.tableWidth!
let nonFixedWidth = view.frame.size.width - nonFixedX
nonFixedView = createCollectionView(view, layout: nonFixedLayout,
x: nonFixedX, width: nonFixedWidth, fixed: false)
nonFixedView!.isScrollEnabled = true
nonFixedView!.showsHorizontalScrollIndicator = true
}
fileprivate func createCollectionView(_ parentView: UIView,
layout: BBPTableLayout, x: CGFloat, width: CGFloat, fixed: Bool) -> UICollectionView {
// N.B. There's some hackery here to compensate for the fact that this control wasn't
// written with autolayout (more's the pity). It was early on - I'd only been doing
// iOS for about 5 months, and I shied away from doing AutoLayout in code. There's
// some tech debt here - I've just patched it up well enough to work for now.
var tabBarOffset : CGFloat = 0.0
var navBarOffset : CGFloat = 0.0
if let nav = navigationController {
navBarOffset += nav.navigationBar.frame.height
}
if let tab = tabBarController {
tabBarOffset += tab.tabBar.frame.height
}
let statusBarOffset = UIApplication.shared.statusBarFrame.height
let height = parentView.frame.height - (navBarOffset + tabBarOffset + statusBarOffset)
let frame = CGRect(x: x, y:parentView.frame.origin.y + navBarOffset + statusBarOffset,
width:width, height: height)
let collectionView = UICollectionView(frame: frame, collectionViewLayout: layout)
parentView.addSubview(collectionView)
collectionView.bounces = false
collectionView.showsVerticalScrollIndicator = false
collectionView.delegate = self
collectionView.dataSource = self
collectionView.register(BBPTableCell.self,
forCellWithReuseIdentifier: "cellIdentifier")
collectionView.backgroundColor = UIColor.white
collectionView.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
collectionView.topAnchor.constraint(equalTo: parentView.safeAreaLayoutGuide.topAnchor),
collectionView.leftAnchor.constraint(equalTo: parentView.safeAreaLayoutGuide.leftAnchor, constant: x),
collectionView.bottomAnchor.constraint(equalTo: parentView.safeAreaLayoutGuide.bottomAnchor),
])
if fixed {
collectionView.widthAnchor.constraint(equalToConstant: width).isActive = true
} else {
collectionView.rightAnchor.constraint(equalTo: parentView.safeAreaLayoutGuide.rightAnchor).isActive = true
}
return collectionView
}
//MARK: Handling synchronized scrolling.
func scrollViewDidScroll(_ scrollView: UIScrollView) {
if scrollView == fixedView! {
matchScrollView(nonFixedView!, second:fixedView!)
} else {
matchScrollView(fixedView!, second: nonFixedView!)
}
}
fileprivate func matchScrollView(_ first: UIScrollView, second: UIScrollView) {
var offset = first.contentOffset
offset.y = second.contentOffset.y
first.setContentOffset(offset, animated:false)
}
//MARK: UICollectionViewDataSource methods
func collectionView(_ collectionView: UICollectionView,
numberOfItemsInSection section: Int) -> Int {
let model = getModel(collectionView)
return model.numberOfColumns
}
func collectionView(_ collectionView: UICollectionView,
cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let model = getModel(collectionView)
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cellIdentifier",
for: indexPath) as! BBPTableCell
let layout = collectionView.collectionViewLayout as! BBPTableLayout
let columnIdx = indexPath.row
let rowIdx = indexPath.section
let cellData = model.dataAtLocation(rowIdx, column: columnIdx)
let cellType = getCellType(indexPath)
cell.setupCellInfo(cellType)
cell.setCellText(cellData)
let columnWidth = layout.columnWidths[columnIdx]
cell.contentView.bounds = CGRect(x:0, y:0, width:columnWidth, height: layout.rowHeight!)
return cell
}
func numberOfSections(in collectionView: UICollectionView) -> Int {
let model = getModel(collectionView)
return model.numberOfRows
}
fileprivate func getCellType(_ indexPath: IndexPath) -> CellType {
var cellType: CellType
if indexPath.section == 0 {
cellType = .columnHeading
} else if ((indexPath.section + 1) % 2) == 0 {
cellType = .dataEven
} else {
cellType = .dataOdd
}
return cellType
}
fileprivate func getModel(_ view: UICollectionView) -> BBPTableModel {
if (view == fixedView!) {
return fixedModel!
} else {
return nonFixedModel!
}
}
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransition(to: size, with: coordinator)
guard let nonFixed = nonFixedView, let fixed = fixedView else {
return
}
nonFixed.collectionViewLayout.invalidateLayout()
fixed.collectionViewLayout.invalidateLayout()
coordinator.animate(alongsideTransition: { ctxt in
nonFixed.layoutIfNeeded()
fixed.layoutIfNeeded()
}, completion: nil)
}
}
| mit | 5db121065a620311eb2d58a47a679ea9 | 36.062201 | 116 | 0.66047 | 5.129801 | false | false | false | false |
telip007/ChatFire | ChatFire/Modals/User.swift | 1 | 1293 | //
// User.swift
// ChatFire
//
// Created by Talip Göksu on 05.09.16.
// Copyright © 2016 ChatFire. All rights reserved.
//
import Firebase
import Foundation
private let userCache = NSCache()
class User: NSObject {
var email: String?
var username: String?
var partners: [String: AnyObject]?
var chats: [String: AnyObject]?
var profile_image: String?
var uid: String?
class func userFromId(id: String, user: (User) -> ()){
if let cachedUser = userCache.objectForKey(id) as? User{
user(cachedUser)
}
else{
let userRef = ref?.child("users/\(id)")
userRef?.observeSingleEventOfType(.Value, withBlock: { (data) in
if let userData = data.value as? [String: AnyObject]{
let retUser = User()
retUser.setValuesForKeysWithDictionary(userData)
userCache.setObject(retUser, forKey: id)
user(retUser)
}
else{
fatalError("What went wrong here ?")
}
})
}
}
class func getCurrentUser(data: (User) -> ()){
userFromId(currentUser!.uid) { (user) in
data(user)
}
}
}
| apache-2.0 | 1986fd31ca2f0b6003c022a5d50ea09b | 25.346939 | 76 | 0.529047 | 4.391156 | false | false | false | false |
IngmarStein/swift | benchmark/single-source/Phonebook.swift | 4 | 2427 | //===--- Phonebook.swift --------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
// This test is based on util/benchmarks/Phonebook, with modifications
// for performance measuring.
import TestsUtils
var words = [
"James", "John", "Robert", "Michael", "William", "David", "Richard", "Joseph",
"Charles", "Thomas", "Christopher", "Daniel", "Matthew", "Donald", "Anthony",
"Paul", "Mark", "George", "Steven", "Kenneth", "Andrew", "Edward", "Brian",
"Joshua", "Kevin", "Ronald", "Timothy", "Jason", "Jeffrey", "Gary", "Ryan",
"Nicholas", "Eric", "Stephen", "Jacob", "Larry", "Frank", "Jonathan", "Scott",
"Justin", "Raymond", "Brandon", "Gregory", "Samuel", "Patrick", "Benjamin",
"Jack", "Dennis", "Jerry", "Alexander", "Tyler", "Douglas", "Henry", "Peter",
"Walter", "Aaron", "Jose", "Adam", "Harold", "Zachary", "Nathan", "Carl",
"Kyle", "Arthur", "Gerald", "Lawrence", "Roger", "Albert", "Keith", "Jeremy",
"Terry", "Joe", "Sean", "Willie", "Jesse", "Ralph", "Billy", "Austin", "Bruce",
"Christian", "Roy", "Bryan", "Eugene", "Louis", "Harry", "Wayne", "Ethan",
"Jordan", "Russell", "Alan", "Philip", "Randy", "Juan", "Howard", "Vincent",
"Bobby", "Dylan", "Johnny", "Phillip", "Craig"
]
// This is a phone book record.
struct Record : Comparable {
var first: String
var last: String
init(_ first_ : String,_ last_ : String) {
first = first_
last = last_
}
}
func ==(lhs: Record, rhs: Record) -> Bool {
return lhs.last == rhs.last && lhs.first == rhs.first
}
func <(lhs: Record, rhs: Record) -> Bool {
if lhs.last < rhs.last {
return true
}
if lhs.last > rhs.last {
return false
}
if lhs.first < rhs.first {
return true
}
return false
}
@inline(never)
public func run_Phonebook(_ N: Int) {
// The list of names in the phonebook.
var Names : [Record] = []
for first in words {
for last in words {
Names.append(Record(first, last))
}
}
for _ in 1...N {
var t = Names
t.sort()
}
}
| apache-2.0 | 18e2c375497168108de8aca1c8ef7cba | 31.36 | 81 | 0.578904 | 3.223108 | false | false | false | false |
tobiasstraub/bwinf-releases | BwInf 34 (2015-2016)/Runde 2/Aufgabe 2/Marian/Source/main.swift | 2 | 1885 |
import Foundation
import Darwin
let task = TaskReader().read()
// Asynchron die Befehle abfragen:
dispatch_async(dispatch_queue_create("missglueckte_drohnenlieferung_commands", DISPATCH_QUEUE_CONCURRENT)) {
print("Verwende 'help' für eine Übersicht der Befehle.")
while true {
if let input = readLine() {
if input == "h" || input == "help" {
print("help / h - Hilfeübersicht anzeigen")
print("quit / q - Programm beenden")
print("info / i - Aktuell beste Schrittanzahl anzeigen")
print("save / s - Bisher beste Lösung speichern")
} else if input == "q" || input == "quit" {
exit(0)
} else if input == "i" || input == "info" {
if let bestSolution = task.bestSolution {
print("Die beste gefundene Lösung benötigt \(bestSolution.moves[0][0].characters.count) Schritte.")
} else {
print("Es wurde noch keine Lösung gefunden.")
}
} else if input == "s" || input == "save" {
if let bestSolution = task.bestSolution {
do {
try bestSolution.solutionString.writeToFile("solution.txt", atomically: false, encoding: NSUTF8StringEncoding)
print("Die zurzeit beste Lösung wurde in der Datei 'solution.txt' gespeichert.")
} catch {
print("Die Datei konnte nicht erstellt werden.")
}
} else {
print("Es wurde noch keine Lösung gefunden.")
}
}
}
}
}
task.run()
print("Das Programm ist nun fertig. Es können weiterhin Befehle eingegeben werden.")
// Endlosschleife, damit weiterhin Befehle abgefragt werden können:
while true {}
| gpl-3.0 | 7d0854136e0b4f04bfced29a8da0242d | 39.73913 | 134 | 0.545358 | 3.667319 | false | false | false | false |
iOSDevLog/iOSDevLog | 2048-Xcode7/2048/ModelSingleton.swift | 1 | 701 | //
// ModelSingleton.swift
// 2048
//
// Created by JiaXianhua on 15/9/14.
// Copyright (c) 2015年 jiaxianhua. All rights reserved.
//
import UIKit
class ModelSingleton: NSObject {
var tiles: Dictionary<NSIndexPath, Int>!
let dimension: Int = 4
let threshold: Int = 2048
class var sharedInstance : ModelSingleton {
struct Static {
static var onceToken : dispatch_once_t = 0
static var instance : ModelSingleton? = nil
}
dispatch_once(&Static.onceToken) {
Static.instance = ModelSingleton()
Static.instance?.tiles = Dictionary<NSIndexPath, Int>()
}
return Static.instance!
}
}
| mit | ccade37c2788bac7a1293c6a7a4fd09f | 23.964286 | 67 | 0.612303 | 4.288344 | false | false | false | false |
ivanbruel/TextStyle | Example/TextStyle/ViewController.swift | 1 | 1168 | //
// ViewController.swift
// TextStyle
//
// Created by Ivan Bruel on 09/01/2016.
// Copyright (c) 2016 Ivan Bruel. All rights reserved.
//
import UIKit
import TextStyle
import RxSwift
class ViewController: UIViewController {
@IBOutlet var labels: [UILabel]!
fileprivate let disposeBag = DisposeBag()
override func viewDidLoad() {
super.viewDidLoad()
let textStyles: [TextStyle] = [.title1, .title2, .headline, .subheadline, .body,
.caption1, .caption2, .footnote, .callout]
let texts: [String] = ["Title1", "Title2", "Headline", "Subheadline", "Body", "Caption1",
"Caption2", "Footnote", "Callout"]
for index in 0..<labels.count {
let label = labels[index]
let textStyle = textStyles[index]
let text = texts[index]
label.text = text
textStyle.rx_font.bindTo(label.rx.font)
.addDisposableTo(disposeBag)
}
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| mit | 05a7ffaa1058e971a7e50708b1f30542 | 26.162791 | 93 | 0.640411 | 4.18638 | false | false | false | false |
johnno1962d/swift | test/SILGen/generic_closures.swift | 1 | 6121 | // RUN: %target-swift-frontend -parse-stdlib -emit-silgen %s | FileCheck %s
import Swift
var zero: Int
// CHECK-LABEL: sil hidden @_TF16generic_closures28generic_nondependent_context{{.*}}
func generic_nondependent_context<T>(_ x: T, y: Int) -> Int {
func foo() -> Int { return y }
// CHECK: [[FOO:%.*]] = function_ref @_TFF16generic_closures28generic_nondependent_context{{.*}} : $@convention(thin) (Int) -> Int
// CHECK: [[FOO_CLOSURE:%.*]] = apply [[FOO]]
return foo()
}
// CHECK-LABEL: sil hidden @_TF16generic_closures15generic_capture{{.*}}
func generic_capture<T>(_ x: T) -> Any.Type {
func foo() -> Any.Type { return T.self }
// CHECK: [[FOO:%.*]] = function_ref @_TFF16generic_closures15generic_capture{{.*}} : $@convention(thin) <τ_0_0> () -> @thick protocol<>.Type
// CHECK: [[FOO_CLOSURE:%.*]] = apply [[FOO]]
return foo()
}
// CHECK-LABEL: sil hidden @_TF16generic_closures20generic_capture_cast{{.*}}
func generic_capture_cast<T>(_ x: T, y: Any) -> Bool {
func foo(_ a: Any) -> Bool { return a is T }
// CHECK: [[FOO:%.*]] = function_ref @_TFF16generic_closures20generic_capture_cast{{.*}} : $@convention(thin) <τ_0_0> (@in protocol<>) -> Bool
// CHECK: [[FOO_CLOSURE:%.*]] = apply [[FOO]]
return foo(y)
}
protocol Concept {
var sensical: Bool { get }
}
// CHECK-LABEL: sil hidden @_TF16generic_closures29generic_nocapture_existential{{.*}}
func generic_nocapture_existential<T>(_ x: T, y: Concept) -> Bool {
func foo(_ a: Concept) -> Bool { return a.sensical }
// CHECK: [[FOO:%.*]] = function_ref @_TFF16generic_closures29generic_nocapture_existential{{.*}} : $@convention(thin) (@in Concept) -> Bool
// CHECK: [[FOO_CLOSURE:%.*]] = apply [[FOO]]
return foo(y)
}
// CHECK-LABEL: sil hidden @_TF16generic_closures25generic_dependent_context{{.*}}
func generic_dependent_context<T>(_ x: T, y: Int) -> T {
func foo() -> T { return x }
// CHECK: [[FOO:%.*]] = function_ref @_TFF16generic_closures25generic_dependent_context{{.*}} : $@convention(thin) <τ_0_0> (@owned @box τ_0_0) -> @out τ_0_0
// CHECK: [[FOO_CLOSURE:%.*]] = apply [[FOO]]<T>
return foo()
}
enum Optionable<Wrapped> {
case none
case some(Wrapped)
}
class NestedGeneric<U> {
class func generic_nondependent_context<T>(_ x: T, y: Int, z: U) -> Int {
func foo() -> Int { return y }
return foo()
}
class func generic_dependent_inner_context<T>(_ x: T, y: Int, z: U) -> T {
func foo() -> T { return x }
return foo()
}
class func generic_dependent_outer_context<T>(_ x: T, y: Int, z: U) -> U {
func foo() -> U { return z }
return foo()
}
class func generic_dependent_both_contexts<T>(_ x: T, y: Int, z: U) -> (T, U) {
func foo() -> (T, U) { return (x, z) }
return foo()
}
// CHECK-LABEL: sil hidden @_TFC16generic_closures13NestedGeneric20nested_reabstraction{{.*}}
// CHECK: [[REABSTRACT:%.*]] = function_ref @_TTRG__rXFo___XFo_iT__iT__
// CHECK: partial_apply [[REABSTRACT]]<U, T>
func nested_reabstraction<T>(_ x: T) -> Optionable<() -> ()> {
return .some({})
}
}
// <rdar://problem/15417773>
// Ensure that nested closures capture the generic parameters of their nested
// context.
// CHECK: sil hidden @_TF16generic_closures25nested_closure_in_generic{{.*}} : $@convention(thin) <T> (@in T) -> @out T
// CHECK: function_ref [[OUTER_CLOSURE:@_TFF16generic_closures25nested_closure_in_genericurFxxU_FT_Q_]]
// CHECK: sil shared [[OUTER_CLOSURE]] : $@convention(thin) <T> (@inout_aliasable T) -> @out T
// CHECK: function_ref [[INNER_CLOSURE:@_TFFF16generic_closures25nested_closure_in_genericurFxxU_FT_Q_U_FT_Q_]]
// CHECK: sil shared [[INNER_CLOSURE]] : $@convention(thin) <T> (@inout_aliasable T) -> @out T {
func nested_closure_in_generic<T>(_ x:T) -> T {
return { { x }() }()
}
// CHECK-LABEL: sil hidden @_TF16generic_closures16local_properties
func local_properties<T>(_ t: inout T) {
// CHECK: [[TBOX:%[0-9]+]] = alloc_box $T
var prop: T {
get {
return t
}
set {
t = newValue
}
}
// CHECK: [[GETTER_REF:%[0-9]+]] = function_ref [[GETTER_CLOSURE:@_TFF16generic_closures16local_properties.*]] : $@convention(thin) <τ_0_0> (@owned @box τ_0_0) -> @out τ_0_0
// CHECK: apply [[GETTER_REF]]
t = prop
// CHECK: [[SETTER_REF:%[0-9]+]] = function_ref [[SETTER_CLOSURE:@_TFF16generic_closures16local_properties.*]] : $@convention(thin) <τ_0_0> (@in τ_0_0, @owned @box τ_0_0) -> ()
// CHECK: apply [[SETTER_REF]]
prop = t
var prop2: T {
get {
return t
}
set {
// doesn't capture anything
}
}
// CHECK: [[GETTER2_REF:%[0-9]+]] = function_ref [[GETTER2_CLOSURE:@_TFF16generic_closures16local_properties.*]] : $@convention(thin) <τ_0_0> (@owned @box τ_0_0) -> @out τ_0_0
// CHECK: apply [[GETTER2_REF]]
t = prop2
// CHECK: [[SETTER2_REF:%[0-9]+]] = function_ref [[SETTER2_CLOSURE:@_TFF16generic_closures16local_properties.*]] : $@convention(thin) <τ_0_0> (@in τ_0_0) -> ()
// CHECK: apply [[SETTER2_REF]]
prop2 = t
}
protocol Fooable {
static func foo() -> Bool
}
// <rdar://problem/16399018>
func shmassert(_ f: @autoclosure () -> Bool) {}
// CHECK-LABEL: sil hidden @_TF16generic_closures21capture_generic_param
func capture_generic_param<A: Fooable>(_ x: A) {
shmassert(A.foo())
}
// Make sure we use the correct convention when capturing class-constrained
// member types: <rdar://problem/24470533>
class Class {}
protocol HasClassAssoc { associatedtype Assoc : Class }
// CHECK-LABEL: sil hidden @_TF16generic_closures34captures_class_constrained_genericuRxS_13HasClassAssocrFTx1fFwx5AssocwxS1__T_
// CHECK: bb0(%0 : $*T, %1 : $@callee_owned (@owned T.Assoc) -> @owned T.Assoc):
// CHECK: [[GENERIC_FN:%.*]] = function_ref @_TFF16generic_closures34captures_class_constrained_genericuRxS_13HasClassAssocrFTx1fFwx5AssocwxS1__T_U_FT_FQQ_5AssocS2_
// CHECK: [[CONCRETE_FN:%.*]] = partial_apply [[GENERIC_FN]]<T, T.Assoc>(%1)
func captures_class_constrained_generic<T : HasClassAssoc>(_ x: T, f: T.Assoc -> T.Assoc) {
let _: () -> T.Assoc -> T.Assoc = { f }
}
| apache-2.0 | e7a5617b0440765b487241febd7986d9 | 36.919255 | 178 | 0.626208 | 3.133984 | false | false | false | false |
Hyfenglin/bluehouseapp | iOS/post/post/Constant.swift | 1 | 736 | //
// Constant.swift
// post
//
// Created by Derek Li on 14-10-8.
// Copyright (c) 2014年 Derek Li. All rights reserved.
//
import Foundation
//let HTTP_PATH:String = "http://192.168.1.101:8000/"
let HTTP_PATH:String = "http://127.0.0.1:8000/"
class Constant{
let URL_POST_LIST:String = "\(HTTP_PATH)post/"
let URL_POST_CREATE:String = "\(HTTP_PATH)post/"
let URL_POST_DETAIL:String = "\(HTTP_PATH)post/"
let URL_COMMENT_LIST:String = "\(HTTP_PATH)post/"
let URL_COMMENT_ADD:String = "\(HTTP_PATH)post/"
let URL_COMMENT_DETAIL:String = "\(HTTP_PATH)postcomment/"
let URL_USER_LOGIN:String = "\(HTTP_PATH)login/"
let URL_USER_REGIST:String = "\(HTTP_PATH)post/"
init(){
}
} | mit | c7803441c6f82a80da2990626afb9261 | 25.25 | 62 | 0.625341 | 3.020576 | false | false | false | false |
swiftingio/SwiftyStrings | SwiftyStrings/String+Localized.swift | 1 | 835 | //
// String+Localized.swift
// LocalizedStrings
//
// Created by Maciej Piotrowski on 12/11/16.
// Copyright © 2016 Maciej Piotrowski. All rights reserved.
//
import Foundation
func NSLocalizedString(_ key: String) -> String {
return NSLocalizedString(key, comment: "")
}
//MARK: Welcome Screen
extension String {
static let Hello = NSLocalizedString("Hello!")
static let ImpressMe = NSLocalizedString("Impress Me!")
static let ThisApplicationIsCreated = NSLocalizedString("This application is created by the swifting.io team")
static let OpsNoFeature = NSLocalizedString("Oops! It looks like this feature haven't been implemented yet :(!")
static let OK = NSLocalizedString("OK")
}
//MARK: Another Screen
extension String {
static let YetAnotherString = NSLocalizedString("Yet Another String")
}
| mit | f8e152d81bc463d770105e580c13cfa6 | 29.888889 | 116 | 0.735012 | 4.412698 | false | false | false | false |
hejunbinlan/Panoramic | Panoramic/Panoramic/AppDelegate.swift | 1 | 2401 | //
// AppDelegate.swift
// Panoramic
//
// Created by Sameh Mabrouk on 12/16/14.
// Copyright (c) 2014 SMApps. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
var panoramaVC : PanoramaViewController? = PanoramaViewController()
window = UIWindow(frame: UIScreen.mainScreen().bounds)
if let window = window {
window.backgroundColor = UIColor.orangeColor()
window.makeKeyAndVisible()
window.rootViewController = panoramaVC
}
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| mit | 9ec60f6a504de8c0cba88918271afb54 | 45.173077 | 285 | 0.740108 | 5.444444 | false | false | false | false |
BirdBrainTechnologies/Hummingbird-iOS-Support | BirdBlox/BirdBlox/PropertiesRequests.swift | 1 | 1453 | //
// PropertiesRequests.swift
// BirdBlox
//
// Created by Jeremy Huang on 2017-05-22.
// Copyright © 2017年 Birdbrain Technologies LLC. All rights reserved.
//
import Foundation
import UIKit
//import Swifter
class PropertiesManager {
var heightInPoints: CGFloat = 300.0
var widthInPoints: CGFloat = 300.0
func loadRequests(server: BBTBackendServer){
server["/properties/dims"] = self.getPhysicalDims
server["/properties/os"] = self.getVersion
}
func mmFromPoints(p:CGFloat) -> CGFloat {
let mmPerPoint = BBTThisIDevice.milimetersPerPointFor(deviceModel:
BBTThisIDevice.platformModelString())
return p * mmPerPoint
}
func getPhysicalDims(request: HttpRequest) -> HttpResponse {
DispatchQueue.main.sync {
let window = UIApplication.shared.delegate?.window
let heightInPoints = window??.bounds.height ?? UIScreen.main.bounds.height
let widthInPoints = window??.bounds.width ?? UIScreen.main.bounds.width
self.heightInPoints = heightInPoints
self.widthInPoints = widthInPoints
}
let height = mmFromPoints(p: self.heightInPoints)
let width = mmFromPoints(p: self.widthInPoints)
return .ok(.text("\(width),\(height)"))
}
func getVersion(request: HttpRequest) -> HttpResponse {
let os = "iOS"
let version = ProcessInfo().operatingSystemVersion
return .ok(.text("\(os) " +
"(\(version.majorVersion).\(version.minorVersion).\(version.patchVersion))"))
}
}
| mit | f21f8337ff6bdb6b433e2e44b7724045 | 25.851852 | 94 | 0.715862 | 3.717949 | false | false | false | false |
sarvex/SwiftRecepies | Cloud/Storing and Synchronizing Dictionaries in iCloud/Storing and Synchronizing Dictionaries in iCloud/AppDelegate.swift | 1 | 2040 | //
// AppDelegate.swift
// Storing and Synchronizing Dictionaries in iCloud
//
// Created by vandad on 207//14.
// Copyright (c) 2014 Pixolity Ltd. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
/* Checks if the user has logged into her iCloud account or not */
func isIcloudAvailable() -> Bool{
if let token = NSFileManager.defaultManager().ubiquityIdentityToken{
return true
} else {
return false
}
}
func application(application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [NSObject : AnyObject]?) -> Bool {
if isIcloudAvailable() == false{
println("iCloud is not available")
return true
}
let kvoStore = NSUbiquitousKeyValueStore.defaultStore()
var stringValue = "My String"
let stringValueKey = "MyStringKey"
var boolValue = true
let boolValueKey = "MyBoolKey"
var mustSynchronize = false
if kvoStore.stringForKey(stringValueKey) == nil{
println("Could not find the string value in iCloud. Setting...")
kvoStore.setString(stringValue, forKey: stringValueKey)
mustSynchronize = true
} else {
stringValue = kvoStore.stringForKey(stringValueKey)!
println("Found the string in iCloud = \(stringValue)")
}
if kvoStore.boolForKey(boolValueKey) == false{
println("Could not find the boolean value in iCloud. Setting...")
kvoStore.setBool(boolValue, forKey: boolValueKey)
mustSynchronize = true
} else {
println("Found the boolean in iCloud, getting...")
boolValue = kvoStore.boolForKey(boolValueKey)
}
if mustSynchronize{
if kvoStore.synchronize(){
println("Successfully synchronized with iCloud.")
} else {
println("Failed to synchronize with iCloud.")
}
}
return true
}
}
| isc | 3dabe0f4807a71dc9f21a423313381f9 | 26.945205 | 83 | 0.635294 | 5.049505 | false | false | false | false |
StratusHunter/JustEat-Test-Swift | Pods/RxCocoa/RxCocoa/Common/CocoaUnits/Driver/Driver+Subscription.swift | 10 | 4094 | //
// Driver+Subscription.swift
// Rx
//
// Created by Krunoslav Zaher on 9/19/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
#if !RX_NO_MODULE
import RxSwift
#endif
extension DriverConvertibleType {
/**
Creates new subscription and sends elements to observer.
In this form it's equivalent to `subscribe` method, but it communicates intent better.
- parameter observer: Observer that receives events.
- returns: Disposable object that can be used to unsubscribe the observer from the subject.
*/
@warn_unused_result(message="http://git.io/rxs.ud")
public func drive<O: ObserverType where O.E == E>(observer: O) -> Disposable {
MainScheduler.ensureExecutingOnScheduler()
return self.asObservable().subscribe(observer)
}
/**
Creates new subscription and sends elements to variable.
- parameter variable: Target variable for sequence elements.
- returns: Disposable object that can be used to unsubscribe the observer from the variable.
*/
@warn_unused_result(message="http://git.io/rxs.ud")
public func drive(variable: Variable<E>) -> Disposable {
return drive(onNext: { e in
variable.value = e
})
}
/**
Subscribes to observable sequence using custom binder function.
- parameter with: Function used to bind elements from `self`.
- returns: Object representing subscription.
*/
@warn_unused_result(message="http://git.io/rxs.ud")
public func drive<R>(transformation: Observable<E> -> R) -> R {
MainScheduler.ensureExecutingOnScheduler()
return transformation(self.asObservable())
}
/**
Subscribes to observable sequence using custom binder function and final parameter passed to binder function
after `self` is passed.
public func drive<R1, R2>(with: Self -> R1 -> R2, curriedArgument: R1) -> R2 {
return with(self)(curriedArgument)
}
- parameter with: Function used to bind elements from `self`.
- parameter curriedArgument: Final argument passed to `binder` to finish binding process.
- returns: Object representing subscription.
*/
@warn_unused_result(message="http://git.io/rxs.ud")
public func drive<R1, R2>(with: Observable<E> -> R1 -> R2, curriedArgument: R1) -> R2 {
MainScheduler.ensureExecutingOnScheduler()
return with(self.asObservable())(curriedArgument)
}
/**
Subscribes an element handler, a completion handler and disposed handler to an observable sequence.
Error callback is not exposed because `Driver` can't error out.
- parameter onNext: Action to invoke for each element in the observable sequence.
- parameter onCompleted: Action to invoke upon graceful termination of the observable sequence.
gracefully completed, errored, or if the generation is cancelled by disposing subscription)
- parameter onDisposed: Action to invoke upon any type of termination of sequence (if the sequence has
gracefully completed, errored, or if the generation is cancelled by disposing subscription)
- returns: Subscription object used to unsubscribe from the observable sequence.
*/
@warn_unused_result(message="http://git.io/rxs.ud")
public func drive(onNext onNext: ((E) -> Void)? = nil, onCompleted: (() -> Void)? = nil, onDisposed: (() -> Void)? = nil) -> Disposable {
MainScheduler.ensureExecutingOnScheduler()
return self.asObservable().subscribe(onNext: onNext, onCompleted: onCompleted, onDisposed: onDisposed)
}
/**
Subscribes an element handler to an observable sequence.
- parameter onNext: Action to invoke for each element in the observable sequence.
- returns: Subscription object used to unsubscribe from the observable sequence.
*/
@warn_unused_result(message="http://git.io/rxs.ud")
public func driveNext(onNext: E -> Void) -> Disposable {
MainScheduler.ensureExecutingOnScheduler()
return self.asObservable().subscribeNext(onNext)
}
}
| mit | 960ace9bc63ac616bac4cb27b139a48c | 38.737864 | 141 | 0.694601 | 4.704598 | false | false | false | false |
ortizraf/macsoftwarecenter | Mac Application Store/LabelCollectionViewItem.swift | 1 | 5118 | //
// LabelCollectionViewItem.swift
// Mac Software Center
//
// Created by Rafael Ortiz.
// Copyright © 2017 Nextneo. All rights reserved.
//
import Cocoa
class LabelCollectionViewItem: NSCollectionViewItem {
@IBOutlet weak var application_label_name: NSTextField!
@IBOutlet weak var application_imageview_image: NSImageView!
@IBOutlet weak var application_link: NSButton!
@IBOutlet weak var application_option: NSPopUpButton!
@IBOutlet weak var application_category: NSTextField!
var productItem: App?
var buildProduct: App? {
didSet{
application_label_name.stringValue = (buildProduct?.name)!
if((buildProduct?.url_image?.contains("http"))! && (buildProduct?.url_image?.contains("png"))!){
application_imageview_image.image = NSImage(named: "no-image")
if let checkedUrl = URL(string: (buildProduct?.url_image)!) {
downloadImage(url: checkedUrl)
}
} else {
let image = buildProduct?.url_image
application_imageview_image.image = NSImage(named: image!)
}
application_link.target = self
application_link.action = #selector(LabelCollectionViewItem.btnDownload)
application_option.isEnabled = true
application_option.target = self
application_option.action = #selector(LabelCollectionViewItem.selectOption)
application_category.stringValue = (buildProduct?.category?.name)!
}
}
func downloadImage(url: URL) {
print("Download Started", url)
getDataFromUrl(url: url) { (data, response, error) in
guard let data = data, error == nil else { return }
print(response?.suggestedFilename ?? url.lastPathComponent)
print("Download Finished", url)
DispatchQueue.main.async() { () -> Void in
self.application_imageview_image.image = NSImage(data: data)
}
}
}
func getDataFromUrl(url: URL, completion: @escaping (_ data: Data?, _ response: URLResponse?, _ error: Error?) -> Void) {
URLSession.shared.dataTask(with: url) {
(data, response, error) in
completion(data, response, error)
}.resume()
}
override func viewDidLoad() {
super.viewDidLoad()
// Do view setup here.
}
@IBAction func btnDownload(sender: NSButton){
print("Button pressed 👍 ")
getDownload(downloadLink: (self.buildProduct?.download_link)!, appName: (self.buildProduct?.name)!)
}
@IBAction func selectOption(sender: NSPopUpButton){
print("PopUp Button pressed 👍 ")
let selectedNumber = sender.indexOfSelectedItem
if(selectedNumber==0){
if let url = URL(string: (self.buildProduct?.download_link)!), NSWorkspace.shared.open(url) {
print("default browser was successfully opened")
}
} else if (selectedNumber==1) {
let pasteBoard = NSPasteboard.general
pasteBoard.clearContents()
pasteBoard.setString((self.buildProduct?.download_link)!, forType: .string)
}
}
func getDownload(downloadLink: String, appName: String){
self.application_link.isEnabled = false
self.application_link.title = "downloading..."
let downloadUrl = NSURL(string: downloadLink)
let downloadService = DownloadService(url: downloadUrl!)
print(downloadLink)
downloadService.downloadData(completion: { (data) in
let fileDirectory = FileManager.default.urls(for: .downloadsDirectory, in: .userDomainMask)[0]
let fileNameUrl = NSURL(fileURLWithPath: (downloadUrl?.absoluteString)!).lastPathComponent!
var fileName = fileNameUrl.removingPercentEncoding
if(self.buildProduct?.file_format?.contains("zip"))!{
print("zip")
fileName = appName+".zip"
} else if(self.buildProduct?.file_format?.contains("dmg"))!{
fileName = appName+".dmg"
} else if(!(fileName?.contains(".dmg"))! && !(fileName?.contains(".zip"))! && !(fileName?.contains(".app"))!){
print("dmg")
fileName = appName+".dmg"
}
let fileUrl = fileDirectory.appendingPathComponent(fileName!, isDirectory: false)
try? data.write(to: fileUrl)
let messageService = MessageService()
messageService.showNotification(title: appName, informativeText: "Download completed successfully")
self.application_link.title = "download"
self.application_link.isEnabled = true
})
}
}
| gpl-3.0 | 28a775337aa5ab88109a1805086f8521 | 34.248276 | 126 | 0.574447 | 5.147029 | false | false | false | false |
TheHolyGrail/Historian | ELCache/ELCache+UIImageView.swift | 2 | 2131 | //
// ELCache+UIImageView.swift
// ELCache
//
// Created by Sam Grover on 12/27/15.
// Copyright © 2015 WalmartLabs. All rights reserved.
//
import UIKit
import ELFoundation
public extension UIImageView {
internal var urlAssociationKey: String {
return "com.walmartlabs.ELCache.UIImageView.NSURL"
}
convenience init(URL: NSURL, completion: FetchImageURLCompletionClosure) {
self.init()
self.setImageAt(URL, placeholder: nil, completion: completion)
}
func setImageAt(URL: NSURL) {
setImageAt(URL, placeholder: nil, completion: {_,_ in })
}
func setImageAt(URL: NSURL, placeholder: UIImage?) {
setImageAt(URL, placeholder: placeholder, completion: {_,_ in })
}
func setImageAt(URL: NSURL, completion: FetchImageURLCompletionClosure) {
setImageAt(URL, placeholder: nil, completion: completion)
}
func setImageAt(URL: NSURL, placeholder: UIImage?, completion: FetchImageURLCompletionClosure) {
// Use the placeholder only if the image is not valid in cache to avoid setting actual image momentarily after setting placeholder.
if URLCache.sharedURLCache.validInCache(URL) != true {
self.image = placeholder
}
URLCache.sharedURLCache.fetchImage(URL) { (image, error) -> Void in
self.processURLFetch(image, error: error, completion: completion)
}
setAssociatedObject(self, value: URL, associativeKey: urlAssociationKey, policy: objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN)
}
func cancelURL(url: NSURL) {
if let URL: NSURL = getAssociatedObject(self, associativeKey: urlAssociationKey) {
URLCache.sharedURLCache.cancelFetch(URL)
}
}
internal func processURLFetch(image: UIImage?, error: NSError?, completion: FetchImageURLCompletionClosure) {
dispatch_async(dispatch_get_main_queue(), { () -> Void in
if let image = image {
self.image = image
}
completion(image, error)
})
}
}
| mit | d2941ce22cdffc4218b17c6858ca1a75 | 32.809524 | 139 | 0.646009 | 4.671053 | false | false | false | false |
Houzz/PuzzleLayout | PuzzleLayout/PuzzleLayout/Layout/Utils/PuzzleCollectionViewLayout+Constants.swift | 1 | 1571 | //
// PuzzleCollectionViewLayout+Constants.swift
// PuzzleLayout
//
// Created by Yossi Avramov on 05/10/2016.
// Copyright © 2016 Houzz. All rights reserved.
//
import UIKit
/// An element kind for separator line. Shouldn't be used by 'PuzzlePieceSectionLayout' since separator lines generated by 'PuzzleCollectionViewLayout'
public let PuzzleCollectionElementKindSeparatorLine = "!_SeparatorLine_!"
/// An element kind for top gutter
public let PuzzleCollectionElementKindSectionTopGutter = "!_SectionTopGutter_!"
/// An element kind for bottom gutter
public let PuzzleCollectionElementKindSectionBottomGutter = "!_SectionBottomGutter_!"
/// A key used to set the view background color for separator lines & gutters.
public let PuzzleCollectionColoredViewColorKey = "!_BackgroundColor_!"
/// An element kind for 'PuzzleCollectionViewLayout' headers. This string is equal to the flow layout element kind for headers, which makes it easy to create header in storyboard.
public let PuzzleCollectionElementKindSectionHeader: String = UICollectionView.elementKindSectionHeader
/// An element kind for 'PuzzleCollectionViewLayout' footers. This string is equal to the flow layout element kind for footers, which makes it easy to create footer in storyboard.
public let PuzzleCollectionElementKindSectionFooter: String = UICollectionView.elementKindSectionFooter
/// A Z index of separator lines, top & bottom gutters
public let PuzzleCollectionSeparatorsViewZIndex = 2
/// A Z index of pinned headers & footers
public let PuzzleCollectionHeaderFooterZIndex = 4
| mit | 51da9b4c1521f5fcd0b01392974ec63f | 46.575758 | 179 | 0.805732 | 4.686567 | false | false | false | false |
valentin7/pineapple-ios | Pineapple/DetailViewController.swift | 1 | 5358 | //
// DetailViewController.swift
// Pineapple
//
// Created by Valentin Perez on 5/23/15.
// Copyright (c) 2015 Valpe Technologies. All rights reserved.
//
import UIKit
//import MapboxGL
import MapKit
import AddressBook
import Parse
class DetailViewController: UIViewController {
@IBOutlet weak var placeNameLabel: UILabel!
@IBOutlet var mapView: MKMapView!
@IBOutlet weak var placeImageView: UIImageView!
@IBOutlet weak var descriptionLabel: UILabel!
var locationManager = CLLocationManager()
let regionRadius: CLLocationDistance = 200
var placeName : String = ""
var placeObject : PFObject!
override func viewDidLoad() {
super.viewDidLoad()
self.navigationController?.hidesBarsOnSwipe = false
self.navigationController?.setNavigationBarHidden(false, animated: true)
if (placeObject != nil) {
print("PLACE IS NOT NIL YOO")
descriptionLabel.text = placeObject["description"] as? String
let placeName = placeObject["name"] as! String
placeNameLabel?.text = placeName
let imageFile = placeObject["image"] as? PFFile
let url = imageFile!.url
placeImageView!.setImageWithURL(NSURL(string: url!)!)
let placeLocation : PFGeoPoint = placeObject["location"] as! PFGeoPoint
//let placeName = placeObject["name"] as! String
let placeDescription = "Get directions"//placeObject["description"] as! String
let placePin = PlaceAnnotation(title: placeName,
description: placeDescription,
coordinate: CLLocationCoordinate2D(latitude: placeLocation.latitude, longitude: placeLocation.longitude))
mapView.addAnnotation(placePin)
mapView.delegate = self
}
// Do any additional setup after loading the view.
}
func getLocation() {
if (placeObject != nil) {
let geoPoint = placeObject["location"] as? PFGeoPoint
let userLoc = CLLocation(latitude: geoPoint!.latitude, longitude: geoPoint!.longitude)
self.centerMapOnLocation(userLoc)
} else {
PFGeoPoint.geoPointForCurrentLocationInBackground {
(geoPoint: PFGeoPoint?, error: NSError?) -> Void in
if error == nil {
let userLoc = CLLocation(latitude: geoPoint!.latitude, longitude: geoPoint!.longitude)
print(" user location: \n", userLoc)
self.centerMapOnLocation(userLoc)
// do something with the new geoPoint
}
}
}
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
checkLocationAuthorizationStatus()
}
func checkLocationAuthorizationStatus() {
if CLLocationManager.authorizationStatus() == .AuthorizedWhenInUse {
mapView.showsUserLocation = true
} else {
locationManager.requestWhenInUseAuthorization()
}
}
func centerMapOnLocation(location: CLLocation) {
let coordinateRegion = MKCoordinateRegionMakeWithDistance(location.coordinate,
regionRadius * 2.0, regionRadius * 2.0)
var placePin = MKMapPoint(x: 70, y: 90)
mapView.setRegion(coordinateRegion, animated: true)
}
@IBAction func unwindToMainViewController (sender: UIStoryboardSegue){
// bug? exit segue doesn't dismiss so we do it manually...
self.dismissViewControllerAnimated(true, completion: nil)
}
@IBAction func tappedDetails(sender: AnyObject) {
var vc : TweakViewController = self.storyboard?.instantiateViewControllerWithIdentifier("tweakController") as! TweakViewController
vc.place = self.placeObject
vc.placeName = self.placeName
self.presentViewController(vc, animated: true, completion: nil)
}
// func mapItem() -> MKMapItem {
// let addressDictionary = [String(kABPersonAddressStreetKey): subtitle]
// let placemark = MKPlacemark(coordinate: coordinate, addressDictionary: addressDictionary)
//
// let mapItem = MKMapItem(placemark: placemark)
// mapItem.name = title
//
// return mapItem
// }
//
// func mapView(mapView: MKMapView!, annotationView view: MKAnnotationView!,
// calloutAccessoryControlTapped control: UIControl!) {
// let location = view.annotation as Artwork
// let launchOptions = [MKLaunchOptionsDirectionsModeKey: MKLaunchOptionsDirectionsModeDriving]
// location.mapItem().openInMapsWithLaunchOptions(launchOptions)
// }
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| mit | 7c9b6697685706d780d897a8af02ac97 | 32.074074 | 136 | 0.639978 | 5.379518 | false | false | false | false |
nguyenantinhbk77/practice-swift | Views/NavigationController/Fonts/Fonts/FontListViewController.swift | 2 | 4136 | //
// FontListViewController.swift
// Fonts
//
// Created by Domenico on 23.04.15.
// Copyright (c) 2015 Domenico Solazzo. All rights reserved.
//
import UIKit
class FontListViewController: UITableViewController {
var fontNames: [String] = []
var showsFavorites:Bool = false
private var cellPointSize: CGFloat!
private let cellIdentifier = "FontName"
override func viewDidLoad() {
super.viewDidLoad()
if showsFavorites {
navigationItem.rightBarButtonItem = editButtonItem()
}
let preferredTableViewFont = UIFont.preferredFontForTextStyle(UIFontTextStyleHeadline)
cellPointSize = preferredTableViewFont.pointSize
}
// Fetch the font names
func fontForDisplay(atIndexPath indexPath: NSIndexPath) -> UIFont {
let fontName = fontNames[indexPath.row]
return UIFont(name: fontName, size: cellPointSize)!
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
if showsFavorites {
fontNames = FavoritesList.sharedFavoriteList.favorites
tableView.reloadData()
}
}
override func tableView(tableView: UITableView,
numberOfRowsInSection section: Int) -> Int {
return fontNames.count
}
override func tableView(tableView: UITableView,
cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier,
forIndexPath: indexPath) as! UITableViewCell
cell.textLabel!.font = fontForDisplay(atIndexPath: indexPath)
cell.textLabel!.text = fontNames[indexPath.row]
cell.detailTextLabel?.text = fontNames[indexPath.row]
return cell
}
// Accepted editing
override func tableView(tableView: UITableView,
canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
return showsFavorites
}
// Deleting a row
override func tableView(tableView: UITableView,
commitEditingStyle editingStyle: UITableViewCellEditingStyle,
forRowAtIndexPath indexPath: NSIndexPath) {
if !showsFavorites {
return
}
if editingStyle == UITableViewCellEditingStyle.Delete {
// Delete the row from the data source
let favorite = fontNames[indexPath.row]
FavoritesList.sharedFavoriteList.removeFavorite(favorite)
fontNames = FavoritesList.sharedFavoriteList.favorites
tableView.deleteRowsAtIndexPaths([indexPath],
withRowAnimation: UITableViewRowAnimation.Fade)
}
}
// Reordering function
override func tableView(tableView: UITableView,
moveRowAtIndexPath sourceIndexPath: NSIndexPath,
toIndexPath destinationIndexPath: NSIndexPath) {
FavoritesList.sharedFavoriteList.moveItem(fromIndex: sourceIndexPath.row,
toIndex: destinationIndexPath.row)
fontNames = FavoritesList.sharedFavoriteList.favorites
}
// MARK: 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.
let tableViewCell = sender as! UITableViewCell
let indexPath = tableView.indexPathForCell(tableViewCell)!
let font = fontForDisplay(atIndexPath: indexPath)
if segue.identifier == "ShowFontSizes" {
let sizesVC = segue.destinationViewController as! FontSizesViewController
sizesVC.title = font.fontName
sizesVC.font = font
} else {
let infoVC = segue.destinationViewController as! FontInfoViewController
infoVC.font = font
infoVC.favorite = contains(FavoritesList.sharedFavoriteList.favorites,
font.fontName)
}
}
}
| mit | b40320bba4514f02cd36ee3965f144da | 36.261261 | 94 | 0.651112 | 5.985528 | false | false | false | false |
jdbateman/VirtualTourist | VirtualTourist/VTError.swift | 1 | 966 | //
// VTError.swift
// VirtualTourist
//
// Created by john bateman on 10/6/15.
// Copyright (c) 2015 John Bateman. All rights reserved.
//
import Foundation
class VTError {
var error: NSError?
struct Constants {
static let ERROR_DOMAIN: String = "self.VirtualTourist.Error"
}
enum ErrorCodes: Int {
case CORE_DATA_INIT_ERROR = 9000
case JSON_PARSE_ERROR = 9001
case FLICKR_REQUEST_ERROR = 9002
case FLICKR_FILE_DOWNLOAD_ERROR = 9003
case IMAGE_CONVERSION_ERROR = 9004
case FILE_NOT_FOUND_ERROR = 9005
}
init(errorString: String, errorCode: ErrorCodes) {
// output to console
println(errorString)
// construct NSError
var dict = [String: AnyObject]()
dict[NSLocalizedDescriptionKey] = errorString
error = NSError(domain: VTError.Constants.ERROR_DOMAIN, code: errorCode.rawValue, userInfo: dict)
}
} | mit | 43eedde3651d16b842633a07ace6e1fa | 24.447368 | 105 | 0.626294 | 4.041841 | false | false | false | false |
mirchow/HungerFreeCity | ios/Hunger Free City/Models/GooglePlace.swift | 1 | 1435 | //
// GooglePlace.swift
// Hunger Free City
//
// Created by Mirek Chowaniok on 6/26/15.
// Copyright (c) 2015 Jacksonville Community. All rights reserved.
//
import UIKit
import Foundation
import CoreLocation
class GooglePlace {
let name: String
let address: String
let coordinate: CLLocationCoordinate2D
let placeType: String
var photoReference: String?
var photo: UIImage?
init(dictionary:NSDictionary, acceptedTypes: [String])
{
name = dictionary["name"] as! String
address = dictionary["vicinity"] as! String
let location = dictionary["geometry"]?["location"] as! NSDictionary
let lat = location["lat"] as! CLLocationDegrees
let lng = location["lng"]as! CLLocationDegrees
coordinate = CLLocationCoordinate2DMake(lat, lng)
if let photos = dictionary["photos"] as? NSArray {
let photo = photos.firstObject as! NSDictionary
photoReference = photo["photo_reference"] as? String
}
var foundType = "restaurant"
let possibleTypes = acceptedTypes.count > 0 ? acceptedTypes : ["bakery", "bar", "cafe", "grocery_or_supermarket", "restaurant"]
for type in dictionary["types"] as! [String] {
if possibleTypes.contains(type) {
foundType = type
break
}
}
placeType = foundType
}
}
| mit | 8e77f489a34cb92d4871d0bf2616c8d1 | 29.531915 | 135 | 0.617422 | 4.555556 | false | false | false | false |
18775134221/SwiftBase | SwiftTest/SwiftTest/Classes/tools/JQPhoneManagerVC.swift | 2 | 1981 | //
// JQPhoneManagerVC.swift
// SwiftTest
//
// Created by MAC on 2016/12/14.
// Copyright © 2016年 MAC. All rights reserved.
//
import UIKit
// MARK: - 拨打电话
class JQPhoneManagerVC: UIViewController {
var webView: UIWebView?
init () {
webView = UIWebView()
super.init(nibName: nil, bundle: nil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
self.removeFromParentViewController()
}
override func viewDidLoad() {
super.viewDidLoad()
}
/**
* 打电话
*
* @param no 电话号码
* @param inViewController 需要打电话的控制器
*/
class func call(_ no: String?, _ inViewController: UIViewController?,failBlock: ()->()) {
guard let _ = no else {
failBlock()
return
}
// 拨打电话
let noString: String = "tel://" + no!
let url: NSURL = NSURL(string: noString)!;
let canOpen: Bool? = UIApplication.shared.openURL(url as URL)
guard canOpen! else { // 可选类型才可以使用可选绑定 对象才可以置空
failBlock()
return
}
let pMVC: JQPhoneManagerVC = JQPhoneManagerVC()
pMVC.view.alpha = 0
pMVC.view.frame = CGRect.zero
inViewController?.addChildViewController(pMVC)
inViewController?.view.addSubview(pMVC.view)
let request: NSURLRequest = NSURLRequest(url: url as URL)
pMVC.webView?.loadRequest(request as URLRequest)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
deinit {
webView = nil
print("PhoneManager已经被释放")
}
}
| apache-2.0 | 675184b7605cf1a574105216b5b6a156 | 23.736842 | 93 | 0.582447 | 4.40281 | false | false | false | false |
inacioferrarini/York | Classes/DataSyncRules/Entities/EntityDailySyncRule.swift | 1 | 3333 | // The MIT License (MIT)
//
// Copyright (c) 2016 Inácio Ferrarini
//
// 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 CoreData
open class EntityDailySyncRule: EntityBaseSyncRules {
open class func fetchEntityDailySyncRuleByName(_ name: String, inManagedObjectContext context: NSManagedObjectContext) -> EntityDailySyncRule? {
guard name.characters.count > 0 else {
return nil
}
let request: NSFetchRequest = NSFetchRequest<EntityDailySyncRule>(entityName: self.simpleClassName())
request.predicate = NSPredicate(format: "name = %@", name)
return self.lastObjectFromRequest(request, inManagedObjectContext: context)
}
open class func entityDailySyncRuleByName(_ name: String, days: NSNumber?, inManagedObjectContext context: NSManagedObjectContext) -> EntityDailySyncRule? {
guard name.characters.count > 0 else {
return nil
}
var entityDailySyncRule: EntityDailySyncRule? = fetchEntityDailySyncRuleByName(name, inManagedObjectContext: context)
if entityDailySyncRule == nil {
let newEntityDailySyncRule = NSEntityDescription.insertNewObject(forEntityName: self.simpleClassName(), into: context) as? EntityDailySyncRule
if let entity = newEntityDailySyncRule {
entity.name = name
}
entityDailySyncRule = newEntityDailySyncRule
}
if let entityDailySyncRule = entityDailySyncRule {
entityDailySyncRule.days = days
}
return entityDailySyncRule
}
override open func shouldRunSyncRuleWithName(_ name: String, date: Date, inManagedObjectContext context: NSManagedObjectContext) -> Bool {
let lastExecution = EntitySyncHistory.fetchEntityAutoSyncHistoryByName(name, inManagedObjectContext: context)
if let lastExecution = lastExecution,
let lastExecutionDate = lastExecution.lastExecutionDate,
let days = self.days {
let elapsedTime = Date().timeIntervalSince(lastExecutionDate)
let targetTime = TimeInterval(days.int32Value * 24 * 60 * 60)
return elapsedTime >= targetTime
}
return true
}
}
| mit | 39a393f553d9a96b25ee32f2d73e7397 | 43.426667 | 160 | 0.704382 | 4.936296 | false | false | false | false |
WeHUD/app | weHub-ios/Gzone_App/Pods/XLPagerTabStrip/Sources/TwitterPagerTabStripViewController.swift | 6 | 10296 | // TwitterPagerTabStripViewController.swift
// XLPagerTabStrip ( https://github.com/xmartlabs/XLPagerTabStrip )
//
// Copyright (c) 2017 Xmartlabs ( http://xmartlabs.com )
//
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
public struct TwitterPagerTabStripSettings {
public struct Style {
public var dotColor = UIColor(white: 1, alpha: 0.4)
public var selectedDotColor = UIColor.white
public var portraitTitleFont = UIFont.systemFont(ofSize: 18)
public var landscapeTitleFont = UIFont.systemFont(ofSize: 15)
public var titleColor = UIColor.white
}
public var style = Style()
}
open class TwitterPagerTabStripViewController: PagerTabStripViewController, PagerTabStripDataSource, PagerTabStripIsProgressiveDelegate {
open var settings = TwitterPagerTabStripSettings()
public override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
pagerBehaviour = .progressive(skipIntermediateViewControllers: true, elasticIndicatorLimit: true)
delegate = self
datasource = self
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
pagerBehaviour = .progressive(skipIntermediateViewControllers: true, elasticIndicatorLimit: true)
delegate = self
datasource = self
}
open override func viewDidLoad() {
super.viewDidLoad()
if titleView.superview == nil {
navigationItem.titleView = titleView
}
// keep watching the frame of titleView
titleView.addObserver(self, forKeyPath: "frame", options: [.new, .old], context: nil)
guard let navigationController = navigationController else {
fatalError("TwitterPagerTabStripViewController should be embedded in a UINavigationController")
}
titleView.frame = CGRect(x: 0, y: 0, width: navigationController.navigationBar.frame.width, height: navigationController.navigationBar.frame.height)
titleView.addSubview(titleScrollView)
titleView.addSubview(pageControl)
reloadNavigationViewItems()
}
open override func reloadPagerTabStripView() {
super.reloadPagerTabStripView()
guard isViewLoaded else { return }
reloadNavigationViewItems()
setNavigationViewItemsPosition(updateAlpha: true)
}
// MARK: - PagerTabStripDelegate
open func updateIndicator(for viewController: PagerTabStripViewController, fromIndex: Int, toIndex: Int, withProgressPercentage progressPercentage: CGFloat, indexWasChanged: Bool) {
// move indicator scroll view
guard let distance = distanceValue else { return }
var xOffset: CGFloat = 0
if fromIndex < toIndex {
xOffset = distance * CGFloat(fromIndex) + distance * progressPercentage
}
else if fromIndex > toIndex {
xOffset = distance * CGFloat(fromIndex) - distance * progressPercentage
}
else {
xOffset = distance * CGFloat(fromIndex)
}
titleScrollView.contentOffset = CGPoint(x: xOffset, y: 0)
// update alpha of titles
setAlphaWith(offset: xOffset, andDistance: distance)
// update page control page
pageControl.currentPage = currentIndex
}
open func updateIndicator(for viewController: PagerTabStripViewController, fromIndex: Int, toIndex: Int) {
fatalError()
}
open override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
guard object as AnyObject === titleView && keyPath == "frame" && change?[NSKeyValueChangeKey.kindKey] as? UInt == NSKeyValueChange.setting.rawValue else { return }
let oldRect = (change![NSKeyValueChangeKey.oldKey]! as AnyObject).cgRectValue
let newRect = (change![NSKeyValueChangeKey.oldKey]! as AnyObject).cgRectValue
if (oldRect?.equalTo(newRect!))! {
titleScrollView.frame = CGRect(x: 0, y: 0, width: titleView.frame.width, height: titleScrollView.frame.height)
setNavigationViewItemsPosition(updateAlpha: true)
}
}
deinit {
if isViewLoaded {
titleView.removeObserver(self, forKeyPath: "frame")
}
}
open override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
setNavigationViewItemsPosition(updateAlpha: false)
}
// MARK: - Helpers
private lazy var titleView: UIView = {
let navigationView = UIView()
navigationView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
return navigationView
}()
private lazy var titleScrollView: UIScrollView = { [unowned self] in
let titleScrollView = UIScrollView(frame: CGRect(x: 0, y: 0, width: self.view.bounds.width, height: 44))
titleScrollView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
titleScrollView.bounces = true
titleScrollView.scrollsToTop = false
titleScrollView.delegate = self
titleScrollView.showsVerticalScrollIndicator = false
titleScrollView.showsHorizontalScrollIndicator = false
titleScrollView.isPagingEnabled = true
titleScrollView.isUserInteractionEnabled = false
titleScrollView.alwaysBounceHorizontal = true
titleScrollView.alwaysBounceVertical = false
return titleScrollView
}()
private lazy var pageControl: FXPageControl = { [unowned self] in
let pageControl = FXPageControl()
pageControl.backgroundColor = .clear
pageControl.dotSize = 3.8
pageControl.dotSpacing = 4.0
pageControl.dotColor = self.settings.style.dotColor
pageControl.selectedDotColor = self.settings.style.selectedDotColor
pageControl.isUserInteractionEnabled = false
return pageControl
}()
private var childTitleLabels = [UILabel]()
private func reloadNavigationViewItems() {
// remove all child view controller header labels
childTitleLabels.forEach { $0.removeFromSuperview() }
childTitleLabels.removeAll()
for (index, item) in viewControllers.enumerated() {
let child = item as! IndicatorInfoProvider
let indicatorInfo = child.indicatorInfo(for: self)
let navTitleLabel : UILabel = {
let label = UILabel()
label.text = indicatorInfo.title
label.font = UIApplication.shared.statusBarOrientation.isPortrait ? settings.style.portraitTitleFont : settings.style.landscapeTitleFont
label.textColor = settings.style.titleColor
label.alpha = 0
return label
}()
navTitleLabel.alpha = currentIndex == index ? 1 : 0
navTitleLabel.textColor = settings.style.titleColor
titleScrollView.addSubview(navTitleLabel)
childTitleLabels.append(navTitleLabel)
}
}
private func setNavigationViewItemsPosition(updateAlpha: Bool) {
guard let distance = distanceValue else { return }
let isPortrait = UIApplication.shared.statusBarOrientation.isPortrait
let navBarHeight: CGFloat = navigationController!.navigationBar.frame.size.height
for (index, label) in childTitleLabels.enumerated() {
if updateAlpha {
label.alpha = currentIndex == index ? 1 : 0
}
label.font = isPortrait ? settings.style.portraitTitleFont : settings.style.landscapeTitleFont
let viewSize = label.intrinsicContentSize
let originX = distance - viewSize.width/2 + CGFloat(index) * distance
let originY = (CGFloat(navBarHeight) - viewSize.height) / 2
label.frame = CGRect(x: originX, y: originY - 2, width: viewSize.width, height: viewSize.height)
label.tag = index
}
let xOffset = distance * CGFloat(currentIndex)
titleScrollView.contentOffset = CGPoint(x: xOffset, y: 0)
pageControl.numberOfPages = childTitleLabels.count
pageControl.currentPage = currentIndex
let viewSize = pageControl.sizeForNumber(ofPages: childTitleLabels.count)
let originX = distance - viewSize.width / 2
pageControl.frame = CGRect(x: originX, y: navBarHeight - 10, width: viewSize.width, height: viewSize.height)
}
private func setAlphaWith(offset: CGFloat, andDistance distance: CGFloat) {
for (index, label) in childTitleLabels.enumerated() {
label.alpha = {
if offset < distance * CGFloat(index) {
return (offset - distance * CGFloat(index - 1)) / distance
}
else {
return 1 - ((offset - distance * CGFloat(index)) / distance)
}
}()
}
}
private var distanceValue: CGFloat? {
return navigationController.map { $0.navigationBar.convert($0.navigationBar.center, to: titleView) }?.x
}
}
| bsd-3-clause | e30a2d2b9fe1b527b2cd35ffe0fe86bb | 42.443038 | 185 | 0.671134 | 5.410405 | false | false | false | false |
fanyu/EDCCharla | EDCChat/EDCChat/EDCChatMessageCell.swift | 1 | 4287 | //
// EDCChatTableViewCell.swift
// EDCChat
//
// Created by FanYu on 10/12/2015.
// Copyright © 2015 FanYu. All rights reserved.
//
import UIKit
// MARK: - Cell Style}
enum EDCChatMessageCellStyle: Int {
case Unknow
case Left
case Right
}
// MARK: - Event Type
enum EDCChatMessageCellEventType: Int {
case Bubble
case Card
case Portrait
}
protocol EDCChatMessageCellProtocol {
var style: EDCChatMessageCellStyle { set get }
var enabled: Bool { set get }
var message: EDCChatMessageProtocol? { set get }
func systemLayoutSizeFittingSize(targetSize: CGSize) ->CGSize
}
@objc protocol EDCChatMessageCellDelegate: NSObjectProtocol {
optional func chatCellDidCpoy(chatCell: EDCChatMessageCell)
optional func chatCellDidDelete(chatCell: EDCChatMessageCell)
optional func chatCellDidResend(chatCell: EDCChatMessageCell)
optional func chatCellDidTap(chatCell: EDCChatMessageCell, withEvent event: EDCChatMessageCellEvent)
optional func chatCellDidLongPress(chatCell: EDCChatMessageCell, withEvent event: EDCChatMessageCellEvent)
}
class EDCChatMessageCell: UITableViewCell, EDCChatMessageCellProtocol {
private(set) static var createdCount = 0
var style: EDCChatMessageCellStyle = .Unknow
var message: EDCChatMessageProtocol? {
willSet {
// belong to self , then right
if newValue?.ownership ?? false {
style = .Right
} else {
style = .Left
}
}
}
// use actions
var enabled: Bool = false {
didSet {
guard oldValue != enabled else {
return
}
if enabled {
addActions()
} else {
removeActions()
}
}
}
// delegate
weak var delegate: EDCChatMessageCellDelegate?
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
setup()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup()
}
func setup() {
self.clipsToBounds = true
self.backgroundColor = UIColor.clearColor()
self.selectionStyle = UITableViewCellSelectionStyle.None
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
}
deinit {
EDCLog.trace("created count \(--self.dynamicType.createdCount)")
}
override func canBecomeFirstResponder() -> Bool {
return true
}
override func canPerformAction(action: Selector, withSender sender: AnyObject?) -> Bool {
if action == "chatCellDelete:" {
return true
}
return false
}
// Calculate size
override func systemLayoutSizeFittingSize(targetSize: CGSize) -> CGSize {
// refresh
self.layoutIfNeeded()
// get content view size
let size = contentView.systemLayoutSizeFittingSize(targetSize)
// refine
return CGSizeMake(size.width, size.height + 1)
}
func addActions() {
}
func removeActions() {
}
}
// MARK: - Event
class EDCChatMessageCellEvent: NSObject {
var type: EDCChatMessageCellEventType
var event: UIEvent?
var sender: AnyObject?
var extra: AnyObject?
init(type: EDCChatMessageCellEventType, sender: AnyObject? = nil, event: UIEvent? = nil, extra: AnyObject? = nil) {
self.type = type
self.event = event
self.sender = sender
self.extra = extra
super.init()
}
}
//// MARK: - Event Action
//extension EDCChatMessageCell {
// // delete
// func chatCellDelete(sender: AnyObject) {
// self.delegate?.chatCellDidDelete?(self)
// }
// // tap
// func chatCellTap(sender: EDCChatMessageCellEvent) {
// self.delegate?.chatCellDidTap?(self, withEvent: sender)
// }
// // long press
// func chatCellLongPress(sender: EDCChatMessageCellEvent) {
// self.delegate?.chatCellDidLongPress?(self, withEvent: sender)
// }
//}
| mit | c4e97764aed3e93f8816255101696cf9 | 23.352273 | 119 | 0.619692 | 4.618534 | false | false | false | false |
Drusy/auvergne-webcams-ios | Carthage/Checkouts/realm-cocoa/RealmSwift/Tests/SwiftTestObjects.swift | 2 | 19399 | ////////////////////////////////////////////////////////////////////////////
//
// Copyright 2014 Realm Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////
import Foundation
import RealmSwift
import Realm
class SwiftStringObject: Object {
@objc dynamic var stringCol = ""
}
class SwiftBoolObject: Object {
@objc dynamic var boolCol = false
}
class SwiftIntObject: Object {
@objc dynamic var intCol = 0
}
class SwiftLongObject: Object {
@objc dynamic var longCol: Int64 = 0
}
class SwiftObject: Object {
@objc dynamic var boolCol = false
@objc dynamic var intCol = 123
@objc dynamic var floatCol = 1.23 as Float
@objc dynamic var doubleCol = 12.3
@objc dynamic var stringCol = "a"
@objc dynamic var binaryCol = "a".data(using: String.Encoding.utf8)!
@objc dynamic var dateCol = Date(timeIntervalSince1970: 1)
@objc dynamic var objectCol: SwiftBoolObject? = SwiftBoolObject()
let arrayCol = List<SwiftBoolObject>()
class func defaultValues() -> [String: Any] {
return [
"boolCol": false,
"intCol": 123,
"floatCol": 1.23 as Float,
"doubleCol": 12.3,
"stringCol": "a",
"binaryCol": "a".data(using: String.Encoding.utf8)!,
"dateCol": Date(timeIntervalSince1970: 1),
"objectCol": [false],
"arrayCol": []
]
}
}
class SwiftOptionalObject: Object {
@objc dynamic var optNSStringCol: NSString?
@objc dynamic var optStringCol: String?
@objc dynamic var optBinaryCol: Data?
@objc dynamic var optDateCol: Date?
let optIntCol = RealmOptional<Int>()
let optInt8Col = RealmOptional<Int8>()
let optInt16Col = RealmOptional<Int16>()
let optInt32Col = RealmOptional<Int32>()
let optInt64Col = RealmOptional<Int64>()
let optFloatCol = RealmOptional<Float>()
let optDoubleCol = RealmOptional<Double>()
let optBoolCol = RealmOptional<Bool>()
@objc dynamic var optObjectCol: SwiftBoolObject?
}
class SwiftOptionalPrimaryObject: SwiftOptionalObject {
let id = RealmOptional<Int>()
override class func primaryKey() -> String? { return "id" }
}
class SwiftListObject: Object {
let int = List<Int>()
let int8 = List<Int8>()
let int16 = List<Int16>()
let int32 = List<Int32>()
let int64 = List<Int64>()
let float = List<Float>()
let double = List<Double>()
let string = List<String>()
let data = List<Data>()
let date = List<Date>()
let intOpt = List<Int?>()
let int8Opt = List<Int8?>()
let int16Opt = List<Int16?>()
let int32Opt = List<Int32?>()
let int64Opt = List<Int64?>()
let floatOpt = List<Float?>()
let doubleOpt = List<Double?>()
let stringOpt = List<String?>()
let dataOpt = List<Data?>()
let dateOpt = List<Date?>()
}
class SwiftImplicitlyUnwrappedOptionalObject: Object {
@objc dynamic var optNSStringCol: NSString!
@objc dynamic var optStringCol: String!
@objc dynamic var optBinaryCol: Data!
@objc dynamic var optDateCol: Date!
@objc dynamic var optObjectCol: SwiftBoolObject!
}
class SwiftOptionalDefaultValuesObject: Object {
@objc dynamic var optNSStringCol: NSString? = "A"
@objc dynamic var optStringCol: String? = "B"
@objc dynamic var optBinaryCol: Data? = "C".data(using: String.Encoding.utf8)! as Data
@objc dynamic var optDateCol: Date? = Date(timeIntervalSince1970: 10)
let optIntCol = RealmOptional<Int>(1)
let optInt8Col = RealmOptional<Int8>(1)
let optInt16Col = RealmOptional<Int16>(1)
let optInt32Col = RealmOptional<Int32>(1)
let optInt64Col = RealmOptional<Int64>(1)
let optFloatCol = RealmOptional<Float>(2.2)
let optDoubleCol = RealmOptional<Double>(3.3)
let optBoolCol = RealmOptional<Bool>(true)
@objc dynamic var optObjectCol: SwiftBoolObject? = SwiftBoolObject(value: [true])
// let arrayCol = List<SwiftBoolObject?>()
class func defaultValues() -> [String: Any] {
return [
"optNSStringCol": "A",
"optStringCol": "B",
"optBinaryCol": "C".data(using: String.Encoding.utf8)!,
"optDateCol": Date(timeIntervalSince1970: 10),
"optIntCol": 1,
"optInt8Col": 1,
"optInt16Col": 1,
"optInt32Col": 1,
"optInt64Col": 1,
"optFloatCol": 2.2 as Float,
"optDoubleCol": 3.3,
"optBoolCol": true
]
}
}
class SwiftOptionalIgnoredPropertiesObject: Object {
@objc dynamic var id = 0
@objc dynamic var optNSStringCol: NSString? = "A"
@objc dynamic var optStringCol: String? = "B"
@objc dynamic var optBinaryCol: Data? = "C".data(using: String.Encoding.utf8)! as Data
@objc dynamic var optDateCol: Date? = Date(timeIntervalSince1970: 10)
@objc dynamic var optObjectCol: SwiftBoolObject? = SwiftBoolObject(value: [true])
override class func ignoredProperties() -> [String] {
return [
"optNSStringCol",
"optStringCol",
"optBinaryCol",
"optDateCol",
"optObjectCol"
]
}
}
class SwiftDogObject: Object {
@objc dynamic var dogName = ""
let owners = LinkingObjects(fromType: SwiftOwnerObject.self, property: "dog")
}
class SwiftOwnerObject: Object {
@objc dynamic var name = ""
@objc dynamic var dog: SwiftDogObject? = SwiftDogObject()
}
class SwiftAggregateObject: Object {
@objc dynamic var intCol = 0
@objc dynamic var floatCol = 0 as Float
@objc dynamic var doubleCol = 0.0
@objc dynamic var boolCol = false
@objc dynamic var dateCol = Date()
@objc dynamic var trueCol = true
let stringListCol = List<SwiftStringObject>()
}
class SwiftAllIntSizesObject: Object {
@objc dynamic var int8: Int8 = 0
@objc dynamic var int16: Int16 = 0
@objc dynamic var int32: Int32 = 0
@objc dynamic var int64: Int64 = 0
}
class SwiftEmployeeObject: Object {
@objc dynamic var name = ""
@objc dynamic var age = 0
@objc dynamic var hired = false
}
class SwiftCompanyObject: Object {
let employees = List<SwiftEmployeeObject>()
}
class SwiftArrayPropertyObject: Object {
@objc dynamic var name = ""
let array = List<SwiftStringObject>()
let intArray = List<SwiftIntObject>()
}
class SwiftDoubleListOfSwiftObject: Object {
let array = List<SwiftListOfSwiftObject>()
}
class SwiftListOfSwiftObject: Object {
let array = List<SwiftObject>()
}
class SwiftListOfSwiftOptionalObject: Object {
let array = List<SwiftOptionalObject>()
}
class SwiftArrayPropertySubclassObject: SwiftArrayPropertyObject {
let boolArray = List<SwiftBoolObject>()
}
class SwiftLinkToPrimaryStringObject: Object {
@objc dynamic var pk = ""
@objc dynamic var object: SwiftPrimaryStringObject?
let objects = List<SwiftPrimaryStringObject>()
override class func primaryKey() -> String? {
return "pk"
}
}
class SwiftUTF8Object: Object {
// swiftlint:disable:next identifier_name
@objc dynamic var 柱колоéнǢкƱаم👍 = "值значен™👍☞⎠‱௹♣︎☐▼❒∑⨌⧭иеمرحبا"
}
class SwiftIgnoredPropertiesObject: Object {
@objc dynamic var name = ""
@objc dynamic var age = 0
@objc dynamic var runtimeProperty: AnyObject?
@objc dynamic var runtimeDefaultProperty = "property"
@objc dynamic var readOnlyProperty: Int { return 0 }
override class func ignoredProperties() -> [String] {
return ["runtimeProperty", "runtimeDefaultProperty"]
}
}
class SwiftRecursiveObject: Object {
let objects = List<SwiftRecursiveObject>()
}
protocol SwiftPrimaryKeyObjectType {
associatedtype PrimaryKey
static func primaryKey() -> String?
}
class SwiftPrimaryStringObject: Object, SwiftPrimaryKeyObjectType {
@objc dynamic var stringCol = ""
@objc dynamic var intCol = 0
typealias PrimaryKey = String
override class func primaryKey() -> String? {
return "stringCol"
}
}
class SwiftPrimaryOptionalStringObject: Object, SwiftPrimaryKeyObjectType {
@objc dynamic var stringCol: String? = ""
@objc dynamic var intCol = 0
typealias PrimaryKey = String?
override class func primaryKey() -> String? {
return "stringCol"
}
}
class SwiftPrimaryIntObject: Object, SwiftPrimaryKeyObjectType {
@objc dynamic var stringCol = ""
@objc dynamic var intCol = 0
typealias PrimaryKey = Int
override class func primaryKey() -> String? {
return "intCol"
}
}
class SwiftPrimaryOptionalIntObject: Object, SwiftPrimaryKeyObjectType {
@objc dynamic var stringCol = ""
let intCol = RealmOptional<Int>()
typealias PrimaryKey = RealmOptional<Int>
override class func primaryKey() -> String? {
return "intCol"
}
}
class SwiftPrimaryInt8Object: Object, SwiftPrimaryKeyObjectType {
@objc dynamic var stringCol = ""
@objc dynamic var int8Col: Int8 = 0
typealias PrimaryKey = Int8
override class func primaryKey() -> String? {
return "int8Col"
}
}
class SwiftPrimaryOptionalInt8Object: Object, SwiftPrimaryKeyObjectType {
@objc dynamic var stringCol = ""
let int8Col = RealmOptional<Int8>()
typealias PrimaryKey = RealmOptional<Int8>
override class func primaryKey() -> String? {
return "int8Col"
}
}
class SwiftPrimaryInt16Object: Object, SwiftPrimaryKeyObjectType {
@objc dynamic var stringCol = ""
@objc dynamic var int16Col: Int16 = 0
typealias PrimaryKey = Int16
override class func primaryKey() -> String? {
return "int16Col"
}
}
class SwiftPrimaryOptionalInt16Object: Object, SwiftPrimaryKeyObjectType {
@objc dynamic var stringCol = ""
let int16Col = RealmOptional<Int16>()
typealias PrimaryKey = RealmOptional<Int16>
override class func primaryKey() -> String? {
return "int16Col"
}
}
class SwiftPrimaryInt32Object: Object, SwiftPrimaryKeyObjectType {
@objc dynamic var stringCol = ""
@objc dynamic var int32Col: Int32 = 0
typealias PrimaryKey = Int32
override class func primaryKey() -> String? {
return "int32Col"
}
}
class SwiftPrimaryOptionalInt32Object: Object, SwiftPrimaryKeyObjectType {
@objc dynamic var stringCol = ""
let int32Col = RealmOptional<Int32>()
typealias PrimaryKey = RealmOptional<Int32>
override class func primaryKey() -> String? {
return "int32Col"
}
}
class SwiftPrimaryInt64Object: Object, SwiftPrimaryKeyObjectType {
@objc dynamic var stringCol = ""
@objc dynamic var int64Col: Int64 = 0
typealias PrimaryKey = Int64
override class func primaryKey() -> String? {
return "int64Col"
}
}
class SwiftPrimaryOptionalInt64Object: Object, SwiftPrimaryKeyObjectType {
@objc dynamic var stringCol = ""
let int64Col = RealmOptional<Int64>()
typealias PrimaryKey = RealmOptional<Int64>
override class func primaryKey() -> String? {
return "int64Col"
}
}
class SwiftIndexedPropertiesObject: Object {
@objc dynamic var stringCol = ""
@objc dynamic var intCol = 0
@objc dynamic var int8Col: Int8 = 0
@objc dynamic var int16Col: Int16 = 0
@objc dynamic var int32Col: Int32 = 0
@objc dynamic var int64Col: Int64 = 0
@objc dynamic var boolCol = false
@objc dynamic var dateCol = Date()
@objc dynamic var floatCol: Float = 0.0
@objc dynamic var doubleCol: Double = 0.0
@objc dynamic var dataCol = Data()
override class func indexedProperties() -> [String] {
return ["stringCol", "intCol", "int8Col", "int16Col", "int32Col", "int64Col", "boolCol", "dateCol"]
}
}
class SwiftIndexedOptionalPropertiesObject: Object {
@objc dynamic var optionalStringCol: String? = ""
let optionalIntCol = RealmOptional<Int>()
let optionalInt8Col = RealmOptional<Int8>()
let optionalInt16Col = RealmOptional<Int16>()
let optionalInt32Col = RealmOptional<Int32>()
let optionalInt64Col = RealmOptional<Int64>()
let optionalBoolCol = RealmOptional<Bool>()
@objc dynamic var optionalDateCol: Date? = Date()
let optionalFloatCol = RealmOptional<Float>()
let optionalDoubleCol = RealmOptional<Double>()
@objc dynamic var optionalDataCol: Data? = Data()
override class func indexedProperties() -> [String] {
return ["optionalStringCol", "optionalIntCol", "optionalInt8Col", "optionalInt16Col",
"optionalInt32Col", "optionalInt64Col", "optionalBoolCol", "optionalDateCol"]
}
}
class SwiftCustomInitializerObject: Object {
@objc dynamic var stringCol: String
init(stringVal: String) {
stringCol = stringVal
super.init()
}
required init() {
stringCol = ""
super.init()
}
required init(realm: RLMRealm, schema: RLMObjectSchema) {
stringCol = ""
super.init(realm: realm, schema: schema)
}
required init(value: Any, schema: RLMSchema) {
stringCol = ""
super.init(value: value, schema: schema)
}
}
class SwiftConvenienceInitializerObject: Object {
@objc dynamic var stringCol = ""
convenience init(stringCol: String) {
self.init()
self.stringCol = stringCol
}
}
class SwiftObjectiveCTypesObject: Object {
@objc dynamic var stringCol: NSString?
@objc dynamic var dateCol: NSDate?
@objc dynamic var dataCol: NSData?
@objc dynamic var numCol: NSNumber? = 0
}
class SwiftComputedPropertyNotIgnoredObject: Object {
// swiftlint:disable:next identifier_name
@objc dynamic var _urlBacking = ""
// Dynamic; no ivar
@objc dynamic var dynamicURL: URL? {
get {
return URL(string: _urlBacking)
}
set {
_urlBacking = newValue?.absoluteString ?? ""
}
}
// Non-dynamic; no ivar
var url: URL? {
get {
return URL(string: _urlBacking)
}
set {
_urlBacking = newValue?.absoluteString ?? ""
}
}
}
@objc(SwiftObjcRenamedObject)
class SwiftObjcRenamedObject: Object {
@objc dynamic var stringCol = ""
}
@objc(SwiftObjcRenamedObjectWithTotallyDifferentName)
class SwiftObjcArbitrarilyRenamedObject: Object {
@objc dynamic var boolCol = false
}
class SwiftCircleObject: Object {
@objc dynamic var obj: SwiftCircleObject?
let array = List<SwiftCircleObject>()
}
// Exists to serve as a superclass to `SwiftGenericPropsOrderingObject`
class SwiftGenericPropsOrderingParent: Object {
var implicitlyIgnoredComputedProperty: Int { return 0 }
let implicitlyIgnoredReadOnlyProperty: Int = 1
let parentFirstList = List<SwiftIntObject>()
@objc dynamic var parentFirstNumber = 0
func parentFunction() -> Int { return parentFirstNumber + 1 }
@objc dynamic var parentSecondNumber = 1
var parentComputedProp: String { return "hello world" }
}
// Used to verify that Swift properties (generic and otherwise) are detected properly and
// added to the schema in the correct order.
class SwiftGenericPropsOrderingObject: SwiftGenericPropsOrderingParent {
func myFunction() -> Int { return firstNumber + secondNumber + thirdNumber }
@objc dynamic var dynamicComputed: Int { return 999 }
var firstIgnored = 999
@objc dynamic var dynamicIgnored = 999
@objc dynamic var firstNumber = 0 // Managed property
class func myClassFunction(x: Int, y: Int) -> Int { return x + y }
var secondIgnored = 999
lazy var lazyIgnored = 999
let firstArray = List<SwiftStringObject>() // Managed property
@objc dynamic var secondNumber = 0 // Managed property
var computedProp: String { return "\(firstNumber), \(secondNumber), and \(thirdNumber)" }
let secondArray = List<SwiftStringObject>() // Managed property
override class func ignoredProperties() -> [String] {
return ["firstIgnored", "dynamicIgnored", "secondIgnored", "thirdIgnored", "lazyIgnored", "dynamicLazyIgnored"]
}
let firstOptionalNumber = RealmOptional<Int>() // Managed property
var thirdIgnored = 999
@objc dynamic lazy var dynamicLazyIgnored = 999
let firstLinking = LinkingObjects(fromType: SwiftGenericPropsOrderingHelper.self, property: "first")
let secondLinking = LinkingObjects(fromType: SwiftGenericPropsOrderingHelper.self, property: "second")
@objc dynamic var thirdNumber = 0 // Managed property
let secondOptionalNumber = RealmOptional<Int>() // Managed property
}
// Only exists to allow linking object properties on `SwiftGenericPropsNotLastObject`.
class SwiftGenericPropsOrderingHelper: Object {
@objc dynamic var first: SwiftGenericPropsOrderingObject?
@objc dynamic var second: SwiftGenericPropsOrderingObject?
}
class SwiftRenamedProperties1: Object {
@objc dynamic var propA = 0
@objc dynamic var propB = ""
let linking1 = LinkingObjects(fromType: LinkToSwiftRenamedProperties1.self, property: "linkA")
let linking2 = LinkingObjects(fromType: LinkToSwiftRenamedProperties2.self, property: "linkD")
override class func _realmObjectName() -> String { return "Swift Renamed Properties" }
override class func _realmColumnNames() -> [String: String] {
return ["propA": "prop 1", "propB": "prop 2"]
}
}
class SwiftRenamedProperties2: Object {
@objc dynamic var propC = 0
@objc dynamic var propD = ""
let linking1 = LinkingObjects(fromType: LinkToSwiftRenamedProperties1.self, property: "linkA")
let linking2 = LinkingObjects(fromType: LinkToSwiftRenamedProperties2.self, property: "linkD")
override class func _realmObjectName() -> String { return "Swift Renamed Properties" }
override class func _realmColumnNames() -> [String: String] {
return ["propC": "prop 1", "propD": "prop 2"]
}
}
class LinkToSwiftRenamedProperties1: Object {
@objc dynamic var linkA: SwiftRenamedProperties1?
@objc dynamic var linkB: SwiftRenamedProperties2?
let array1 = List<SwiftRenamedProperties1>()
override class func _realmObjectName() -> String { return "Link To Swift Renamed Properties" }
override class func _realmColumnNames() -> [String: String] {
return ["linkA": "link 1", "linkB": "link 2", "array1": "array"]
}
}
class LinkToSwiftRenamedProperties2: Object {
@objc dynamic var linkC: SwiftRenamedProperties1?
@objc dynamic var linkD: SwiftRenamedProperties2?
let array2 = List<SwiftRenamedProperties2>()
override class func _realmObjectName() -> String { return "Link To Swift Renamed Properties" }
override class func _realmColumnNames() -> [String: String] {
return ["linkC": "link 1", "linkD": "link 2", "array2": "array"]
}
}
| apache-2.0 | 3f2e94c2d4c57d03c20ac14c025e545e | 31.393635 | 119 | 0.673665 | 4.264388 | false | false | false | false |
pixelspark/catena | Sources/CatenaCore/Gossip.swift | 1 | 26070 | import Foundation
import Kitura
import LoggerAPI
import KituraWebSocket
import Dispatch
#if !os(Linux)
import Starscream
#endif
public enum GossipError: LocalizedError {
case missingActionKey
case unknownAction(String)
case deserializationFailed
case limitExceeded
public var localizedDescription: String {
switch self {
case .missingActionKey: return "action key is missing"
case .unknownAction(let a): return "unknown action '\(a)'"
case .deserializationFailed: return "deserialization of payload failed"
case .limitExceeded: return "a limit was exceeded"
}
}
}
public enum Gossip<LedgerType: Ledger> {
public typealias BlockchainType = LedgerType.BlockchainType
public typealias BlockType = BlockchainType.BlockType
/** Request the peer's index. The reply is either of type 'index' or 'passive'. */
case query // -> index or passive
/** Reply message that contains the peer's index. */
case index(Index<BlockType>)
/** Unsolicited new blocks. */
case block([String: Any]) // no reply
/** Response to a fetch request. `extra` contains a few predecessor blocks to improve fetch speeds (may be empty). */
case result(block: [String: Any], extra: [BlockType.HashType: [String: Any]])
/** Request a specific block from the peer. The reply is of type 'result'. The 'extra' parameter
specifies how many predecessor blocks may be included in the result (as 'extra' blocks). */
case fetch(hash: BlockType.HashType, extra: Int) // -> block
/** An error has occurred. Only sent in reply to a request by the peer. */
case error(String)
/** A transaction the peer wants us to store/relay. */
case transaction([String: Any])
/** The peer indicates that it is a passive peer without an index (in response to a query request) */
case passive
/** The peer requests to be forgotten, most probably because its UUID does not match the requested UUID. */
case forget
init(json: [String: Any]) throws {
if let q = json[LedgerType.ParametersType.actionKey] as? String {
if q == "query" {
self = .query
}
else if q == "block" {
if let blockData = json["block"] as? [String: Any] {
self = .block(blockData)
}
else {
throw GossipError.deserializationFailed
}
}
else if q == "result" {
if let blockData = json["block"] as? [String: Any] {
var extraBlocks: [BlockType.HashType: [String: Any]] = [:]
if let extra = json["extra"] as? [String: [String: Any]] {
if extra.count > LedgerType.ParametersType.maximumExtraBlocks {
throw GossipError.limitExceeded
}
for (hash, extraBlockData) in extra {
extraBlocks[try BlockType.HashType(hash: hash)] = extraBlockData
}
}
self = .result(block: blockData, extra: extraBlocks)
}
else {
throw GossipError.deserializationFailed
}
}
else if q == "fetch" {
if let hash = json["hash"] as? String {
let extra = (json["extra"] as? Int) ?? 0
self = .fetch(hash: try BlockType.HashType(hash: hash), extra: extra)
}
else {
throw GossipError.deserializationFailed
}
}
else if q == "index" {
if let idx = json["index"] as? [String: Any] {
self = .index(try Index<BlockType>(json: idx))
}
else {
throw GossipError.deserializationFailed
}
}
else if q == "error" {
if let message = json["message"] as? String {
self = .error(message)
}
else {
throw GossipError.deserializationFailed
}
}
else if q == "tx" {
if let tx = json["tx"] as? [String: Any] {
self = .transaction(tx)
}
else {
throw GossipError.deserializationFailed
}
}
else if q == "passive" {
self = .passive
}
else if q == "forget" {
self = .forget
}
else {
throw GossipError.unknownAction(q)
}
}
else {
throw GossipError.missingActionKey
}
}
var json: [String: Any] {
switch self {
case .query:
return [LedgerType.ParametersType.actionKey: "query"]
case .result(block: let b, extra: let extra):
var extraData: [String: [String: Any]] = [:]
for (hash, extraBlock) in extra {
extraData[hash.stringValue] = extraBlock
}
return [LedgerType.ParametersType.actionKey: "result", "block": b, "extra": extraData]
case .block(let b):
return [LedgerType.ParametersType.actionKey: "block", "block": b]
case .index(let i):
return [LedgerType.ParametersType.actionKey: "index", "index": i.json]
case .fetch(hash: let h, extra: let e):
return [LedgerType.ParametersType.actionKey: "fetch", "hash": h.stringValue, "extra": e]
case .transaction(let tx):
return [LedgerType.ParametersType.actionKey: "tx", "tx": tx]
case .error(let m):
return [LedgerType.ParametersType.actionKey: "error", "message": m]
case .passive:
return [LedgerType.ParametersType.actionKey: "passive"]
case .forget:
return [LedgerType.ParametersType.actionKey: "forget"]
}
}
}
public class Server<LedgerType: Ledger>: WebSocketService {
public typealias BlockchainType = LedgerType.BlockchainType
public typealias BlockType = BlockchainType.BlockType
public let router = Router()
public let port: Int
private let mutex = Mutex()
private var gossipConnections = [String: PeerIncomingConnection<LedgerType>]()
weak var node: Node<LedgerType>?
init(node: Node<LedgerType>, port: Int) {
self.node = node
self.port = port
WebSocket.register(service: self, onPath: "/")
Kitura.addHTTPServer(onPort: port, with: router)
}
public func connected(connection: WebSocketConnection) {
Log.debug("[Server] gossip connected incoming \(connection.request.remoteAddress) \(connection.request.urlURL.absoluteString)")
self.mutex.locked {
do {
let pic = try PeerIncomingConnection<LedgerType>(connection: connection)
self.node?.add(peer: pic)
self.gossipConnections[connection.id] = pic
}
catch {
Log.error("[Server] \(error.localizedDescription)")
}
}
}
public func disconnected(connection: WebSocketConnection, reason: WebSocketCloseReasonCode) {
Log.info("[Server] disconnected gossip \(connection.id); reason=\(reason)")
self.mutex.locked {
if let pic = self.gossipConnections[connection.id] {
pic.disconnected()
self.gossipConnections.removeValue(forKey: connection.id)
}
}
}
public func received(message: Data, from: WebSocketConnection) {
do {
if let d = try JSONSerialization.jsonObject(with: message, options: []) as? [Any] {
try self.handleGossip(data: d, from: from)
}
else {
Log.error("[Gossip] Invalid format")
}
}
catch {
Log.error("[Gossip] Invalid: \(error.localizedDescription)")
}
}
public func received(message: String, from: WebSocketConnection) {
do {
if let d = try JSONSerialization.jsonObject(with: message.data(using: .utf8)!, options: []) as? [Any] {
try self.handleGossip(data: d, from: from)
}
else {
Log.error("[Gossip] Invalid format")
}
}
catch {
Log.error("[Gossip] Invalid: \(error.localizedDescription)")
}
}
func handleGossip(data: [Any], from: WebSocketConnection) throws {
Log.debug("[Gossip] received \(data)")
self.mutex.locked {
if let pic = self.gossipConnections[from.id] {
DispatchQueue.global().async {
pic.receive(data: data)
}
}
else {
Log.error("[Server] received gossip data for non-connection: \(from.id)")
}
}
}
}
public struct Index<BlockType: Block>: Equatable {
let genesis: BlockType.HashType
let peers: [URL]
let highest: BlockType.HashType
let height: BlockType.IndexType
let timestamp: BlockType.TimestampType
init(genesis: BlockType.HashType, peers: [URL], highest: BlockType.HashType, height: BlockType.IndexType, timestamp: BlockType.TimestampType) {
self.genesis = genesis
self.peers = peers
self.highest = highest
self.height = height
self.timestamp = timestamp
}
init(json: [String: Any]) throws {
if let genesisHash = json["genesis"] as? String,
let highestHash = json["highest"] as? String,
let peers = json["peers"] as? [String] {
let genesis = try BlockType.HashType(hash: genesisHash)
let highest = try BlockType.HashType(hash: highestHash)
self.genesis = genesis
self.highest = highest
self.peers = peers.compactMap { return URL(string: $0) }
if let height = json["height"] as? NSNumber, let timestamp = json["time"] as? NSNumber {
// Darwin
self.height = BlockType.IndexType(height.uint64Value)
self.timestamp = BlockType.TimestampType(timestamp.uint64Value)
}
else if let height = json["height"] as? Int, let timestamp = json["time"] as? Int {
// Linux
self.height = BlockType.IndexType(height)
self.timestamp = BlockType.TimestampType(timestamp)
}
else {
throw GossipError.deserializationFailed
}
}
else {
throw GossipError.deserializationFailed
}
}
public static func ==(lhs: Index<BlockType>, rhs: Index<BlockType>) -> Bool {
return lhs.genesis == rhs.genesis &&
lhs.peers == rhs.peers &&
lhs.highest == rhs.highest &&
lhs.height == rhs.height &&
lhs.timestamp == rhs.timestamp
}
var json: [String: Any] {
return [
"highest": self.highest.stringValue,
"height": NSNumber(value: self.height),
"genesis": self.genesis.stringValue,
"time": NSNumber(value: self.timestamp),
"peers": self.peers.map { $0.absoluteString }
]
}
}
public protocol PeerConnectionDelegate {
associatedtype LedgerType: Ledger
func peer(connection: PeerConnection<LedgerType>, requests gossip: Gossip<LedgerType>, counter: Int)
func peer(connected _: PeerConnection<LedgerType>)
func peer(disconnected _: PeerConnection<LedgerType>)
}
public class PeerConnection<LedgerType: Ledger> {
public typealias GossipType = Gossip<LedgerType>
public typealias Callback = (Gossip<LedgerType>) -> ()
public let mutex = Mutex()
private var counter = 0
private var callbacks: [Int: Callback] = [:]
public weak var delegate: Peer<LedgerType>? = nil
fileprivate init(isIncoming: Bool) {
self.counter = isIncoming ? 1 : 0
}
public func receive(data: [Any]) {
if data.count == 2, let counter = data[0] as? Int, let gossipData = data[1] as? [String: Any] {
do {
let g = try GossipType(json: gossipData)
self.mutex.locked {
if counter != 0, let cb = callbacks[counter] {
self.callbacks.removeValue(forKey: counter)
DispatchQueue.global().async {
cb(g)
}
}
else {
// Unsolicited
Log.debug("[Gossip] Get \(counter): \(g)")
if let d = self.delegate {
DispatchQueue.global().async {
d.peer(connection: self, requests: g, counter: counter)
}
}
else {
Log.error("[Server] cannot handle gossip \(counter) for \(self): no delegate. Message is \(g.json)")
}
}
}
}
catch {
Log.warning("[Gossip] Received invalid gossip \(error.localizedDescription): \(gossipData)")
}
}
else {
Log.warning("[Gossip] Received malformed gossip: \(data)")
}
}
public final func reply(counter: Int, gossip: GossipType) throws {
try self.mutex.locked {
let d = try JSONSerialization.data(withJSONObject: [counter, gossip.json], options: [])
try self.send(data: d)
}
}
public final func request(gossip: GossipType, callback: Callback? = nil) throws {
let c = self.mutex.locked { () -> Int in
counter += 2
if let c = callback {
self.callbacks[counter] = c
}
return counter
}
try self.mutex.locked {
Log.debug("[PeerConnection] send request \(c)")
let d = try JSONSerialization.data(withJSONObject: [c, gossip.json], options: [])
try self.send(data: d)
}
}
public func send(data: Data) throws {
fatalError("Should be subclassed")
}
}
enum PeerConnectionError: LocalizedError {
case protocolVersionMissing
case protocolVersionUnsupported(version: String)
case notConnected
var errorDescription: String? {
switch self {
case .protocolVersionMissing: return "the client did not indicate a protocol version"
case .protocolVersionUnsupported(version: let v): return "protocol version '\(v)' is not supported"
case .notConnected: return "the peer is not connected"
}
}
}
public class PeerIncomingConnection<LedgerType: Ledger>: PeerConnection<LedgerType>, CustomDebugStringConvertible {
let connection: WebSocketConnection
init(connection: WebSocketConnection) throws {
guard let protocolVersion = connection.request.headers["Sec-WebSocket-Protocol"]?.first else { throw PeerConnectionError.protocolVersionMissing }
if protocolVersion != LedgerType.ParametersType.protocolVersion {
throw PeerConnectionError.protocolVersionUnsupported(version: protocolVersion)
}
self.connection = connection
super.init(isIncoming: true)
}
deinit {
self.connection.close()
}
/** Called by the Server class when the WebSocket connection is disconnected. */
fileprivate func disconnected() {
self.delegate?.peer(disconnected: self)
}
func close() {
self.connection.close()
}
public override func send(data: Data) throws {
self.connection.send(message: data, asBinary: false)
}
public var debugDescription: String {
return "PeerIncomingConnection(\(self.connection.request.remoteAddress) -> \(self.connection.request.urlURL.absoluteString)";
}
}
#if !os(Linux)
public class PeerOutgoingConnection<LedgerType: Ledger>: PeerConnection<LedgerType>, WebSocketDelegate {
let connection: Starscream.WebSocket
public init?(to url: URL, from uuid: UUID? = nil, at port: Int? = nil) {
assert((uuid != nil && port != nil) || (uuid == nil && port == nil), "either set both a port and uuid or set neither (passive mode)")
if var uc = URLComponents(url: url, resolvingAgainstBaseURL: false) {
// Set source peer port and UUID
if let uuid = uuid, let port = port {
if port <= 0 {
return nil
}
uc.queryItems = [
URLQueryItem(name: LedgerType.ParametersType.uuidRequestKey, value: uuid.uuidString),
URLQueryItem(name: LedgerType.ParametersType.portRequestKey, value: String(port))
]
}
self.connection = Starscream.WebSocket(url: uc.url!, protocols: [LedgerType.ParametersType.protocolVersion])
super.init(isIncoming: false)
}
else {
return nil
}
}
init(connection: Starscream.WebSocket) {
self.connection = connection
super.init(isIncoming: false)
}
public func connect() {
self.connection.delegate = self
self.connection.callbackQueue = DispatchQueue.global(qos: .background)
if !self.connection.isConnected {
self.connection.connect()
}
}
public override func send(data: Data) throws {
if self.connection.isConnected {
self.connection.write(data: data)
}
else {
throw PeerConnectionError.notConnected
}
}
public func websocketDidConnect(socket: Starscream.WebSocketClient) {
self.delegate?.peer(connected: self)
}
public func websocketDidReceiveData(socket: Starscream.WebSocketClient, data: Data) {
do {
if let obj = try JSONSerialization.jsonObject(with: data, options: []) as? [Any] {
self.receive(data: obj)
}
else {
Log.error("[Gossip] Outgoing socket received malformed data")
}
}
catch {
Log.error("[Gossip] Outgoing socket received malformed data: \(error)")
}
}
public func websocketDidDisconnect(socket: Starscream.WebSocketClient, error: Error?) {
self.delegate?.peer(disconnected: self)
self.delegate = nil
connection.delegate = nil
}
public func websocketDidReceiveMessage(socket: Starscream.WebSocketClient, text: String) {
self.websocketDidReceiveData(socket: socket, data: text.data(using: .utf8)!)
}
}
#endif
public class Peer<LedgerType: Ledger>: PeerConnectionDelegate, CustomDebugStringConvertible {
typealias BlockchainType = LedgerType.BlockchainType
typealias BlockType = BlockchainType.BlockType
typealias TransactionType = BlockType.TransactionType
public let url: URL
/** Time at which we last received a response or request from this peer. Nil when that never happened. */
public internal(set) var lastSeen: Date? = nil
/** The time difference observed during the last index request */
public internal(set) var lastIndexRequestLatency: TimeInterval? = nil
public internal(set) var timeDifference: TimeInterval? = nil
public internal(set) var state: PeerState
fileprivate(set) var connection: PeerConnection<LedgerType>? = nil
weak var node: Node<LedgerType>?
public let mutex = Mutex()
private struct Request: CustomStringConvertible {
let connection: PeerConnection<LedgerType>
let gossip: Gossip<LedgerType>
let counter: Int
var description: String {
return "#\(self.counter):\(gossip)"
}
}
public var debugDescription: String {
return "<\(self.url.absoluteString)>"
}
private lazy var queue = ThrottlingQueue<Request>(interval: LedgerType.ParametersType.maximumPeerRequestRate, maxQueuedRequests: LedgerType.ParametersType.maximumPeerRequestQueueSize) { [weak self] (request: Request) throws -> () in
try self?.process(request: request)
}
init(url: URL, state: PeerState, connection: PeerConnection<LedgerType>?, delegate: Node<LedgerType>) {
assert(Peer<LedgerType>.isValidPeerURL(url: url), "Peer URL must be valid")
self.url = url
self.state = state
self.connection = connection
self.node = delegate
connection?.delegate = self
}
public var uuid: UUID {
return UUID(uuidString: self.url.user!)!
}
static public func isValidPeerURL(url: URL) -> Bool {
if let uc = URLComponents(url: url, resolvingAgainstBaseURL: false) {
// URL must contain a port, host and user part
if uc.port == nil || uc.host == nil || uc.user == nil {
return false
}
// The user in the URL must be a valid node identifier (UUID)
if UUID(uuidString: uc.user!) == nil {
return false
}
return true
}
return false
}
/** Returns true when a peer action was performed, false when no action was required. */
public func advance() -> Bool {
return self.mutex.locked { () -> Bool in
Log.debug("Advance peer \(url) from state \(self.state)")
do {
if let n = node {
// If the connection has been disconnected since the last time we checked, reset state
if self.connection == nil {
switch self.state {
case .connected, .connecting(since: _), .queried, .querying(since: _), .passive:
self.state = .new(since: Date())
case .new(since: _), .failed(error: _, at: _), .ignored(reason: _):
break
}
}
switch self.state {
case .failed(error: _, at: let date):
// Failed peers become 'new' after a certain amount of time, so we can retry
if Date().timeIntervalSince(date) > LedgerType.ParametersType.peerRetryAfterFailureInterval {
self.connection = nil
self.state = .new(since: date)
}
return false
case .new:
// Perhaps reconnect to this peer
#if !os(Linux)
if url.port == nil || url.port! == 0 {
self.state = .ignored(reason: "disconnected, and peer does not accept incoming connections")
}
else if let pic = PeerOutgoingConnection<LedgerType>(to: url, from: n.uuid, at: n.server.port) {
pic.delegate = self
self.state = .connecting(since: Date())
self.connection = pic
Log.debug("[Peer] connect outgoing \(url)")
pic.connect()
}
#else
// Outgoing connections are not supported on Linux (yet!)
self.state = .ignored(reason: "disconnected, and cannot make outgoing connections")
#endif
return true
case .connected, .queried:
try self.query()
return true
case .passive, .ignored(reason: _):
// Do nothing (perhaps ping in the future?)
return false
case .connecting(since: let date), .querying(since: let date):
// Reset hung peers
if Date().timeIntervalSince(date) > LedgerType.ParametersType.peerRetryAfterFailureInterval {
self.connection = nil
self.state = .new(since: date)
}
return true
}
}
else {
return false
}
}
catch {
self.fail(error: "advance error: \(error.localizedDescription)")
return false
}
}
}
public func fail(error: String) {
self.mutex.locked {
Log.info("[Peer] \(self.url.absoluteString) failing: \(error)")
self.connection = nil
self.state = .failed(error: error, at: Date())
}
}
private func query() throws {
if let n = self.node, let c = self.connection {
self.mutex.locked {
self.state = .querying(since: Date())
}
let requestTime = Date()
try c.request(gossip: .query) { reply in
// Update last seen
self.mutex.locked {
self.lastSeen = Date()
// Update observed time difference
let requestEndTime = Date()
self.lastIndexRequestLatency = requestEndTime.timeIntervalSince(requestTime) / 2.0
}
if case .index(let index) = reply {
Log.debug("[Peer] Receive index reply: \(index)")
self.mutex.locked {
// Update peer status
if index.genesis != n.ledger.longest.genesis.signature! {
// Peer believes in another genesis, ignore him
self.connection = nil
self.state = .ignored(reason: "believes in other genesis")
}
else {
self.state = .queried
}
// Calculate time difference
// TODO: perhaps add (requestEndTime - requestTime) to make this more precise
let peerTime = Date(timeIntervalSince1970: TimeInterval(index.timestamp))
self.timeDifference = peerTime.timeIntervalSinceNow
}
// New peers?
for p in index.peers {
n.add(peer: p)
}
// Request the best block from this peer
n.receive(best: Candidate(hash: index.highest, height: index.height, peer: self.uuid))
}
else if case .passive = reply {
self.mutex.locked {
self.state = .passive
}
}
else {
self.fail(error: "Invalid reply received to query request")
}
}
}
}
private func process(request: Request) throws {
Log.debug("[Peer] process request \(request.counter) for peer \(self)")
switch request.gossip {
case .forget:
try self.node?.forget(peer: self)
self.state = .ignored(reason: "peer requested to be forgotten")
case .transaction(let trData):
let tr = try TransactionType(json: trData)
_ = try self.node?.receive(transaction: tr, from: self)
case .block(let blockData):
do {
let b = try BlockType.read(json: blockData)
try self.node?.receive(block: b, from: self, wasRequested: false)
}
catch {
self.fail(error: "Received invalid unsolicited block")
}
case .fetch(hash: let h, extra: let extraBlocksRequested):
if extraBlocksRequested > LedgerType.ParametersType.maximumExtraBlocks {
self.fail(error: "limit exceeded")
}
else {
try self.node?.ledger.mutex.locked {
if let n = node, let block = try n.ledger.longest.get(block: h) {
assert(block.isSignatureValid, "returning invalid blocks, that can't be good")
assert(try! BlockType.read(json: block.json).isSignatureValid, "JSON goes wild")
// Fetch predecessors
var extra: [BlockType.HashType: [String: Any]] = [:]
var last = block
for _ in 0..<extraBlocksRequested {
if last.index <= 0 {
break
}
if let block = try n.ledger.longest.get(block: last.previous) {
assert(block.signature! == last.previous)
extra[block.signature!] = block.json
last = block
}
else {
break
}
}
try request.connection.reply(counter: request.counter, gossip: .result(block: block.json, extra: extra))
}
else {
try request.connection.reply(counter: request.counter, gossip: .error("not found"))
}
}
}
case .query:
// We received a query from the other end
if let n = self.node {
let idx = n.ledger.mutex.locked {
return Index<BlockchainType.BlockType>(
genesis: n.ledger.longest.genesis.signature!,
peers: Array(n.validPeers),
highest: n.ledger.longest.highest.signature!,
height: n.ledger.longest.highest.index,
timestamp: BlockchainType.BlockType.TimestampType(Date().timeIntervalSince1970)
)
}
try request.connection.reply(counter: request.counter, gossip: .index(idx))
}
break
default:
// These are not requests we handle. Ignore clients that don't play by the rules
self.state = .ignored(reason: "peer sent invalid request \(request.gossip)")
break
}
}
public func peer(connection: PeerConnection<LedgerType>, requests gossip: Gossip<LedgerType>, counter: Int) {
self.lastSeen = Date()
Log.debug("[Peer] receive request \(counter)")
self.queue.enqueue(request: Request(connection: connection, gossip: gossip, counter: counter))
}
public func peer(connected _: PeerConnection<LedgerType>) {
self.mutex.locked {
if case .connecting = self.state {
Log.debug("[Peer] \(url) connected outgoing")
self.state = .connected
}
else {
Log.error("[Peer] \(url) connected while not connecting")
}
}
}
public func peer(disconnected _: PeerConnection<LedgerType>) {
self.mutex.locked {
Log.debug("[Peer] \(url) disconnected outgoing")
self.connection = nil
self.fail(error: "disconnected")
}
}
}
public enum PeerState {
case new(since: Date) // Peer has not yet connected
case connecting(since: Date)
case connected // The peer is connected but has not been queried yet
case querying(since: Date) // The peer is currently being queried
case queried // The peer has last been queried successfully
case passive // Peer is active, but should not be queried (only listens passively)
case ignored(reason: String) // The peer is ourselves or believes in another genesis, ignore it forever
case failed(error: String, at: Date) // Talking to the peer failed for some reason, ignore it for a while
}
| mit | da55dcdc96fbdad5cb1c1d317daf3f34 | 29.349243 | 233 | 0.673379 | 3.52774 | false | false | false | false |
ahoppen/swift | test/Inputs/resilient_struct.swift | 29 | 2031 | // Fixed-layout struct
@frozen public struct Point {
public var x: Int // read-write stored property
public let y: Int // read-only stored property
public init(x: Int, y: Int) {
self.x = x
self.y = y
}
public func method() {}
public mutating func mutantMethod() {}
}
// Resilient-layout struct
public struct Size {
public var w: Int // should have getter and setter
public let h: Int // getter only
public init(w: Int, h: Int) {
self.w = w
self.h = h
}
public func method() {}
public mutating func mutantMethod() {}
}
// Fixed-layout struct with resilient members
@frozen public struct Rectangle {
public let p: Point
public let s: Size
public let color: Int
public init(p: Point, s: Size, color: Int) {
self.p = p
self.s = s
self.color = color
}
}
// More complicated resilient structs for runtime tests
public struct ResilientBool {
public let b: Bool
public init(b: Bool) {
self.b = b
}
}
public struct ResilientInt {
public let i: Int
public init(i: Int) {
self.i = i
}
}
public struct ResilientDouble {
public let d: Double
public init(d: Double) {
self.d = d
}
}
@frozen public struct ResilientLayoutRuntimeTest {
public let b1: ResilientBool
public let i: ResilientInt
public let b2: ResilientBool
public let d: ResilientDouble
public init(b1: ResilientBool, i: ResilientInt, b2: ResilientBool, d: ResilientDouble) {
self.b1 = b1
self.i = i
self.b2 = b2
self.d = d
}
}
public class Referent {
public init() {}
}
public struct ResilientWeakRef {
public weak var ref: Referent?
public init (_ r: Referent) {
ref = r
}
}
public struct ResilientRef {
public var r: Referent
public init(r: Referent) { self.r = r }
}
public struct ResilientWithInternalField {
var x: Int
}
// Tuple parameters with resilient structs
public class Subject {}
public struct Container {
public var s: Subject
}
public struct PairContainer {
public var pair : (Container, Container)
}
| apache-2.0 | 21f1bfa8bfff46b1a588117e12bcac09 | 17.133929 | 90 | 0.666667 | 3.582011 | false | false | false | false |
google/JacquardSDKiOS | Example/JacquardSDK/ScanningView/ScanningTableViewCell.swift | 1 | 2828 | // Copyright 2021 Google LLC
//
// 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 JacquardSDK
import MaterialComponents
import UIKit
class ScanningTableViewCell: UITableViewCell {
static let reuseIdentifier = "tagCellIdentifier"
@IBOutlet private weak var title: UILabel!
@IBOutlet private weak var checkboxImageView: UIImageView!
func configure(with model: AdvertisingTagCellModel, isSelected: Bool) {
let tagPrefixText = NSMutableAttributedString(string: "Jacquard Tag ")
let tagName = NSMutableAttributedString(
string: model.tag.displayName,
attributes: [NSAttributedString.Key.font: UIFont.system16Medium]
)
layer.masksToBounds = true
layer.cornerRadius = 5
layer.borderWidth = 1
layer.shadowOffset = CGSize(width: -1, height: 1)
layer.borderColor = UIColor.black.withAlphaComponent(0.3).cgColor
if isSelected {
contentView.backgroundColor = .black
let attributes = [NSAttributedString.Key.foregroundColor: UIColor.white]
tagPrefixText.addAttributes(attributes, range: NSMakeRange(0, tagPrefixText.string.count))
tagName.addAttributes(attributes, range: NSMakeRange(0, tagName.string.count))
checkboxImageView.image = UIImage(named: "circularCheck")
} else {
contentView.backgroundColor = .white
let attributes = [NSAttributedString.Key.foregroundColor: UIColor.gray]
tagPrefixText.addAttributes(attributes, range: NSMakeRange(0, tagPrefixText.string.count))
tagName.addAttribute(
NSAttributedString.Key.foregroundColor,
value: UIColor.black,
range: NSMakeRange(0, tagName.string.count)
)
checkboxImageView.image = UIImage(named: "circularUncheck")
}
tagPrefixText.append(tagName)
if let advertisingTag = model.tag as? AdvertisedTag {
let attributes = [
NSAttributedString.Key.font: UIFont.system14Medium,
NSAttributedString.Key.foregroundColor: UIColor.signalColor(advertisingTag.rssi),
]
let rssi = NSMutableAttributedString(
string: " (rssi: \(advertisingTag.rssi))",
attributes: attributes
)
tagPrefixText.append(rssi)
}
title.attributedText = tagPrefixText
let rippleTouchController = MDCRippleTouchController()
rippleTouchController.addRipple(to: self)
}
}
| apache-2.0 | c3e986be933f1ea80670985a8d646894 | 36.706667 | 96 | 0.73338 | 4.620915 | false | false | false | false |
LoganWright/vapor | Sources/Vapor/Validation/And.swift | 1 | 3073 | /*
The MIT License (MIT) Copyright (c) 2016 Benjamin Encz
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.
*/
/**
This struct is used to encompass multiple Validators into one entity.
It is possible to access this struct directly using
And(validatorOne, validatorTwo)
But it is more common to create And objects using the `+` operator:
validatorOne + validatorTwo
*/
public struct And<
V: Validator,
U: Validator where V.InputType == U.InputType> {
private typealias Validator = (input: V.InputType) throws -> Void
private let validator: Validator
/**
Convenience only.
Must stay private.
*/
private init(_ lhs: Validator, _ rhs: Validator) {
validator = { value in
try lhs(input: value)
try rhs(input: value)
}
}
}
extension And: Validator {
/**
Validator conformance that allows the 'And' struct
to concatenate multiple Validator types.
- parameter value: the value to validate
- throws: an error on failed validation
*/
public func validate(input value: V.InputType) throws {
try validator(input: value)
}
}
extension And {
/**
Used to combine two Validator types
*/
public init(_ lhs: V, _ rhs: U) {
self.init(lhs.validate, rhs.validate)
}
}
extension And where V: ValidationSuite {
/**
Used to combine two Validator types where one is a ValidationSuite
*/
public init(_ lhs: V.Type = V.self, _ rhs: U) {
self.init(lhs.validate, rhs.validate)
}
}
extension And where U: ValidationSuite {
/**
Used to combine two Validators where one is a ValidationSuite
*/
public init(_ lhs: V, _ rhs: U.Type = U.self) {
self.init(lhs.validate, rhs.validate)
}
}
extension And where V: ValidationSuite, U: ValidationSuite {
/**
Used to combine two ValidationSuite types
*/
public init(_ lhs: V.Type = V.self, _ rhs: U.Type = U.self) {
self.init(lhs.validate, rhs.validate)
}
}
| mit | 34bf57b8827f2dd1d3f8997119ed6ba9 | 30.357143 | 97 | 0.676212 | 4.39628 | false | false | false | false |
LoveZYForever/HXWeiboPhotoPicker | Pods/HXPHPicker/Sources/HXPHPicker/Editor/Controller/Photo/PhotoEditorViewController+Export.swift | 1 | 1648 | //
// PhotoEditorViewController+Export.swift
// HXPHPicker
//
// Created by Slience on 2021/7/14.
//
import UIKit
extension PhotoEditorViewController {
func exportResources() {
if imageView.canReset() ||
imageView.imageResizerView.hasCropping ||
imageView.canUndoDraw ||
imageView.canUndoMosaic ||
imageView.hasFilter ||
imageView.hasSticker {
imageView.deselectedSticker()
ProgressHUD.showLoading(addedTo: view, text: "正在处理...", animated: true)
imageView.cropping { [weak self] in
guard let self = self else { return }
if let result = $0 {
ProgressHUD.hide(forView: self.view, animated: false)
self.isFinishedBack = true
self.transitionalImage = result.editedImage
self.delegate?.photoEditorViewController(self, didFinish: result)
self.finishHandler?(self, result)
self.didBackClick()
}else {
ProgressHUD.hide(forView: self.view, animated: true)
ProgressHUD.showWarning(
addedTo: self.view,
text: "处理失败".localized,
animated: true,
delayHide: 1.5
)
}
}
}else {
transitionalImage = image
delegate?.photoEditorViewController(didFinishWithUnedited: self)
finishHandler?(self, nil)
didBackClick()
}
}
}
| mit | c3c5d27f2bb728d24cb414b508814537 | 34.478261 | 85 | 0.523284 | 5.298701 | false | false | false | false |
Burning-Man-Earth/iBurn-iOS | iBurn/Tracks/Breadcrumb.swift | 1 | 1482 | //
// Breadcrumb.swift
// iBurn
//
// Created by Chris Ballinger on 7/29/19.
// Copyright © 2019 Burning Man Earth. All rights reserved.
//
import Foundation
import GRDB
struct Breadcrumb {
var id: Int64?
var coordinate: CLLocationCoordinate2D {
get {
return CLLocationCoordinate2D(latitude: latitude, longitude: longitude)
}
set {
latitude = newValue.latitude
longitude = newValue.longitude
}
}
private var latitude: Double
private var longitude: Double
var timestamp: Date
static func from(_ location: CLLocation) -> Breadcrumb {
return Breadcrumb(id: nil, latitude: location.coordinate.latitude, longitude: location.coordinate.longitude, timestamp: location.timestamp)
}
}
// MARK: - Persistence
// Turn Player into a Codable Record.
// See https://github.com/groue/GRDB.swift/blob/master/README.md#records
extension Breadcrumb: Codable, FetchableRecord, MutablePersistableRecord {
// Define database columns from CodingKeys
private enum Columns {
static let id = Column(CodingKeys.id)
static let latitude = Column(CodingKeys.latitude)
static let longitude = Column(CodingKeys.longitude)
static let timestamp = Column(CodingKeys.timestamp)
}
// Update a player id after it has been inserted in the database.
mutating func didInsert(with rowID: Int64, for column: String?) {
id = rowID
}
}
| mpl-2.0 | c7b6b5212bf7935af6d2d0d2104052dd | 29.854167 | 147 | 0.67792 | 4.487879 | false | false | false | false |
briandw/SwiftFighter | SwiftFighter/Quote.swift | 1 | 2829 | //
// Quote.swift
// SwiftFighter
//
// Created by Brian Williams on 4/9/16.
// Copyright © 2016 RL. All rights reserved.
//
import Foundation
var formatter = NSDateFormatter.init()
var formatterInit = false
class Quote
{
var venue : String = ""
var symbol : String = ""
var bid : Int = 0
var bidSize : Int = 0
var bidDepth : Int = 0
var ask : Int = 0
var askSize : Int = 0
var askDepth : Int = 0
var lastPrice : Int = 0
var lastSize : Int = 0
var lastTrade : String = ""
var quoteTime : NSDate?
init (json : NSDictionary)
{
if (!formatterInit)
{
formatterInit = true
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
formatter.locale = NSLocale.init(localeIdentifier: "en_US_POSIX")
}
var jsonObject = json["\(dictionaryKeys.symbol)"]
if let symbol = jsonObject as? String
{
self.symbol = symbol
}
jsonObject = json["\(dictionaryKeys.venue)"]
if let venue = jsonObject as? String
{
self.venue = venue
}
jsonObject = json["\(dictionaryKeys.bid)"]
if let bid = jsonObject as? Int
{
self.bid = bid
}
jsonObject = json["\(dictionaryKeys.ask)"]
if let ask = jsonObject as? Int
{
self.ask = ask
}
jsonObject = json["\(dictionaryKeys.bidSize)"]
if let bidSize = jsonObject as? Int
{
self.bidSize = bidSize
}
jsonObject = json["\(dictionaryKeys.askSize)"]
if let askSize = jsonObject as? Int
{
self.askSize = askSize
}
jsonObject = json["\(dictionaryKeys.bidDepth)"]
if let bidDepth = jsonObject as? Int
{
self.bidDepth = bidDepth
}
jsonObject = json["\(dictionaryKeys.askDepth)"]
if let askDepth = jsonObject as? Int
{
self.askDepth = askDepth
}
jsonObject = json["\(dictionaryKeys.last)"]
if let lastPrice = jsonObject as? Int
{
self.lastPrice = lastPrice
}
jsonObject = json["\(dictionaryKeys.lastSize)"]
if let lastSize = jsonObject as? Int
{
self.lastSize = lastSize
}
jsonObject = json["\(dictionaryKeys.lastTrade)"]
if let lastTrade = jsonObject as? String
{
self.lastTrade = lastTrade
}
jsonObject = json["\(dictionaryKeys.quoteTime)"]
if let quoteTime = jsonObject as? String
{
self.quoteTime = formatter.dateFromString(quoteTime)
}
}
}
| bsd-2-clause | 70f8b6552aeab8a9203ff081a6b2587e | 23.807018 | 77 | 0.51662 | 4.705491 | false | false | false | false |
strike65/SwiftyStats | SwiftyStats/Experimental Sources/Pearson.swift | 1 | 4822 | //
// Created by VT on 17.09.18.
// Copyright © 2018 strike65. All rights reserved.
//
/*
Copyright (2017-2019) strike65
GNU GPL 3+
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, version 3 of the License.
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 Foundation
extension SSSpecialFunctions {
// see : https://people.maths.ox.ac.uk/porterm/research/pearson_final.pdf
internal static func h1f1taylora<T: SSComplexFloatElement>(_ a: Complex<T>, _ b: Complex<T>, _ x: Complex<T>, _ tol: T) -> (h: Complex<T>, mIter: Bool) {
var a1: Array<Complex<T>> = Array<Complex<T>>.init()
var sum: Complex<T> = Complex<T>.init(re: 1, im: 0)
a1.append(Complex<T>.init(re: 1, im: 0))
var e1, e2, e3, e4, e5: Complex<T>
var jf: Complex<T>
var maxIter: Bool = false
for j in stride(from: 1, through: 500, by: 1) {
jf = Complex<T>.init(re: Helpers.makeFP(j), im: 0)
e1 = (a &++ jf &-- 1)
e2 = (b &++ jf &-- 1)
e3 = e1 &% e2
e4 = x &% jf &** a1[j - 1]
e5 = e3 &** e4
a1.append(e5)
sum = sum &++ a1[j]
if ((a1[j - 1].abs / sum.abs) < tol && (a1[j].abs / sum.abs < tol)) {
break
}
if j == 500 {
maxIter = true
}
}
return (h: sum, mIter: maxIter)
}
internal static func h1f1taylorb<T: SSComplexFloatElement>(_ a: Complex<T>, _ b: Complex<T>, _ x: Complex<T>, _ tol: T) -> (h: Complex<T>, mIter: Bool) {
var r: Array<Complex<T>> = Array<Complex<T>>.init()
r.append(a &% b)
r.append((a &++ 1) &% 2 &% (b &++ 1))
var A: Array<Complex<T>> = Array<Complex<T>>.init()
A.append(1 &++ x &** r[0])
A.append(A[0] &++ pow(x, 2) &** a &% b &** r[1])
var jf: Complex<T>
var e1, e2, e3: Complex<T>
var maxIter: Bool = false
for j in stride(from: 3, through: 500, by: 1) {
jf = Complex<T>.init(re: Helpers.makeFP(j), im: 0)
e1 = (a &++ jf &-- 1) &% jf
e2 = (b &++ jf &-- 1)
e3 = e1 &% e2
r.append(e3)
e1 = A[j - 2] &++ (A[j - 2] &-- A[j - 3]) &** r[j - 2] &** x
A.append(e1)
if (((A[j - 1] &-- A[j - 2]).abs / A[j - 2].abs) < tol) && ((A[j - 2] &-- A[j - 3]).abs / A[j - 3].abs < tol) {
break
}
if j == 500 {
maxIter = true
}
}
return (h: A.last!, mIter: maxIter)
}
internal static func h1f1singleFraction<T: SSComplexFloatElement>(a: Complex<T>, b: Complex<T>, z: Complex<T>, tol: T) -> (h: Complex<T>, maxiter: Bool) {
var A1: Array<Complex<T>> = Array<Complex<T>>.init()
var B1: Array<Complex<T>> = Array<Complex<T>>.init()
var C1: Array<Complex<T>> = Array<Complex<T>>.init()
var D1: Array<Complex<T>> = Array<Complex<T>>.init()
var maxiter: Bool = false
A1.append(Complex<T>.zero)
A1.append(b)
B1.append(Complex<T>.init(re: 1, im: 0))
B1.append(a &** z)
C1.append(Complex<T>.init(re: 1, im: 0))
C1.append(b)
D1.append(Complex<T>.init(re: 1, im: 0))
D1.append((b &++ a &** z) &% b)
var jf: Complex<T>
var ex1: Complex<T>
var ex2: Complex<T>
var ex3: Complex<T>
var ex4: Complex<T>
for j in stride(from: 3, through: 500, by: 1) {
jf = Complex<T>.init(re: Helpers.makeFP(j), im: 0)
ex1 = A1[j - 2] &++ B1[j - 2]
ex2 = jf &-- 1
ex3 = b &++ jf &-- 2
ex4 = ex1 &** ex2
A1[j - 1] = ex4 &** ex3
B1[j - 1] = B1[j - 2] &** (a &++ jf &-- 2) &** z
C1[j - 1] = C1[j - 2] &** (jf &-- 1) &** (b &++ jf &-- 2)
if A1[j - 1].isInfinite || B1[j - 1].isInfinite || C1[j - 1].isInfinite {
break
}
D1[j - 1] = (A1[j - 1] &++ B1[j - 1] &% C1[j - 1])
if (((D1[j - 1] &-- D1[j - 2]).abs / D1[j - 2].abs) < tol) && (((D1[j - 2] &-- D1[j - 3]).abs / D1[j - 3].abs) < tol) {
break
}
if j == 500 {
maxiter = true
}
}
return (h: D1.last!, maxiter: maxiter)
}
}
| gpl-3.0 | f49aa602768a40ef0ed31208e6e43dc6 | 38.516393 | 158 | 0.479154 | 3.028266 | false | false | false | false |
drmohundro/SWXMLHash | Tests/SWXMLHashTests/TypeConversionPrimitiveTypesTests.swift | 1 | 10610 | //
// TypeConversionPrimitiveTypesTests.swift
// SWXMLHash
//
// Copyright (c) 2016 David Mohundro
//
// 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 SWXMLHash
import XCTest
// swiftlint:disable line_length
class TypeConversionPrimitiveTypesTests: XCTestCase {
var parser: XMLIndexer?
let xmlWithArraysOfTypes = """
<root>
<arrayOfGoodInts>
<int>0</int> <int>1</int> <int>2</int> <int>3</int>
</arrayOfGoodInts>
<arrayOfBadInts>
<int></int> <int>boom</int>
</arrayOfBadInts>
<arrayOfMixedInts>
<int>0</int> <int>boom</int> <int>2</int> <int>3</int>
</arrayOfMixedInts>
<arrayOfAttributeInts>
<int value=\"0\"/> <int value=\"1\"/> <int value=\"2\"/> <int value=\"3\"/>
</arrayOfAttributeInts>
<empty></empty>
</root>
"""
override func setUp() {
super.setUp()
parser = XMLHash.parse(xmlWithArraysOfTypes)
}
func testShouldConvertArrayOfGoodIntsToNonOptional() {
do {
let value: [Int] = try parser!["root"]["arrayOfGoodInts"]["int"].value()
XCTAssertEqual(value, [0, 1, 2, 3])
} catch {
XCTFail("\(error)")
}
}
func testShouldConvertArrayOfGoodIntsToOptional() {
do {
let value: [Int]? = try parser!["root"]["arrayOfGoodInts"]["int"].value()
XCTAssertNotNil(value)
if let value = value {
XCTAssertEqual(value, [0, 1, 2, 3])
}
} catch {
XCTFail("\(error)")
}
}
func testShouldConvertArrayOfGoodIntsToArrayOfOptionals() {
do {
let value: [Int?] = try parser!["root"]["arrayOfGoodInts"]["int"].value()
XCTAssertEqual(value.compactMap({ $0 }), [0, 1, 2, 3])
} catch {
XCTFail("\(error)")
}
}
func testShouldThrowWhenConvertingArrayOfBadIntsToNonOptional() {
XCTAssertThrowsError(try (parser!["root"]["arrayOfBadInts"]["int"].value() as [Int])) { error in
guard error is XMLDeserializationError else {
XCTFail("Wrong type of error")
return
}
}
}
func testShouldThrowWhenConvertingArrayOfBadIntsToOptional() {
XCTAssertThrowsError(try (parser!["root"]["arrayOfBadInts"]["int"].value() as [Int]?)) { error in
guard error is XMLDeserializationError else {
XCTFail("Wrong type of error")
return
}
}
}
func testShouldThrowWhenConvertingArrayOfBadIntsToArrayOfOptionals() {
XCTAssertThrowsError(try (parser!["root"]["arrayOfBadInts"]["int"].value() as [Int?])) { error in
guard error is XMLDeserializationError else {
XCTFail("Wrong type of error")
return
}
}
}
func testShouldThrowWhenConvertingArrayOfMixedIntsToNonOptional() {
XCTAssertThrowsError(try (parser!["root"]["arrayOfMixedInts"]["int"].value() as [Int])) { error in
guard error is XMLDeserializationError else {
XCTFail("Wrong type of error")
return
}
}
}
func testShouldThrowWhenConvertingArrayOfMixedIntsToOptional() {
XCTAssertThrowsError(try (parser!["root"]["arrayOfMixedInts"]["int"].value() as [Int]?)) { error in
guard error is XMLDeserializationError else {
XCTFail("Wrong type of error")
return
}
}
}
func testShouldThrowWhenConvertingArrayOfMixedIntsToArrayOfOptionals() {
XCTAssertThrowsError(try (parser!["root"]["arrayOfMixedInts"]["int"].value() as [Int?])) { error in
guard error is XMLDeserializationError else {
XCTFail("Wrong type of error")
return
}
}
}
func testShouldConvertArrayOfAttributeIntsToNonOptional() {
do {
let value: [Int] = try parser!["root"]["arrayOfAttributeInts"]["int"].value(ofAttribute: "value")
XCTAssertEqual(value, [0, 1, 2, 3])
} catch {
XCTFail("\(error)")
}
}
func testShouldConvertArrayOfAttributeIntsToOptional() {
do {
let value: [Int]? = try parser!["root"]["arrayOfAttributeInts"]["int"].value(ofAttribute: "value")
XCTAssertNotNil(value)
if let value = value {
XCTAssertEqual(value, [0, 1, 2, 3])
}
} catch {
XCTFail("\(error)")
}
}
func testShouldConvertArrayOfAttributeIntsToArrayOfOptionals() {
do {
let value: [Int?] = try parser!["root"]["arrayOfAttributeInts"]["int"].value(ofAttribute: "value")
XCTAssertEqual(value.compactMap({ $0 }), [0, 1, 2, 3])
} catch {
XCTFail("\(error)")
}
}
func testShouldConvertArrayOfAttributeIntsToNonOptionalWithStringRawRepresentable() {
enum Keys: String {
case value
}
do {
let value: [Int] = try parser!["root"]["arrayOfAttributeInts"]["int"].value(ofAttribute: Keys.value)
XCTAssertEqual(value, [0, 1, 2, 3])
} catch {
XCTFail("\(error)")
}
}
func testShouldConvertArrayOfAttributeIntsToOptionalWithStringRawRepresentable() {
enum Keys: String {
case value
}
do {
let value: [Int]? = try parser!["root"]["arrayOfAttributeInts"]["int"].value(ofAttribute: Keys.value)
XCTAssertNotNil(value)
if let value = value {
XCTAssertEqual(value, [0, 1, 2, 3])
}
} catch {
XCTFail("\(error)")
}
}
func testShouldConvertArrayOfAttributeIntsToArrayOfOptionalsWithStringRawRepresentable() {
enum Keys: String {
case value
}
do {
let value: [Int?] = try parser!["root"]["arrayOfAttributeInts"]["int"].value(ofAttribute: Keys.value)
XCTAssertEqual(value.compactMap({ $0 }), [0, 1, 2, 3])
} catch {
XCTFail("\(error)")
}
}
func testShouldConvertEmptyArrayOfIntsToNonOptional() {
do {
let value: [Int] = try parser!["root"]["empty"]["int"].value()
XCTAssertEqual(value, [])
} catch {
XCTFail("\(error)")
}
}
func testShouldConvertEmptyArrayOfIntsToOptional() {
do {
let value: [Int]? = try parser!["root"]["empty"]["int"].value()
XCTAssertNil(value)
} catch {
XCTFail("\(error)")
}
}
func testShouldConvertEmptyArrayOfIntsToArrayOfOptionals() {
do {
let value: [Int?] = try parser!["root"]["empty"]["int"].value()
XCTAssertEqual(value.count, 0)
} catch {
XCTFail("\(error)")
}
}
}
extension TypeConversionPrimitiveTypesTests {
static var allTests: [(String, (TypeConversionPrimitiveTypesTests) -> () throws -> Void)] {
[
("testShouldConvertArrayOfGoodIntsToNonOptional", testShouldConvertArrayOfGoodIntsToNonOptional),
("testShouldConvertArrayOfGoodIntsToOptional", testShouldConvertArrayOfGoodIntsToOptional),
("testShouldConvertArrayOfGoodIntsToArrayOfOptionals", testShouldConvertArrayOfGoodIntsToArrayOfOptionals),
("testShouldThrowWhenConvertingArrayOfBadIntsToNonOptional", testShouldThrowWhenConvertingArrayOfBadIntsToNonOptional),
("testShouldThrowWhenConvertingArrayOfBadIntsToOptional", testShouldThrowWhenConvertingArrayOfBadIntsToOptional),
("testShouldThrowWhenConvertingArrayOfBadIntsToArrayOfOptionals", testShouldThrowWhenConvertingArrayOfBadIntsToArrayOfOptionals),
("testShouldThrowWhenConvertingArrayOfMixedIntsToNonOptional", testShouldThrowWhenConvertingArrayOfMixedIntsToNonOptional),
("testShouldThrowWhenConvertingArrayOfMixedIntsToOptional", testShouldThrowWhenConvertingArrayOfMixedIntsToOptional),
("testShouldThrowWhenConvertingArrayOfMixedIntsToArrayOfOptionals", testShouldThrowWhenConvertingArrayOfMixedIntsToArrayOfOptionals),
("testShouldConvertArrayOfAttributeIntsToNonOptional", testShouldConvertArrayOfAttributeIntsToNonOptional),
("testShouldConvertArrayOfAttributeIntsToOptional", testShouldConvertArrayOfAttributeIntsToOptional),
("testShouldConvertArrayOfAttributeIntsToArrayOfOptionals", testShouldConvertArrayOfAttributeIntsToArrayOfOptionals),
("testShouldConvertArrayOfAttributeIntsToNonOptionalWithStringRawRepresentable", testShouldConvertArrayOfAttributeIntsToNonOptionalWithStringRawRepresentable),
("testShouldConvertArrayOfAttributeIntsToOptionalWithStringRawRepresentable", testShouldConvertArrayOfAttributeIntsToOptionalWithStringRawRepresentable),
("testShouldConvertArrayOfAttributeIntsToArrayOfOptionalsWithStringRawRepresentable", testShouldConvertArrayOfAttributeIntsToArrayOfOptionalsWithStringRawRepresentable),
("testShouldConvertEmptyArrayOfIntsToNonOptional", testShouldConvertEmptyArrayOfIntsToNonOptional),
("testShouldConvertEmptyArrayOfIntsToOptional", testShouldConvertEmptyArrayOfIntsToOptional),
("testShouldConvertEmptyArrayOfIntsToArrayOfOptionals", testShouldConvertEmptyArrayOfIntsToArrayOfOptionals)
]
}
}
| mit | d15c222f709dd5824609bec1edc92932 | 39.807692 | 181 | 0.636475 | 5.221457 | false | true | false | false |
wolf81/Nimbl3Survey | Nimbl3Survey/SurveyInfoView.swift | 1 | 2445 | //
// SurveyInfoView.swift
// Nimbl3Survey
//
// Created by Wolfgang Schreurs on 22/03/2017.
// Copyright © 2017 Wolftrail. All rights reserved.
//
import UIKit
import AlamofireImage
protocol SurveyInfoViewDelegate: class {
func surveyInfoViewSurveyAction(_ surveyInfoView: SurveyInfoView)
}
class SurveyInfoView: UIView, InterfaceBuilderInstantiable {
weak var delegate: SurveyInfoViewDelegate?
@IBOutlet weak var titleLabel: UILabel?
@IBOutlet weak var descriptionLabel: UILabel?
@IBOutlet weak var surveyButton: UIButton?
@IBOutlet weak var imageView: UIImageView?
@IBOutlet weak var overlayView: UIView?
private(set) var survey: Survey? {
didSet {
self.titleLabel?.text = self.survey?.title
self.descriptionLabel?.text = self.survey?.description
if let imageUrl = self.survey?.imageUrl {
self.imageView?.af_setImage(withURL: imageUrl, placeholderImage: nil, filter: nil, progress: nil, progressQueue: DispatchQueue.main, imageTransition: .crossDissolve(0.5), runImageTransitionIfCached: true, completion: { response in
})
} else {
self.imageView?.image = nil
}
}
}
// MARK: - Initialization
override func awakeFromNib() {
super.awakeFromNib()
if let surveyButton = self.surveyButton {
let bgImage = UIImage.from(color: UIColor.red)
surveyButton.setBackgroundImage(bgImage, for: .normal)
let cornerRadius: CGFloat = surveyButton.frame.height / 2
self.surveyButton?.layer.cornerRadius = cornerRadius
self.surveyButton?.layer.masksToBounds = true
}
}
// MARK: - Public
@IBAction func surveyAction() {
self.delegate?.surveyInfoViewSurveyAction(self)
}
func updateWithSurvey(_ survey: Survey) {
self.survey = survey
applyTheme(survey.theme)
}
// MARK: - Private
private func applyTheme(_ theme: Theme) {
let bgImage = UIImage.from(color: theme.activeColor)
surveyButton?.setBackgroundImage(bgImage, for: .normal)
surveyButton?.setTitleColor(theme.questionColor, for: .normal)
self.descriptionLabel?.textColor = theme.questionColor
self.titleLabel?.textColor = theme.questionColor
}
}
| bsd-2-clause | 6b1977cb8250e931b2cceda67faf92e2 | 31.157895 | 246 | 0.638707 | 4.878244 | false | false | false | false |
camdenfullmer/UnsplashSwift | Source/Serializers.swift | 1 | 18002 | // Serializers.swift
//
// Copyright (c) 2016 Camden Fullmer (http://camdenfullmer.com/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import UIKit
import CoreGraphics
// TODO: Create struct to hold single instance for all serializers.
public enum JSON {
case Array([JSON])
case Dictionary([String: JSON])
case Str(String)
case Number(NSNumber)
case Null
}
public protocol JSONSerializer {
typealias ValueType
func deserialize(_: JSON) -> ValueType
}
public extension JSONSerializer {
func deserialize(json: JSON?) -> ValueType? {
if let j = json {
switch j {
case .Null:
return nil
default:
return deserialize(j)
}
}
return nil
}
}
func objectToJSON(json : AnyObject) -> JSON {
switch json {
case _ as NSNull:
return .Null
case let num as NSNumber:
return .Number(num)
case let str as String:
return .Str(str)
case let dict as [String : AnyObject]:
var ret = [String : JSON]()
for (k, v) in dict {
ret[k] = objectToJSON(v)
}
return .Dictionary(ret)
case let array as [AnyObject]:
return .Array(array.map(objectToJSON))
default:
fatalError("Unknown type trying to parse JSON.")
}
}
func parseJSON(data: NSData) -> JSON {
let obj: AnyObject = try! NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments)
return objectToJSON(obj)
}
// MARK: - Common Serializers
public class ArraySerializer<T : JSONSerializer> : JSONSerializer {
var elementSerializer : T
init(_ elementSerializer: T) {
self.elementSerializer = elementSerializer
}
public func deserialize(json : JSON) -> Array<T.ValueType> {
switch json {
case .Array(let arr):
return arr.map { self.elementSerializer.deserialize($0) }
default:
fatalError("Type error deserializing")
}
}
}
public class UInt32Serializer : JSONSerializer {
public func deserialize(json : JSON) -> UInt32 {
switch json {
case .Number(let n):
return n.unsignedIntValue
default:
fatalError("Type error deserializing")
}
}
public func deserialize(json: JSON?) -> UInt32? {
if let j = json {
switch(j) {
case .Number(let n):
return n.unsignedIntValue
default:
break
}
}
return nil
}
}
public class BoolSerializer : JSONSerializer {
public func deserialize(json : JSON) -> Bool {
switch json {
case .Number(let b):
return b.boolValue
default:
fatalError("Type error deserializing")
}
}
}
public class DoubleSerializer : JSONSerializer {
public func deserialize(json: JSON) -> Double {
switch json {
case .Number(let n):
return n.doubleValue
default:
fatalError("Type error deserializing")
}
}
public func deserialize(json: JSON?) -> Double? {
if let j = json {
switch(j) {
case .Number(let n):
return n.doubleValue
default:
break
}
}
return nil
}
}
public class StringSerializer : JSONSerializer {
public func deserialize(json: JSON) -> String {
switch (json) {
case .Str(let s):
return s
default:
fatalError("Type error deserializing")
}
}
}
// Color comes in the following format: #000000
public class UIColorSerializer : JSONSerializer {
public func deserialize(json: JSON) -> UIColor {
switch (json) {
case .Str(let s):
return UIColor.colorWithHexString(s)
default:
fatalError("Type error deserializing")
}
}
}
public class NSURLSerializer : JSONSerializer {
public func deserialize(json: JSON) -> NSURL {
switch (json) {
case .Str(let s):
return NSURL(string: s)!
default:
fatalError("Type error deserializing")
}
}
}
// Date comes in the following format: 2015-06-17T11:53:00-04:00
public class NSDateSerializer : JSONSerializer {
var dateFormatter : NSDateFormatter
init() {
self.dateFormatter = NSDateFormatter()
self.dateFormatter.timeZone = NSTimeZone(name: "UTC")
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZZZZZ"
}
public func deserialize(json: JSON) -> NSDate {
switch json {
case .Str(let s):
return self.dateFormatter.dateFromString(s)!
default:
fatalError("Type error deserializing")
}
}
}
public class DeleteResultSerializer : JSONSerializer {
init(){}
public func deserialize(json: JSON) -> Bool {
switch json {
case .Null:
return true
default:
fatalError("Type error deserializing")
}
}
}
// MARK: Model Serializers
extension User {
public class Serializer : JSONSerializer {
public init() {}
public func deserialize(json: JSON) -> User {
switch json {
case .Dictionary(let dict):
let id = StringSerializer().deserialize(dict["id"])
let username = StringSerializer().deserialize(dict["username"] ?? .Null)
let name = StringSerializer().deserialize(dict["name"])
let firstName = StringSerializer().deserialize(dict["first_name"])
let lastName = StringSerializer().deserialize(dict["last_name"])
let downloads = UInt32Serializer().deserialize(dict["downloads"])
let profilePhoto = ProfilePhotoURL.Serializer().deserialize(dict["profile_image"])
let portfolioURL = NSURLSerializer().deserialize(dict["portfolio_url"])
let bio = StringSerializer().deserialize(dict["bio"])
let uploadsRemaining = UInt32Serializer().deserialize(dict["uploads_remaining"])
let instagramUsername = StringSerializer().deserialize(dict["instagram_username"])
let location = StringSerializer().deserialize(dict["location"])
let email = StringSerializer().deserialize(dict["email"])
return User(id: id, username: username, name: name, firstName: firstName, lastName: lastName, downloads: downloads, profilePhoto: profilePhoto, portfolioURL: portfolioURL, bio: bio, uploadsRemaining: uploadsRemaining, instagramUsername: instagramUsername, location: location, email: email)
default:
fatalError("error deserializing")
}
}
public func deserialize(json: JSON?) -> User? {
if let j = json {
return deserialize(j)
}
return nil
}
}
}
extension ProfilePhotoURL {
public class Serializer : JSONSerializer {
public init() {}
public func deserialize(json: JSON) -> ProfilePhotoURL {
switch json {
case .Dictionary(let dict):
let large = NSURLSerializer().deserialize(dict["large"] ?? .Null)
let medium = NSURLSerializer().deserialize(dict["medium"] ?? .Null)
let small = NSURLSerializer().deserialize(dict["small"] ?? .Null)
let custom = NSURLSerializer().deserialize(dict["custom"])
return ProfilePhotoURL(large: large, medium: medium, small: small, custom: custom)
default:
fatalError("error deserializing")
}
}
}
}
extension CollectionsResult {
public class Serializer : JSONSerializer {
public init() {}
public func deserialize(json: JSON) -> CollectionsResult {
switch json {
case .Array:
let collections = ArraySerializer(Collection.Serializer()).deserialize(json)
return CollectionsResult(collections: collections)
default:
fatalError("error deserializing")
}
}
}
}
extension Collection {
public class Serializer : JSONSerializer {
public init() {}
public func deserialize(json: JSON) -> Collection {
switch json {
case .Dictionary(let dict):
let id = UInt32Serializer().deserialize(dict["id"] ?? .Null)
let title = StringSerializer().deserialize(dict["title"] ?? .Null)
let curated = BoolSerializer().deserialize(dict["curated"] ?? .Null)
let coverPhoto = Photo.Serializer().deserialize(dict["cover_photo"] ?? .Null)
let publishedAt = NSDateSerializer().deserialize(dict["published_at"] ?? .Null)
let user = User.Serializer().deserialize(dict["user"] ?? .Null)
return Collection(id: id, title: title, curated: curated, coverPhoto: coverPhoto, publishedAt: publishedAt, user: user)
default:
fatalError("error deserializing")
}
}
}
}
extension PhotoCollectionResult {
public class Serializer : JSONSerializer {
public init() {}
public func deserialize(json: JSON) -> PhotoCollectionResult {
switch json {
case .Dictionary(let dict):
let photo = Photo.Serializer().deserialize(dict["photo"] ?? .Null)
let collection = Collection.Serializer().deserialize(dict["collection"] ?? .Null)
return PhotoCollectionResult(photo: photo, collection: collection)
default:
fatalError("error deserializing")
}
}
}
}
extension PhotoUserResult {
public class Serializer : JSONSerializer {
public init() {}
public func deserialize(json: JSON) -> PhotoUserResult {
switch json {
case .Dictionary(let dict):
let photo = Photo.Serializer().deserialize(dict["photo"] ?? .Null)
let user = User.Serializer().deserialize(dict["user"] ?? .Null)
return PhotoUserResult(photo: photo, user: user)
default:
fatalError("error deserializing")
}
}
}
}
extension Photo {
public class Serializer : JSONSerializer {
public init() {}
public func deserialize(json: JSON) -> Photo {
switch json {
case .Dictionary(let dict):
let id = StringSerializer().deserialize(dict["id"] ?? .Null)
let width = UInt32Serializer().deserialize(dict["width"])
let height = UInt32Serializer().deserialize(dict["height"])
let color = UIColorSerializer().deserialize(dict["color"])
let user = User.Serializer().deserialize(dict["user"])
let url = PhotoURL.Serializer().deserialize(dict["urls"] ?? .Null)
let categories = ArraySerializer(Category.Serializer()).deserialize(dict["categories"])
let exif = Exif.Serializer().deserialize(dict["exif"])
let downloads = UInt32Serializer().deserialize(dict["downloads"])
let likes = UInt32Serializer().deserialize(dict["likes"])
let location = Location.Serializer().deserialize(dict["location"])
return Photo(id: id, width: width, height: height, color: color, user: user, url: url, categories: categories, exif: exif, downloads: downloads, likes: likes, location: location)
default:
fatalError("error deserializing")
}
}
}
}
extension PhotosResult {
public class Serializer : JSONSerializer {
public init() {}
public func deserialize(json: JSON) -> PhotosResult {
switch json {
case .Array:
let photos = ArraySerializer(Photo.Serializer()).deserialize(json)
return PhotosResult(photos: photos)
default:
fatalError("error deserializing")
}
}
}
}
extension PhotoURL {
public class Serializer : JSONSerializer {
public init() {}
public func deserialize(json: JSON) -> PhotoURL {
switch json {
case .Dictionary(let dict):
let full = NSURLSerializer().deserialize(dict["full"] ?? .Null)
let regular = NSURLSerializer().deserialize(dict["regular"] ?? .Null)
let small = NSURLSerializer().deserialize(dict["small"] ?? .Null)
let thumb = NSURLSerializer().deserialize(dict["thumb"] ?? .Null)
let custom = NSURLSerializer().deserialize(dict["custom"])
return PhotoURL(full: full, regular: regular, small: small, thumb: thumb, custom: custom)
default:
fatalError("error deserializing")
}
}
}
}
extension Exif {
public class Serializer : JSONSerializer {
public init() {}
public func deserialize(json: JSON) -> Exif {
switch json {
case .Dictionary(let dict):
let make = StringSerializer().deserialize(dict["make"])
let model = StringSerializer().deserialize(dict["model"])
let exposureTime = DoubleSerializer().deserialize(dict["exposure_time"])
let aperture = DoubleSerializer().deserialize(dict["aperture"])
let focalLength = UInt32Serializer().deserialize(dict["focal_length"])
let iso = UInt32Serializer().deserialize(dict["iso"])
return Exif(make: make, model: model, exposureTime: exposureTime, aperture: aperture, focalLength: focalLength, iso: iso)
default:
fatalError("error deserializing")
}
}
}
}
extension Location {
public class Serializer : JSONSerializer {
public init() {}
public func deserialize(json: JSON) -> Location {
switch json {
case .Dictionary(let dict):
let position = Position.Serializer().deserialize(dict["position"] ?? .Null)
let city = StringSerializer().deserialize(dict["city"] ?? .Null)
let country = StringSerializer().deserialize(dict["country"] ?? .Null)
return Location(city: city, country: country, position: position)
default:
fatalError("error deserializing")
}
}
}
}
extension Position {
public class Serializer : JSONSerializer {
public init() {}
public func deserialize(json: JSON) -> Position {
switch json {
case .Dictionary(let dict):
let latitude = DoubleSerializer().deserialize(dict["latitude"] ?? .Null)
let longitude = DoubleSerializer().deserialize(dict["longitude"] ?? .Null)
return Position(latitude: latitude, longitude: longitude)
default:
fatalError("error deserializing")
}
}
}
}
extension CategoriesResult {
public class Serializer : JSONSerializer {
public init() {}
public func deserialize(json: JSON) -> CategoriesResult {
switch json {
case .Array:
let categories = ArraySerializer(Category.Serializer()).deserialize(json)
return CategoriesResult(categories: categories)
default:
fatalError("error deserializing")
}
}
}
}
extension Category {
public class Serializer : JSONSerializer {
public init() {}
public func deserialize(json: JSON) -> Category {
switch json {
case .Dictionary(let dict):
let id = UInt32Serializer().deserialize(dict["id"] ?? .Null)
let title = StringSerializer().deserialize(dict["title"] ?? .Null)
let photoCount = UInt32Serializer().deserialize(dict["photo_count"] ?? .Null)
return Category(id: id, title: title, photoCount: photoCount)
default:
fatalError("error deserializing")
}
}
}
}
extension Stats {
public class Serializer : JSONSerializer {
public init() {}
public func deserialize(json: JSON) -> Stats {
switch json {
case .Dictionary(let dict):
let photoDownloads = UInt32Serializer().deserialize(dict["photo_downloads"] ?? .Null)
let batchDownloads = UInt32Serializer().deserialize(dict["batch_downloads"] ?? .Null)
return Stats(photoDownloads: photoDownloads, batchDownloads: batchDownloads)
default:
fatalError("error deserializing")
}
}
}
}
| mit | 69137eb3f21e4442e31ce813a80eecf2 | 36.582463 | 305 | 0.589601 | 5.070986 | false | false | false | false |
wordpress-mobile/WordPress-iOS | WordPress/Classes/ViewRelated/System/Floating Create Button/UIView+SpringAnimations.swift | 2 | 2542 | extension FloatingActionButton {
private enum Constants {
enum Maximize {
static let damping: CGFloat = 0.7
static let duration: TimeInterval = 0.5
static let initialScale: CGFloat = 0.0
static let finalScale: CGFloat = 1.0
}
enum Minimize {
static let damping: CGFloat = 0.9
static let duration: TimeInterval = 0.25
static let initialScale: CGFloat = 1.0
static let finalScale: CGFloat = 0.001
}
}
/// Animates the showing and hiding of a view using a spring animation
/// - Parameter toShow: Whether to show the view
func springAnimation(toShow: Bool) {
if toShow {
guard isHidden == true else { return }
maximizeSpringAnimation()
} else {
guard isHidden == false else { return }
minimizeSpringAnimation()
}
}
/// Applies a spring animation, from size 1 to 0
func minimizeSpringAnimation() {
let damping = Constants.Minimize.damping
let scaleInitial = Constants.Minimize.initialScale
let scaleFinal = Constants.Minimize.finalScale
let duration = Constants.Minimize.duration
scaleAnimation(duration: duration, damping: damping, scaleInitial: scaleInitial, scaleFinal: scaleFinal) { [weak self] success in
self?.transform = .identity
self?.isHidden = true
}
}
/// Applies a spring animation, from size 0 to 1
func maximizeSpringAnimation() {
let damping = Constants.Maximize.damping
let scaleInitial = Constants.Maximize.initialScale
let scaleFinal = Constants.Maximize.finalScale
let duration = Constants.Maximize.duration
scaleAnimation(duration: duration, damping: damping, scaleInitial: scaleInitial, scaleFinal: scaleFinal)
}
func scaleAnimation(duration: TimeInterval, damping: CGFloat, scaleInitial: CGFloat, scaleFinal: CGFloat, completion: ((Bool) -> Void)? = nil) {
setNeedsDisplay() // Make sure we redraw so that corners are rounded
transform = CGAffineTransform(scaleX: scaleInitial, y: scaleInitial)
isHidden = false
let animator = UIViewPropertyAnimator(duration: duration, dampingRatio: damping) {
self.transform = CGAffineTransform(scaleX: scaleFinal, y: scaleFinal)
}
animator.addCompletion { (position) in
completion?(true)
}
animator.startAnimation()
}
}
| gpl-2.0 | ab71db826bf4a29b39e358c68dd236c1 | 36.382353 | 148 | 0.638474 | 5.177189 | false | false | false | false |
the-blue-alliance/the-blue-alliance-ios | Frameworks/MyTBAKit/Sources/Models/MyTBAPreferences.swift | 1 | 2039 | import Foundation
public struct MyTBAPreferences: Codable {
var deviceKey: String?
var favorite: Bool
var modelKey: String
var modelType: MyTBAModelType
var notifications: [NotificationType]
}
public struct MyTBAPreferencesMessageResponse: Codable {
let favorite: MyTBABaseResponse
let subscription: MyTBABaseResponse
}
extension MyTBA {
// TODO: Android has some local rate limiting, which is probably smart
// https://github.com/the-blue-alliance/the-blue-alliance-ios/issues/174
public func updatePreferences(modelKey: String, modelType: MyTBAModelType, favorite: Bool, notifications: [NotificationType], completion: @escaping (_ favoriteResponse: MyTBABaseResponse?, _ subscriptionResponse: MyTBABaseResponse?, _ error: Error?) -> Void) -> MyTBAOperation? {
let preferences = MyTBAPreferences(deviceKey: fcmToken,
favorite: favorite,
modelKey: modelKey,
modelType: modelType,
notifications: notifications)
guard let encodedPreferences = try? MyTBA.jsonEncoder.encode(preferences) else {
return nil
}
let method = "model/setPreferences"
return callApi(method: method, bodyData: encodedPreferences, completion: { (preferencesResponse: MyTBABaseResponse?, error: Error?) in
if let preferencesResponse = preferencesResponse, let data = preferencesResponse.message.data(using: .utf8) {
guard let messageResponse = try? JSONDecoder().decode(MyTBAPreferencesMessageResponse.self, from: data) else {
completion(nil, nil, MyTBAError.error(nil, "Error decoding myTBA preferences response"))
return
}
completion(messageResponse.favorite, messageResponse.subscription, error)
} else {
completion(nil, nil, error)
}
})
}
}
| mit | 266a923eb02949889dfecfd392157798 | 42.382979 | 283 | 0.635606 | 5.422872 | false | false | false | false |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.