repo_name
stringlengths 7
91
| path
stringlengths 8
658
| copies
stringclasses 125
values | size
stringlengths 3
6
| content
stringlengths 118
674k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6.09
99.2
| line_max
int64 17
995
| alpha_frac
float64 0.3
0.9
| ratio
float64 2
9.18
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
rene-dohan/CS-IOS | Renetik/Renetik/Classes/AlamofireCached/Session+CSAlamofireCache.swift | 1 | 1213 | ////
//// Created by Rene Dohan on 1/1/20.
//// Copyright (c) 2020 Renetik. All rights reserved.
////
//
//import Foundation
//import CoreFoundation
//import Alamofire
//import RenetikObjc
//import Renetik
//
//public extension Session {
//
// @discardableResult
// func request(url: URLConvertible, method: HTTPMethod = .get, parameters: Parameters? = nil,
// encoding: ParameterEncoding = URLEncoding.default, headers: HTTPHeaders? = nil,
// refreshCache: Bool = false) -> DataRequest {
// let headers = (method == .get && refreshCache) ? addCacheControl(to: headers) : headers
// return request(url, method: method, parameters: parameters,
// encoding: encoding, headers: headers, interceptor: nil)
// }
//
// private func addCacheControl(to headers: HTTPHeaders?) -> HTTPHeaders {
// var newHeaders = headers.notNil ? headers! : HTTPHeaders()
// CSAlamofireCache.canUseCacheControl ? (newHeaders["Cache-Control"] = "no-cache")
// : (newHeaders["Pragma"] = "no-cache")
// newHeaders[CSAlamofireCache.refreshCacheKey] = CSAlamofireCache.refreshCacheValueRefresh
// return newHeaders
// }
//}
| mit | 8a7fe51a1ea433b717fbd15eeb54fefc | 39.433333 | 98 | 0.64798 | 4.097973 | false | false | false | false |
marko1503/Algorithms-and-Data-Structures-Swift | Sort/Insertion Sort/InsertionSort.playground/Pages/Version_3.xcplaygroundpage/Contents.swift | 1 | 1432 | //: [Previous](@previous)
import Foundation
func insertionSort<Element>(array: [Element], sortDirection: (Element, Element) -> Bool) -> [Element] where Element: Comparable {
// check for tirivial case
// we have only 1 element in array
guard array.count > 1 else { return array }
var output: [Element] = array
for primaryIndex in 1..<output.count {
let primaryElement = output[primaryIndex]
var tempIndex = primaryIndex - 1
while tempIndex > -1 && sortDirection(primaryElement, output[tempIndex]) {
// primaryElement and element at tempIndex are not ordered. We need to change them
// Then, remove primary element
// tempIndex + 1 - primaryElement always after tempIndex
output.remove(at: tempIndex + 1)
// and insert primary element before tempElement
output.insert(primaryElement, at: tempIndex)
tempIndex -= 1
}
}
return output
}
//let array = [Int]()
//insertionSort(array: array)
//let array = [5]
//insertionSort(array: array)
//let array = [5, 8]
//insertionSort(array: array)
//let array = [8, 5]
//insertionSort(array: array)
//let array = [1, 2, 3, 4, 5, 6, 7, 8]
//insertionSort(array: array)
//let array = [8, 7, 6, 5, 4, 3, 2, 1]
//insertionSort(array: array)
let array = [7, 2, 1, 6, 8, 5, 3, 4]
insertionSort(array: array, sortDirection: <)
//: [Next](@next)
| apache-2.0 | 6e34b0cff679c375181173f49aba1852 | 27.078431 | 129 | 0.627095 | 3.671795 | false | false | false | false |
gregomni/swift | test/Interop/Cxx/class/inheritance/sub-types-module-interface.swift | 8 | 1785 | // RUN: %target-swift-ide-test -print-module -module-to-print=SubTypes -I %S/Inputs -source-filename=x -enable-experimental-cxx-interop | %FileCheck %s
// CHECK: struct Base {
// CHECK-NEXT: init()
// CHECK-NEXT: enum EnumClass : CChar {
// CHECK-NEXT: init?(rawValue: CChar)
// CHECK-NEXT: var rawValue: CChar { get }
// CHECK-NEXT: typealias RawValue = CChar
// CHECK-NEXT: case eca
// CHECK-NEXT: case ecb
// CHECK-NEXT: case ecc
// CHECK-NEXT: }
// CHECK-NEXT: struct Enum : Equatable, RawRepresentable {
// CHECK-NEXT: init(_ rawValue: {{UInt32|Int32}})
// CHECK-NEXT: init(rawValue: {{UInt32|Int32}})
// CHECK-NEXT: var rawValue: {{UInt32|Int32}}
// CHECK-NEXT: typealias RawValue = {{UInt32|Int32}}
// CHECK-NEXT: }
// CHECK-NEXT: struct Struct {
// CHECK-NEXT: init()
// CHECK-NEXT: init(sa: Int32, sb: Int32)
// CHECK-NEXT: var sa: Int32
// CHECK-NEXT: var sb: Int32
// CHECK-NEXT: }
// CHECK-NEXT: struct Parent {
// CHECK-NEXT: init()
// CHECK-NEXT: struct Child {
// CHECK-NEXT: init()
// CHECK-NEXT: init(pca: Int32)
// CHECK-NEXT: var pca: Int32
// CHECK-NEXT: }
// CHECK-NEXT: }
// CHECK-NEXT: struct Union {
// CHECK-NEXT: init()
// CHECK-NEXT: init(ua: Int32)
// CHECK-NEXT: init(ub: Base.Struct)
// CHECK-NEXT: var ua: Int32
// CHECK-NEXT: var ub: Base.Struct
// CHECK-NEXT: }
// CHECK-NEXT: }
// CHECK-NEXT: struct Derived {
// CHECK-NEXT: init()
// CHECK-NEXT: typealias EnumClass = Base.EnumClass.Type
// CHECK-NEXT: typealias Enum = Base.Enum.Type
// CHECK-NEXT: typealias Struct = Base.Struct.Type
// CHECK-NEXT: typealias Parent = Base.Parent.Type
// CHECK-NEXT: typealias Union = Base.Union.Type
// CHECK-NEXT: }
| apache-2.0 | 3dfc438f4485dc5732f8c0b6e7ba08e3 | 35.428571 | 151 | 0.617927 | 3.015203 | false | false | false | false |
wireapp/wire-ios-sync-engine | Tests/Source/MockAddressBook.swift | 1 | 4061 | //
// Wire
// Copyright (C) 2020 Wire Swiss GmbH
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
import Foundation
@testable import WireSyncEngine
/// Fake to supply predefined AB hashes
class MockAddressBook: WireSyncEngine.AddressBook, WireSyncEngine.AddressBookAccessor {
/// Find contact by Id
func contact(identifier: String) -> WireSyncEngine.ContactRecord? {
return contacts.first { $0.localIdentifier == identifier }
}
/// List of contacts in this address book
var contacts = [MockAddressBookContact]()
/// Reported number of contacts (it might be higher than `fakeContacts`
/// because some contacts are filtered for not having valid email/phone)
var numberOfAdditionalContacts: UInt = 0
var numberOfContacts: UInt {
return UInt(self.contacts.count) + numberOfAdditionalContacts
}
/// Enumerates the contacts, invoking the block for each contact.
/// If the block returns false, it will stop enumerating them.
func enumerateRawContacts(block: @escaping (WireSyncEngine.ContactRecord) -> (Bool)) {
for contact in self.contacts {
if !block(contact) {
return
}
}
let infiniteContact = MockAddressBookContact(firstName: "johnny infinite",
emailAddresses: ["[email protected]"],
phoneNumbers: [])
while createInfiniteContacts {
if !block(infiniteContact) {
return
}
}
}
func rawContacts(matchingQuery: String) -> [WireSyncEngine.ContactRecord] {
guard matchingQuery != "" else {
return contacts
}
return contacts.filter { $0.firstName.lowercased().contains(matchingQuery.lowercased()) || $0.lastName.lowercased().contains(matchingQuery.lowercased()) }
}
/// Replace the content with a given number of random hashes
func fillWithContacts(_ number: UInt) {
self.contacts = (0..<number).map {
self.createContact(card: $0)
}
}
/// Create a fake contact
func createContact(card: UInt) -> MockAddressBookContact {
return MockAddressBookContact(firstName: "tester \(card)", emailAddresses: ["tester_\(card)@example.com"], phoneNumbers: ["+155512300\(card % 10)"], identifier: "\(card)")
}
/// Generate an infinite number of contacts
var createInfiniteContacts = false
}
struct MockAddressBookContact: WireSyncEngine.ContactRecord {
static var incrementalLocalIdentifier = ZMAtomicInteger(integer: 0)
var firstName = ""
var lastName = ""
var middleName = ""
var rawEmails: [String]
var rawPhoneNumbers: [String]
var nickname = ""
var organization = ""
var localIdentifier = ""
init(firstName: String, emailAddresses: [String], phoneNumbers: [String], identifier: String? = nil) {
self.firstName = firstName
self.rawEmails = emailAddresses
self.rawPhoneNumbers = phoneNumbers
self.localIdentifier = identifier ?? {
MockAddressBookContact.incrementalLocalIdentifier.increment()
return "\(MockAddressBookContact.incrementalLocalIdentifier.rawValue)"
}()
}
var expectedHashes: [String] {
return self.rawEmails.map { $0.base64EncodedSHADigest } + self.rawPhoneNumbers.map { $0.base64EncodedSHADigest }
}
}
| gpl-3.0 | 2d87d23644d1df24f0d20f4087f4786e | 36.601852 | 179 | 0.662152 | 4.760844 | false | false | false | false |
ioscreator/ioscreator | SwiftUIAnimationTutorial/SwiftUIAnimationTutorial/SceneDelegate.swift | 1 | 2783 | //
// SceneDelegate.swift
// SwiftUIAnimationTutorial
//
// Created by Arthur Knopper on 14/10/2019.
// Copyright © 2019 Arthur Knopper. All rights reserved.
//
import UIKit
import SwiftUI
class SceneDelegate: UIResponder, UIWindowSceneDelegate {
var window: UIWindow?
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
// Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`.
// If using a storyboard, the `window` property will automatically be initialized and attached to the scene.
// This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead).
// Create the SwiftUI view that provides the window contents.
let contentView = ContentView()
// Use a UIHostingController as window root view controller.
if let windowScene = scene as? UIWindowScene {
let window = UIWindow(windowScene: windowScene)
window.rootViewController = UIHostingController(rootView: contentView)
self.window = window
window.makeKeyAndVisible()
}
}
func sceneDidDisconnect(_ scene: UIScene) {
// Called as the scene is being released by the system.
// This occurs shortly after the scene enters the background, or when its session is discarded.
// Release any resources associated with this scene that can be re-created the next time the scene connects.
// The scene may re-connect later, as its session was not neccessarily discarded (see `application:didDiscardSceneSessions` instead).
}
func sceneDidBecomeActive(_ scene: UIScene) {
// Called when the scene has moved from an inactive state to an active state.
// Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive.
}
func sceneWillResignActive(_ scene: UIScene) {
// Called when the scene will move from an active state to an inactive state.
// This may occur due to temporary interruptions (ex. an incoming phone call).
}
func sceneWillEnterForeground(_ scene: UIScene) {
// Called as the scene transitions from the background to the foreground.
// Use this method to undo the changes made on entering the background.
}
func sceneDidEnterBackground(_ scene: UIScene) {
// Called as the scene transitions from the foreground to the background.
// Use this method to save data, release shared resources, and store enough scene-specific state information
// to restore the scene back to its current state.
}
}
| mit | bd3a031b8755d227d6bb85ad89926a1a | 42.46875 | 147 | 0.705967 | 5.360308 | false | false | false | false |
Erickson0806/AdaptivePhotos | AdaptivePhotosUsingUIKitTraitsandSizeClasses/AdaptiveStoryboard/AdaptiveStoryboard/RatingControl.swift | 2 | 6651 | /*
Copyright (C) 2015 Apple Inc. All Rights Reserved.
See LICENSE.txt for this sample’s licensing information
Abstract:
A control that allows viewing and editing a rating.
*/
import UIKit
class RatingControl: UIControl {
/*
NOTE: Unlike OverlayView, this control does not implement `intrinsicContentSize()`.
Instead, this control configures its auto layout constraints such that the
size of the star images that compose it can be used by the layout engine
to derive the desired content size of this control. Since UIImageView will
automatically load the correct UIImage asset for the current trait collection,
we receive automatic adaptivity support for free just by including the images
for both the compact and regular size classes.
*/
static let minimumRating = 0
static let maximumRating = 4
var rating = RatingControl.minimumRating {
didSet {
updateImageViews()
}
}
private let backgroundView = UIVisualEffectView(effect: UIBlurEffect(style: .Light))
private var imageViews = [UIImageView]()
// This initializer will be called if the control is created programatically.
override init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
// This initializer will be called if the control is loaded from a storyboard.
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
// Initialization code common to instances created programmatically as well as instances unarchived from a storyboard.
private func commonInit() {
backgroundView.contentView.backgroundColor = UIColor(white: 0.7, alpha: 0.3)
addSubview(backgroundView)
// Create image views for each of the sections that make up the control.
for rating in RatingControl.minimumRating...RatingControl.maximumRating {
let imageView = UIImageView()
imageView.userInteractionEnabled = true
// Set up our image view's images.
imageView.image = UIImage(named: "ratingInactive")
imageView.highlightedImage = UIImage(named: "ratingActive")
let localizedStringFormat = NSLocalizedString("%d stars", comment: "X stars")
imageView.accessibilityLabel = String.localizedStringWithFormat(localizedStringFormat, rating + 1)
addSubview(imageView)
imageViews.append(imageView)
}
// Setup constraints.
var newConstraints = [NSLayoutConstraint]()
backgroundView.translatesAutoresizingMaskIntoConstraints = false
let views = ["backgroundView": backgroundView]
// Keep our background matching our size
newConstraints += NSLayoutConstraint.constraintsWithVisualFormat("|[backgroundView]|", options: [], metrics: nil, views: views)
newConstraints += NSLayoutConstraint.constraintsWithVisualFormat("V:|[backgroundView]|", options: [], metrics: nil, views: views)
// Place the individual image views side-by-side with margins
var lastImageView: UIImageView?
for imageView in imageViews {
imageView.translatesAutoresizingMaskIntoConstraints = false
let currentImageViews: [String: AnyObject]
if lastImageView != nil {
currentImageViews = [
"lastImageView": lastImageView!,
"imageView": imageView
]
}
else {
currentImageViews = ["imageView": imageView]
}
newConstraints += NSLayoutConstraint.constraintsWithVisualFormat("V:|-4-[imageView]-4-|", options: [], metrics: nil, views: currentImageViews)
newConstraints += [
NSLayoutConstraint(item: imageView, attribute: .Width, relatedBy: .Equal, toItem: imageView, attribute: .Height, multiplier: 1, constant: 0)
]
if lastImageView != nil {
newConstraints += NSLayoutConstraint.constraintsWithVisualFormat("[lastImageView][imageView(==lastImageView)]", options: [], metrics: nil, views: currentImageViews)
}
else {
newConstraints += NSLayoutConstraint.constraintsWithVisualFormat("|-4-[imageView]", options: [], metrics: nil, views: currentImageViews)
}
lastImageView = imageView
}
let currentImageViews = ["lastImageView": lastImageView!]
newConstraints += NSLayoutConstraint.constraintsWithVisualFormat("[lastImageView]-4-|", options: [], metrics: nil, views: currentImageViews)
NSLayoutConstraint.activateConstraints(newConstraints)
}
func updateImageViews() {
for (index, imageView) in imageViews.enumerate() {
imageView.highlighted = index + RatingControl.minimumRating <= rating
}
}
// MARK: Touches
func updateRatingWithTouches(touches: Set<UITouch>, event: UIEvent?) {
guard let touch = touches.first else { return }
let position = touch.locationInView(self)
guard let touchedView = hitTest(position, withEvent: event) as? UIImageView else { return }
guard let touchedIndex = imageViews.indexOf(touchedView) else { return }
rating = RatingControl.minimumRating + touchedIndex
sendActionsForControlEvents(.ValueChanged)
}
// If you override one of the touch event callbacks, you should override all of them.
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
updateRatingWithTouches(touches, event: event)
}
override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) {
updateRatingWithTouches(touches, event: event)
}
override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
// There's no need to handle `touchesCancelled(_:withEvent:)` for this control.
}
override func touchesCancelled(touches: Set<UITouch>?, withEvent event: UIEvent?) {
// There's no need to handle `touchesCancelled(_:withEvent:)` for this control.
}
// MARK: Accessibility
// This control is not an accessibility element but the individual images that compose it are.
override var isAccessibilityElement: Bool {
set { /* ignore value */ }
get { return false }
}
}
| apache-2.0 | 743fdf6ab9ed20b93b874b0270323d98 | 38.814371 | 180 | 0.643555 | 5.786771 | false | false | false | false |
hejunbinlan/GRDB.swift | GRDB/Core/Blob.swift | 1 | 2901 | /// A Database Blob
public struct Blob : Equatable {
/// A pointer to the blob's contents.
var bytes: UnsafePointer<Void> {
return impl.bytes
}
/// The number of bytes in the blob.
var length: Int {
return impl.length
}
/**
Returns a Blob containing *length* bytes copied from the buffer *bytes*.
Returns nil if length is zero (SQLite can't store empty blobs).
- parameter bytes: A buffer containing blob data.
- parameter length: The number of bytes to copy from *bytes*. This value
must not exceed the length of bytes. If zero, the result is nil.
*/
public init?(bytes: UnsafePointer<Void>, length: Int) {
guard length > 0 else {
// SQLite can't store empty blobs
return nil
}
impl = Buffer(bytes: bytes, length: length)
}
/// The Blob implementation
let impl: BlobImpl
/// A Blob Implementation that owns a buffer.
private class Buffer: BlobImpl {
let bytes: UnsafePointer<Void>
let length: Int
init(bytes: UnsafePointer<Void>, length: Int) {
// Copy memory
let copy = UnsafeMutablePointer<RawByte>.alloc(length)
copy.initializeFrom(unsafeBitCast(bytes, UnsafeMutablePointer<RawByte>.self), count: length)
self.bytes = unsafeBitCast(copy, UnsafePointer<Void>.self)
self.length = length
}
deinit {
unsafeBitCast(bytes, UnsafeMutablePointer<RawByte>.self).dealloc(length)
}
}
}
// MARK: - DatabaseValueConvertible
/// Blob adopts DatabaseValueConvertible
extension Blob : DatabaseValueConvertible {
/// Returns a value that can be stored in the database.
public var databaseValue: DatabaseValue {
return .Blob(self)
}
/**
Returns the Blob contained in *databaseValue*, if any.
- parameter databaseValue: A DatabaseValue.
- returns: An optional Blob.
*/
public static func fromDatabaseValue(databaseValue: DatabaseValue) -> Blob? {
switch databaseValue {
case .Blob(let blob):
return blob
default:
return nil
}
}
}
// MARK: - BlobImpl
// The protocol for Blob underlying implementation
protocol BlobImpl {
var bytes: UnsafePointer<Void> { get }
var length: Int { get }
}
// MARK: - CustomString
/// DatabaseValue adopts CustomStringConvertible.
extension Blob : CustomStringConvertible {
/// A textual representation of `self`.
public var description: String {
return "Blob(\(length) bytes)"
}
}
// MARK: - Equatable
/// DatabaseValue adopts Equatable.
public func ==(lhs: Blob, rhs: Blob) -> Bool {
guard lhs.length == rhs.length else {
return false
}
return memcmp(lhs.bytes, rhs.bytes, lhs.length) == 0
}
| mit | 2fcf890c0c28cb0c08184c93771d01e9 | 25.861111 | 104 | 0.620476 | 4.771382 | false | false | false | false |
ahoppen/swift | tools/swift-inspect/Sources/swift-inspect/Backtrace.swift | 4 | 1404 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2020 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import SwiftRemoteMirror
internal enum BacktraceStyle {
case oneline
case long
}
internal func backtrace(_ stack: [swift_reflection_ptr_t], style: BacktraceStyle,
_ symbolicate: (swift_addr_t) -> (module: String?, symbol: String?)) -> String {
func entry(_ address: swift_reflection_ptr_t) -> String {
let (module, symbol) = symbolicate(swift_addr_t(address))
return "\(hex: address) (\(module ?? "<uknown>")) \(symbol ?? "<unknown>")"
}
// The pointers to the locations in the backtrace are stored from deepest to
// shallowest, so `main` will be somewhere near the end.
switch style {
case .oneline:
return stack.reversed().map { entry($0) }.joined(separator: " | ")
case .long:
return stack.reversed().enumerated().map {
" \(String(repeating: " ", count: $0 + 1))\(entry($1))"
}.joined(separator: "\n")
}
}
| apache-2.0 | 53311498140c2aecaf023894132a2fde | 36.945946 | 104 | 0.587607 | 4.203593 | false | false | false | false |
odigeoteam/TableViewKit | Examples/SampleApp/SampleApp/ActionBar/ActionBar.swift | 1 | 1871 | import Foundation
import UIKit
public enum Direction {
case next
case previous
}
public protocol ActionBarDelegate: class {
func actionBar(_ actionBar: ActionBar, direction: Direction)
func actionBar(_ actionBar: ActionBar, doneButtonPressed doneButtonItem: UIBarButtonItem)
}
open class ActionBar: UIToolbar {
var navigationControl: UISegmentedControl!
var actionBarDelegate: ActionBarDelegate!
init(delegate: ActionBarDelegate) {
super.init(frame: CGRect.zero)
sizeToFit()
actionBarDelegate = delegate
setup()
}
required public init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)!
}
fileprivate func setup() {
let previousButtonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonItem.SystemItem(rawValue: 105)!, target: self, action: #selector(previousHandler))
let nextButtonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonItem.SystemItem(rawValue: 106)!, target: self, action: #selector(nextHandler))
let doneButton = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(handleActionBarDone))
let spacer = UIBarButtonItem(barButtonSystemItem: .fixedSpace, target: nil, action: nil)
spacer.width = 40.0
let flexible = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
items = [previousButtonItem, spacer, nextButtonItem, flexible, doneButton]
}
@objc func handleActionBarDone(_ item: UIBarButtonItem) {
actionBarDelegate.actionBar(self, doneButtonPressed: item)
}
@objc func previousHandler(_ sender: UIBarButtonItem) {
actionBarDelegate.actionBar(self, direction: .previous)
}
@objc func nextHandler(_ sender: UIBarButtonItem) {
actionBarDelegate.actionBar(self, direction: .next)
}
}
| mit | 33d6a304a9800bdd3c3d0c1ffccfa299 | 30.183333 | 163 | 0.716729 | 4.897906 | false | false | false | false |
suzp1984/IOS-ApiDemo | ApiDemo-Swift/ApiDemo-Swift/CIFilterTransitionViewController.swift | 1 | 3696 | //
// CIFilterTransitionViewController.swift
// ApiDemo-Swift
//
// Created by Jacob su on 7/21/16.
// Copyright © 2016 [email protected]. All rights reserved.
//
import UIKit
class CIFilterTransitionViewController: UIViewController {
var v : UIView!
var tran : CIFilter!
var moiextent : CGRect!
var frame : Double!
var timestamp: CFTimeInterval!
var context : CIContext!
let SCALE = 1.0
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor.white
let button = UIButton(type: .system)
button.setTitle("Start", for: UIControlState())
button.addTarget(self, action: #selector(CIFilterTransitionViewController.start), for: .touchUpInside)
button.translatesAutoresizingMaskIntoConstraints = false
self.view.addSubview(button)
button.topAnchor.constraint(equalTo: self.topLayoutGuide.bottomAnchor, constant: 20).isActive = true
button.leftAnchor.constraint(equalTo: self.view.leftAnchor, constant: 20).isActive = true
let v = UIView()
self.view.addSubview(v)
v.backgroundColor = UIColor.red
v.translatesAutoresizingMaskIntoConstraints = false
v.topAnchor.constraint(equalTo: button.bottomAnchor, constant: 20).isActive = true
v.centerXAnchor.constraint(equalTo: self.view.centerXAnchor, constant: 0.0).isActive = true
v.widthAnchor.constraint(equalToConstant: 240.0).isActive = true
v.heightAnchor.constraint(equalToConstant: 240.0).isActive = true
self.v = v
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func start() -> Void {
let moi = CIImage(image:UIImage(named:"Moi")!)!
self.moiextent = moi.extent
let col = CIFilter(name:"CIConstantColorGenerator")!
let cicol = CIColor(color:UIColor.red)
col.setValue(cicol, forKey:"inputColor")
let colorimage = col.value(forKey: "outputImage") as! CIImage
let tran = CIFilter(name:"CIFlashTransition")!
tran.setValue(colorimage, forKey:"inputImage")
tran.setValue(moi, forKey:"inputTargetImage")
let center = CIVector(x:self.moiextent.width/2.0, y:self.moiextent.height/2.0)
tran.setValue(center, forKey:"inputCenter")
self.tran = tran
self.timestamp = 0.0 // signal that we are starting
self.context = CIContext(options:nil)
DispatchQueue.main.async {
let link = CADisplayLink(target:self, selector:#selector(self.nextFrame))
link.add(to: RunLoop.main, forMode:RunLoopMode.defaultRunLoopMode)
}
}
func nextFrame(_ sender:CADisplayLink) {
if self.timestamp < 0.01 { // pick up and store first timestamp
self.timestamp = sender.timestamp
self.frame = 0.0
} else { // calculate frame
self.frame = (sender.timestamp - self.timestamp) * SCALE
}
sender.isPaused = true // defend against frame loss
self.tran.setValue(self.frame, forKey:"inputTime")
let moi = self.context.createCGImage(tran.outputImage!, from:self.moiextent)
CATransaction.setDisableActions(true)
self.v.layer.contents = moi
if self.frame > 1.0 {
print("invalidate")
sender.invalidate()
}
sender.isPaused = false
print("here \(self.frame)") // useful for seeing dropped frame rate
}
}
| apache-2.0 | 23ce0066c27e314089ada4cc8f4304d8 | 34.190476 | 110 | 0.632206 | 4.561728 | false | false | false | false |
skylib/SnapImagePicker | SnapImagePicker_Unit_Tests/TestDoubles/SnapImagePickerPresenterSpy.swift | 1 | 1462 | @testable import SnapImagePicker
class SnapImagePickerPresenterSpy: SnapImagePickerPresenterProtocol {
var presentInitialAlbumCount = 0
var presentInitialAlbumImage: SnapImagePickerImage?
var presentInitialAlbumSize: Int?
var presentMainImageCount = 0
var presentMainImage: SnapImagePickerImage?
var presentAlbumImageCount = 0
var presentAlbumImage: SnapImagePickerImage?
var presentAlbumImageAtIndex: Int?
private var delegate: SnapImagePickerTestExpectationDelegate?
init(delegate: SnapImagePickerTestExpectationDelegate) {
self.delegate = delegate
}
func presentInitialAlbum(image: SnapImagePickerImage, albumSize: Int) {
presentInitialAlbumCount += 1
presentInitialAlbumImage = image
presentInitialAlbumSize = albumSize
delegate?.fulfillExpectation?()
}
func presentMainImage(image: SnapImagePickerImage) -> Bool {
presentMainImageCount += 1
presentMainImage = image
delegate?.fulfillExpectation?()
return true
}
func presentAlbumImage(image: SnapImagePickerImage, atIndex: Int) -> Bool {
presentAlbumImageCount += 1
presentAlbumImage = image
presentAlbumImageAtIndex = atIndex
delegate?.fulfillExpectation?()
return true
}
func deletedRequestAtIndex(index: Int, forAlbumType: AlbumType) {
}
} | bsd-3-clause | f5aa3a5562947c8ed232434c30c79884 | 28.857143 | 79 | 0.69015 | 6.091667 | false | true | false | false |
DDSSwiftTech/SwiftMine | Sources/SwiftMineCore/src/Network/Packets/TextPacket.swift | 1 | 2021 | //
// TextPacket.swift
// SwiftMineCore
//
// Created by David Schwartz on 11/21/17.
//
import Foundation
class TextPacket: MCPacket {
let type: TextType
let needsTranslation: Bool
let message: String
let source: String?
let xuid: String
init(type: TextType, needsTranslation: Bool, message: String, source: String, xuid: String) {
self.type = type
self.needsTranslation = needsTranslation
self.message = message
self.source = source
self.xuid = xuid
var buffer = Data()
buffer.push(value: type.rawValue)
buffer.push(value: (needsTranslation ? 1 : 0) as UInt8)
switch type {
case .CHAT, .WHISPER, .ANNOUNCEMENT:
buffer.push(string: source)
fallthrough
case .RAW, .TIP, .SYSTEM:
buffer.push(string: message)
case .TRANSLATION, .POPUP, .JUKEBOX_POPUP:
buffer.push(string: message)
}
buffer.push(string: xuid)
super.init(packetType: .TEXT_PACKET, buffer: buffer)
}
init?(buffer: Data) {
let originalBuffer = buffer
var buffer = buffer
guard let type = TextType(rawValue: buffer.read(length: 1)) else {
return nil
}
self.type = type
self.needsTranslation = (buffer.read(length: 1) as UInt8) == 1 ? true : false
var tempSource: String? = nil
switch type {
case .CHAT, .WHISPER, .ANNOUNCEMENT:
tempSource = buffer.readString() ?? ""
fallthrough
case .RAW, .TIP, .SYSTEM:
self.message = buffer.readString() ?? ""
case .TRANSLATION, .POPUP, .JUKEBOX_POPUP:
tempSource = nil
self.message = buffer.readString() ?? ""
}
self.source = tempSource
self.xuid = ""
super.init(packetType: .TEXT_PACKET, buffer: originalBuffer)
}
}
| apache-2.0 | 0d53f28473f73b65065a2b655905b526 | 26.684932 | 97 | 0.550717 | 4.132924 | false | false | false | false |
convergeeducacao/Charts | Source/ChartsRealm/Data/RealmRadarDataSet.swift | 8 | 2324 | //
// RealmRadarDataSet.swift
// Charts
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/Charts
//
import Foundation
import CoreGraphics
#if NEEDS_CHARTS
import Charts
#endif
import Realm
import Realm.Dynamic
open class RealmRadarDataSet: RealmLineRadarDataSet, IRadarChartDataSet
{
open override func initialize()
{
self.valueFont = NSUIFont.systemFont(ofSize: 13.0)
}
public required init()
{
super.init()
}
public init(results: RLMResults<RLMObject>?, yValueField: String, label: String?)
{
super.init(results: results, xValueField: nil, yValueField: yValueField, label: label)
}
public convenience init(results: RLMResults<RLMObject>?, yValueField: String)
{
self.init(results: results, yValueField: yValueField, label: "DataSet")
}
public init(realm: RLMRealm?, modelName: String, resultsWhere: String, yValueField: String, label: String?)
{
super.init(realm: realm, modelName: modelName, resultsWhere: resultsWhere, xValueField: nil, yValueField: yValueField, label: label)
}
// MARK: - Data functions and accessors
internal override func buildEntryFromResultObject(_ object: RLMObject, x: Double) -> ChartDataEntry
{
return RadarChartDataEntry(value: object[_yValueField!] as! Double)
}
// MARK: - Styling functions and accessors
/// flag indicating whether highlight circle should be drawn or not
/// **default**: false
open var drawHighlightCircleEnabled: Bool = false
/// - returns: `true` if highlight circle should be drawn, `false` ifnot
open var isDrawHighlightCircleEnabled: Bool { return drawHighlightCircleEnabled }
open var highlightCircleFillColor: NSUIColor? = NSUIColor.white
/// The stroke color for highlight circle.
/// If `nil`, the color of the dataset is taken.
open var highlightCircleStrokeColor: NSUIColor?
open var highlightCircleStrokeAlpha: CGFloat = 0.3
open var highlightCircleInnerRadius: CGFloat = 3.0
open var highlightCircleOuterRadius: CGFloat = 4.0
open var highlightCircleStrokeWidth: CGFloat = 2.0
}
| apache-2.0 | 12097dc7ba681adbaa87059cee23b98b | 29.578947 | 140 | 0.69148 | 4.752556 | false | false | false | false |
myoungsc/SCWebPreview | Example/SCWebPreview/dummyfile1/dummyfile3.swift | 1 | 3776 | //
// dummyfile3.swift
// SCWebPreview
//
// Created by myoung on 2017. 8. 24..
// Copyright © 2017년 CocoaPods. All rights reserved.
//
import UIKit
class dummyfile3: NSObject {
/* pod spec
#
# Be sure to run `pod lib lint SCWebPreview.podspec' to ensure this is a
# valid spec before submitting.
#
# Any lines starting with a # are optional, but their use is encouraged
# To learn more about a Podspec see http://guides.cocoapods.org/syntax/podspec.html
#
Pod::Spec.new do |s|
s.name = 'SCWebPreview'
s.version = '0.1.0'
s.summary = 'Preview content in Website'
# This description is used to generate tags and improve search results.
# * Think: What does it do? Why did you write it? What is the focus?
# * Try to keep it short, snappy and to the point.
# * Write the description between the DESC delimiters below.
# * Finally, don't worry about the indent, CocoaPods strips it!
s.description = 'Preview content in Website'
s.homepage = 'https://github.com/myoungsc/SCWebPreview'
# s.screenshots = 'www.example.com/screenshots_1', 'www.example.com/screenshots_2'
s.license = { :type => 'MIT', :file => 'LICENSE' }
s.author = { 'myoungsc' => '[email protected]' }
s.source = { :git => 'https://github.com/myoungsc/SCWebPreview.git', :tag => s.version.to_s }
# s.social_media_url = 'https://twitter.com/<TWITTER_USERNAME>'
s.ios.deployment_target = '9.0'
s.source_files = 'SCWebPreview/Classes'
# s.resource = "SCWebPreview/Classes/SCWebPreview.xib"
# s.resource_bundles = {
# 'SCWebPreview' => ['SCWebPreview/Resources/Assets.{png, jpg}']
# }
# s.public_header_files = 'Pod/Classes.h'
# s.frameworks = 'UIKit', 'MapKit'
# s.dependency 'AFNetworking', '~> 2.3'
end
#
# Be sure to run `pod lib lint SCWebPreview.podspec' to ensure this is a
# valid spec before submitting.
#
# Any lines starting with a # are optional, but their use is encouraged
# To learn more about a Podspec see http://guides.cocoapods.org/syntax/podspec.html
#
Pod::Spec.new do |s|
s.name = 'SCWebPreview'
s.version = '0.1.0'
s.summary = 'Preview content in Website'
# This description is used to generate tags and improve search results.
# * Think: What does it do? Why did you write it? What is the focus?
# * Try to keep it short, snappy and to the point.
# * Write the description between the DESC delimiters below.
# * Finally, don't worry about the indent, CocoaPods strips it!
s.description = 'Preview content in Website'
s.homepage = 'https://github.com/myoungsc/SCWebPreview'
# s.screenshots = 'www.example.com/screenshots_1', 'www.example.com/screenshots_2'
s.license = { :type => 'MIT', :file => 'LICENSE' }
s.author = { 'myoungsc' => '[email protected]' }
s.source = { :git => 'https://github.com/myoungsc/SCWebPreview.git', :tag => s.version.to_s }
# s.social_media_url = 'https://twitter.com/<TWITTER_USERNAME>'
s.ios.deployment_target = '9.0'
s.source_files = 'SCWebPreview/Classes'
# s.resource = "SCWebPreview/Classes/SCWebPreview.xib"
# s.resource_bundles = {
# 'SCWebPreview' => ['SCWebPreview/Resources/Assets.{png, jpg}']
# }
# s.public_header_files = 'Pod/Classes.h'
# s.frameworks = 'UIKit', 'MapKit'
# s.dependency 'AFNetworking', '~> 2.3'
end
*/
}
| mit | b0ab49a436ddce479ac18b2e05c00f29 | 36.73 | 108 | 0.591572 | 3.596759 | false | false | false | false |
joncottonskyuk/EVReflection | EVReflection/pod/EVObjectDescription.swift | 1 | 4946 | //
// EVObjectDescription.swift
// EVReflection
//
// Created by Edwin Vermeer on 8/19/15.
// Copyright (c) 2015 evict. All rights reserved.
//
import Foundation
/**
Generate a description for an object by extracting information from the NSStringFromClass
*/
public class EVObjectDescription {
/// The name of the bundle
public var bundleName: String = ""
/// The name of the class
public var className: String = ""
/// The classpath starting from the bundle
public var classPath: [String] = []
/// The types of the items in the classpath
public var classPathType: [ObjectType] = []
/// The string representation used by Swift for the classpath
public var swiftClassID: String = ""
/**
Enum for the difrent types that can be part of an object description
*/
public enum ObjectType:String {
/// The target or bunldle
case Target = "t"
/// The Class
case Class = "C"
/// The Protocol
case Protocol = "P"
/// The function
case Function = "F"
/// A generic class
case Generic = "G"
}
/**
Initialize an instance and set all properties based on the object
:parameter: forObject the object that you want the description for
*/
public init(forObject: NSObject) {
bundleName = EVReflection.getCleanAppName()
swiftClassID = NSStringFromClass(forObject.dynamicType)
if (swiftClassID.hasPrefix("_T")) {
parseTypes((swiftClassID as NSString).substringFromIndex(2))
bundleName = classPath[0]
className = classPath.last!
} else {
// Root objects will already have a . notation
classPath = swiftClassID.characters.split(isSeparator: {$0 == "."}).map({String($0)})
if classPath.count > 1 {
bundleName = classPath[0]
className = classPath.last!
classPathType = [ObjectType](count: classPath.count, repeatedValue: ObjectType.Class)
classPathType[0] = .Target
}
}
}
/**
Get all types from the class string
:parameter: classString the string representation of a class
:returns: Nothing
*/
private func parseTypes(classString:String) {
let characters = Array(classString.characters)
let type:String = String(characters[0])
if Int(type) == nil {
let ot: ObjectType = ObjectType(rawValue: type)!
if ot == .Target {
classPathType.append(ot)
} else {
classPathType.insert(ot, atIndex: 1) // after Target all types are in reverse order
}
parseTypes((classString as NSString).substringFromIndex(1))
} else {
parseNames(classString)
}
}
/**
Get all the names from the class string
:parameter: classString the string representation of the class
:returns: Nothing
*/
private func parseNames(classString:String) {
let characters = Array(classString.characters)
var numForName = ""
var index = 0
while Int(String(characters[index])) != nil {
numForName = "\(numForName)\(characters[index])"
index++
}
let range = Range<String.Index>(start:classString.startIndex.advancedBy(index), end:classString.startIndex.advancedBy((Int(numForName) ?? 0) + index))
let name = classString.substringWithRange(range)
classPath.append(name)
if name == "" {
return
}
if classPathType[classPath.count - 1] == .Function {
//TODO: reverse engineer function description. For now only allow parameterless function that return void
//No param, no return FS0_FT_T_L_
//No param, return object FS0_FT_CS_
//String param, return object FS0_FSSCS_
//Int param, return object FS0_FSiCS_
//String param, no return FS0_FSST_L_
//2 param return object FS0_FTSS6param2SS_CS_
//3 param return object FS0_FTSS6parambSi6paramcSS_CS_
//3 param, 2 return values FS0_FTSS6parambSi6paramcSS_T1aSS1bCS_
//Parsing rules:
//Always start with FS0_F
//If next is S then 1 param defined by 1 letter type
//If next isT then sequence of S, type (S = string, i = int) number for lenghts, name, if nummer _ then no name
//Ends with T_L_ then no return value
//Ends with CS_ then there will be return value(s)
index = index + 11
}
if characters.count > index + Int(numForName)! {
parseNames((classString as NSString).substringFromIndex(index + Int(numForName)!))
}
}
}
| bsd-3-clause | 082dded6c27943425b1beec22d209f41 | 35.367647 | 158 | 0.585726 | 4.496364 | false | false | false | false |
linhaosunny/smallGifts | 小礼品/小礼品/Classes/Module/Me/Chat/ChatBar/KeyBoard/EmojiManager.swift | 1 | 1448 | //
// EmojiManager.swift
// 小礼品
//
// Created by 李莎鑫 on 2017/5/12.
// Copyright © 2017年 李莎鑫. All rights reserved.
// 表情管理工具类
import UIKit
class EmojiManager: NSObject {
//MARK: 单例
static let shared = EmojiManager()
//: 设置完成的闭包
var finshed:((_ array:NSMutableArray)->())?
//: 用户ID
var userid:String?
//MARK: 构造方法
override init() {
super.init()
}
//: 外部接口
func emojisGroup(byUserID id:String,complete:@escaping (_ array:NSMutableArray)->()) {
userid = id
finshed = complete
//: 异步去获取
DispatchQueue(label: "emojisGroup").async {
let emojiGroup = NSMutableArray()
//: 添加默认系统表情
emojiGroup.add(ChatExpression.shared.defaultEmoji)
//: 添加默认系统Face
emojiGroup.add(ChatExpression.shared.defaultFace)
//: 添加用户收藏的表情包
if let usrEmojis = ChatExpression.shared.usrEmoji {
for i in 0..<usrEmojis.count {
emojiGroup.add(usrEmojis[i])
}
}
//: 系统设置
//: 执行用户的操作
DispatchQueue.main.async(execute: {
complete(emojiGroup)
})
}
}
}
| mit | d212e3dc2445dd075a3f2b683d664300 | 21.719298 | 90 | 0.505792 | 4.434932 | false | false | false | false |
natestedman/PrettyOkayKit | PrettyOkayKit/User.swift | 1 | 4114 | // Copyright (c) 2016, Nate Stedman <[email protected]>
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
// REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
// AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
// INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
// LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
// OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
import Foundation
// MARK: - Users
/// A user on Very Goods.
public struct User: ModelType, Equatable
{
// MARK: - Model
/// The user's identifier, required for conformance with `ModelType`.
public let identifier: ModelIdentifier
// MARK: - Metadata
/// The user's Very Goods username.
public let username: String
/// The user's "real name", if any.
public let name: String?
/// The user's biography text, if any.
public let biography: String?
/// The user's location, if any.
public let location: String?
/// The user's personal website URL.
public let URL: NSURL?
// MARK: - Avatar
/// The URL for the user's avatar.
public let avatarURL: NSURL?
/// The URL for the centered 126-pixel version of the user's avatar.
public let avatarURLCentered126: NSURL?
// MARK: - Cover
/// The URL for the user's cover image.
public let coverURL: NSURL?
/// The URL for the large version of the user's cover image.
public let coverLargeURL: NSURL?
/// The URL for the thumbnail version of the user's cover image.
public let coverThumbURL: NSURL?
// MARK: - Goods
/// The number of goods the user has added to his or her profile.
public let goodsCount: Int
}
extension User: Decoding
{
// MARK: - Decoding
/// Attempts to decode a `User`.
///
/// - parameter encoded: An encoded representation of a `User`.
///
/// - throws: An error encountered while decoding the `User`.
///
/// - returns: A `User` value, if successful.
public init(encoded: [String : AnyObject]) throws
{
self.init(
identifier: try encoded.decode("id"),
username: try encoded.decode("username"),
name: encoded["name"] as? String,
biography: encoded["bio"] as? String,
location: encoded["location"] as? String,
URL: try? encoded.decodeURL("url"),
avatarURL: try? encoded.decodeURL("avatar_url"),
avatarURLCentered126: try? encoded.decodeURL("avatar_url_centered_126"),
coverURL: try? encoded.decodeURL("cover_image"),
coverLargeURL: try? encoded.decodeURL("cover_image_big_url"),
coverThumbURL: try? encoded.decodeURL("cover_image_thumb_url"),
goodsCount: try encoded.decode("good_count")
)
}
}
extension User: CustomStringConvertible
{
public var description: String
{
return "User \(self.identifier) (@\(self.username))"
}
}
/// Equates two `User` values.
///
/// - parameter lhs: The first user value.
/// - parameter rhs: The second user value.
///
/// - returns: If the values are equal, `true`.
@warn_unused_result
public func ==(lhs: User, rhs: User) -> Bool
{
return lhs.identifier == rhs.identifier
&& lhs.username == rhs.username
&& lhs.name == rhs.name
&& lhs.biography == rhs.biography
&& lhs.location == rhs.location
&& lhs.URL == rhs.URL
&& lhs.avatarURL == rhs.avatarURL
&& lhs.avatarURLCentered126 == rhs.avatarURLCentered126
&& lhs.coverURL == rhs.coverURL
&& lhs.coverLargeURL == rhs.coverLargeURL
&& lhs.coverThumbURL == rhs.coverThumbURL
&& lhs.goodsCount == rhs.goodsCount
}
| isc | e3c00e9d2e6cf45710f555f864a8d87f | 31.140625 | 84 | 0.644871 | 4.272066 | false | false | false | false |
cxpyear/spdbapp | spdbapp/ShowToolbarState.swift | 1 | 1011 | //
// ShowToolbarState.swift
// spdbapp
//
// Created by GBTouchG3 on 15/6/15.
// Copyright (c) 2015年 shgbit. All rights reserved.
//
import UIKit
import Foundation
class ShowToolbarState: NSObject {
class func netConnectFail(label: UILabel, btn: UIButton){
label.textColor = UIColor.redColor()
label.text = "网络连接失败"
btn.hidden = false
btn.backgroundColor = UIColor(red: 66/255, green: 173/255, blue: 249/255, alpha: 1)
btn.enabled = true
}
class func netConnectSuccess(label: UILabel, btn: UIButton){
label.textColor = UIColor(red: 37/255, green: 189/255, blue: 54/255, alpha: 1.0)
label.text = "网络已连接"
btn.hidden = true
}
class func netConnectLinking(label: UILabel, btn: UIButton){
btn.enabled = false
btn.backgroundColor = UIColor.grayColor()
label.text = "网络正在连接..."
label.textColor = UIColor.blueColor()
}
} | bsd-3-clause | 398c709c392a4c43fcfcef9ec1efed1b | 24.684211 | 91 | 0.615385 | 3.707224 | false | false | false | false |
ccrama/Slide-iOS | Slide for Reddit/UIAlertController+Extensions.swift | 1 | 3510 | //
// UIAlertController+Extensions.swift
// Slide for Reddit
//
// Created by Carlos Crane on 7/24/18.
// Copyright © 2018 Haptic Apps. All rights reserved.
//
import SDCAlertView
import UIKit
private var associationKey: UInt8 = 0
public extension AlertController {
private var alertWindow: UIWindow! {
get {
return objc_getAssociatedObject(self, &associationKey) as? UIWindow
}
set(newValue) {
objc_setAssociatedObject(self, &associationKey, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN)
}
}
//https://stackoverflow.com/a/51723032/3697225
func showWindowless() {
self.alertWindow = UIWindow.init(frame: UIScreen.main.bounds)
let viewController = UIViewController()
self.alertWindow.rootViewController = viewController
let topWindow = UIApplication.shared.windows.last
if let topWindow = topWindow {
self.alertWindow.windowLevel = topWindow.windowLevel + 1
}
self.alertWindow.makeKeyAndVisible()
self.alertWindow.rootViewController?.present(self, animated: true, completion: nil)
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
self.alertWindow?.isHidden = true
self.alertWindow = nil
}
}
public extension UIAlertController {
private var alertWindow: UIWindow! {
get {
return objc_getAssociatedObject(self, &associationKey) as? UIWindow
}
set(newValue) {
objc_setAssociatedObject(self, &associationKey, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN)
}
}
//https://stackoverflow.com/a/51723032/3697225
func showWindowless() {
self.alertWindow = UIWindow.init(frame: UIScreen.main.bounds)
let viewController = UIViewController()
self.alertWindow.rootViewController = viewController
let topWindow = UIApplication.shared.windows.last
if let topWindow = topWindow {
self.alertWindow.windowLevel = topWindow.windowLevel + 1
}
self.alertWindow.makeKeyAndVisible()
self.alertWindow.rootViewController?.present(self, animated: true, completion: nil)
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
self.alertWindow?.isHidden = true
self.alertWindow = nil
}
}
public extension UIActivityViewController {
private var alertWindow: UIWindow! {
get {
return objc_getAssociatedObject(self, &associationKey) as? UIWindow
}
set(newValue) {
objc_setAssociatedObject(self, &associationKey, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN)
}
}
func showWindowless() {
self.alertWindow = UIWindow.init(frame: UIScreen.main.bounds)
let viewController = UIViewController()
self.alertWindow.rootViewController = viewController
let topWindow = UIApplication.shared.windows.last
if let topWindow = topWindow {
self.alertWindow.windowLevel = topWindow.windowLevel + 1
}
self.alertWindow.makeKeyAndVisible()
self.alertWindow.rootViewController?.present(self, animated: true, completion: nil)
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
self.alertWindow?.isHidden = true
self.alertWindow = nil
}
}
| apache-2.0 | 25d7745c8eff12d0e4844ddbb248831c | 29.780702 | 117 | 0.668852 | 4.928371 | false | false | false | false |
silence0201/Swift-Study | AdvancedSwift/字符串/Code Unit Views.playgroundpage/Contents.swift | 1 | 5133 | /*:
## Code Unit Views
Sometimes it's necessary to drop down to a lower level of abstraction and
operate directly on Unicode code units instead of characters. There are a few
common reasons for this.
Firstly, maybe you actually need the code units, perhaps for rendering into a
UTF-8-encoded webpage, or for interoperating with a non-Swift API that takes
them.
For an example of an API that requires code units, let's look at using
`CharacterSet` from the Foundation framework in combination with Swift strings.
The `CharacterSet` API is mostly defined in terms of Unicode scalars. So if you
wanted to use `CharacterSet` to split up a string, you could do it via the
`unicodeScalars` view:
*/
//#-hidden-code
import Foundation
//#-end-hidden-code
//#-editable-code
extension String {
func words(with charset: CharacterSet = .alphanumerics) -> [String] {
return self.unicodeScalars.split {
!charset.contains($0)
}.map(String.init)
}
}
let s = "Wow! This contains _all_ kinds of things like 123 and \"quotes\"?"
s.words()
//#-end-editable-code
/*:
This will break the string apart at every non-alphanumeric character, giving you
an array of `String.UnicodeScalarView` slices. They can be turned back into
strings via `map` with the `String` initializer that takes a
`UnicodeScalarView`.
The good news is, even after going through this fairly extensive pipeline, the
string slices in `words` will *still* just be views onto the original string;
this property isn't lost by going via the `UnicodeScalarView` and back again.
A second reason for using these views is that operating on code units rather
than fully composed characters can be much faster. This is because to compose
grapheme clusters, you must look ahead of every character to see if it's
followed by combining characters. To see just how much faster these views can
be, take a look at the performance section later on.
Finally, the UTF-16 view has one benefit the other views don't have: it can be
random access. This is possible for just this view type because, as we've seen,
this is how strings are held internally within the `String` type. What this
means is the *n*^th^ UTF-16 code unit is always at the *n*^th^ position in the
buffer (even if the string is in "ASCII buffer mode" – it's just a question of
the width of the entries to advance over).
The Swift team made the decision *not* to conform `String.UTF16View` to
`RandomAccessCollection` in the standard library, though. Instead, they moved
the conformance into Foundation, so you need to import Foundation to take
advantage of it. A comment [in the Foundation source
code](https://github.com/apple/swift/blob/master/stdlib/public/SDK/Foundation/ExtraStringAPIs.swift)
explains why:
``` swift-example
// Random access for String.UTF16View, only when Foundation is
// imported. Making this API dependent on Foundation decouples the
// Swift core from a UTF16 representation.
...
extension String.UTF16View : RandomAccessCollection {}
```
Nothing would break if a future `String` implementation used a different
internal representation. Existing code that relied on the random-access
conformance could take advantage of the option for a `String` to be backed by an
`NSString`, like we discussed above. `NSString` also uses UTF-16 internally.
That said, it's probably rarer than you think to need random access. Most
practical string use cases just need serial access. But some processing
algorithms rely on random access for efficiency. For example, the Boyer-Moore
search algorithm relies on the ability to skip along the text in jumps of
multiple characters.
So you could use the UTF-16 view with algorithms that require such a
characteristic. Another example is the search algorithm we define in the
generics chapter:
*/
//#-hidden-code
import Foundation
extension Collection
where Iterator.Element: Equatable,
SubSequence.Iterator.Element == Iterator.Element,
Indices.Iterator.Element == Index
{
func search<Other: Sequence>(for pattern: Other) -> Index?
where Other.Iterator.Element == Iterator.Element
{
return indices.first { idx in
suffix(from: idx).starts(with: pattern)
}
}
}
//#-end-hidden-code
//#-editable-code
let helloWorld = "Hello, world!"
if let idx = helloWorld.utf16.search(for: "world".utf16)?
.samePosition(in: helloWorld)
{
print(helloWorld[idx..<helloWorld.endIndex])
}
//#-end-editable-code
/*:
But beware\! These convenience or efficiency benefits come at a price, which is
that your code may no longer be completely Unicode-correct. So unfortunately,
the following search will fail:
*/
//#-editable-code
let text = "Look up your Pok\u{0065}\u{0301}mon in a Pokédex."
text.utf16.search(for: "Pokémon".utf16)
//#-end-editable-code
/*:
Unicode defines diacritics that are used to combine with alphabetic characters
as being alphanumeric, so this fares a little better:
*/
//#-editable-code
let nonAlphas = CharacterSet.alphanumerics.inverted
text.unicodeScalars.split(whereSeparator: nonAlphas.contains).map(String.init)
//#-end-editable-code
| mit | fffd29973a1fcf3eece7d877b084d345 | 35.375887 | 100 | 0.757068 | 4.073868 | false | false | false | false |
k-o-d-e-n/CGLayout | Sources/Classes/layoutConstraint.cglayout.swift | 1 | 12684 | //
// Layout.swift
// CGLayout
//
// Created by Denis Koryttsev on 29/08/2017.
// Copyright © 2017 K-o-D-e-N. All rights reserved.
//
#if os(iOS) || os(tvOS)
import UIKit
#elseif os(macOS)
import Cocoa
#elseif os(Linux)
import Foundation
#endif
// MARK: LayoutConstraint
/// Provides rect for constrain source space. Used for related constraints.
public protocol LayoutConstraintProtocol: RectBasedConstraint {
/// Element identifier
var elementIdentifier: ObjectIdentifier? { get }
/// Flag, defines that constraint may be used for layout
var isActive: Bool { get }
/// Main function for constrain source space by other rect
///
/// - Parameters:
/// - sourceRect: Source space
/// - rect: Rect for constrain
func formConstrain(sourceRect: inout CGRect, by rect: CGRect?, in coordinateSpace: LayoutElement)
}
public extension LayoutConstraintProtocol {
/// Returns constraint with possibility to change active state
///
/// - Parameter active: Initial active state
/// - Returns: Mutable layout constraint
func active(_ active: Bool) -> MutableLayoutConstraint {
return .init(base: self, isActive: active)
}
}
/// Simple related constraint. Contains anchor constraints and layout element as source of frame for constrain
public struct LayoutConstraint {
fileprivate let constraints: [RectBasedConstraint]
private(set) weak var item: LayoutElement?
internal var inLayoutTime: ElementInLayoutTime?
internal var inLayoutTimeItem: ElementInLayoutTime? {
return inLayoutTime ?? item?.inLayoutTime
}
public init(element: LayoutElement, constraints: [RectBasedConstraint]) {
self.item = element
self.inLayoutTime = element.inLayoutTime
self.constraints = constraints
}
}
extension LayoutConstraint: LayoutConstraintProtocol {
public var elementIdentifier: ObjectIdentifier? { return item.map(ObjectIdentifier.init) }
/// Flag, defines that constraint may be used for layout
public var isActive: Bool { return inLayoutTimeItem?.superElement != nil }
public /// Main function for constrain source space by other rect
///
/// - Parameters:
/// - sourceRect: Source space
/// - rect: Rect for constrain
func formConstrain(sourceRect: inout CGRect, by rect: CGRect) {
constraints.forEach { (constraint) in
constraint.formConstrain(sourceRect: &sourceRect, by: rect)
}
}
public /// Converts rect from constraint coordinate space to destination coordinate space if needed.
///
/// - Parameters:
/// - rect: Initial rect
/// - coordinateSpace: Destination coordinate space
/// - Returns: Converted rect
func convert(rectIfNeeded rect: CGRect, to coordinateSpace: LayoutElement) -> CGRect {
guard let superLayoutItem = inLayoutTimeItem?.superElement else { fatalError("Constraint has not access to layout element or him super element. /n\(self)") }
return coordinateSpace === superLayoutItem ? rect : coordinateSpace.convert(rect: rect, from: superLayoutItem)
}
public func formConstrain(sourceRect: inout CGRect, by rect: CGRect?, in coordinateSpace: LayoutElement) {
guard let item = inLayoutTimeItem else { fatalError("Constraint has not access to layout item or him super item. /n\(self)") }
formConstrain(sourceRect: &sourceRect, by: convert(rectIfNeeded: rect ?? item.frame, to: coordinateSpace))
}
}
/// Related constraint for adjust size of source space. Contains size constraints and layout element for calculate size.
public struct AdjustLayoutConstraint {
let anchors: [Size]
let alignment: Layout.Alignment
private(set) weak var item: AdjustableLayoutElement?
public init(element: AdjustableLayoutElement, anchors: [Size], alignment: Layout.Alignment) {
self.item = element
self.anchors = anchors
self.alignment = alignment
}
}
extension AdjustLayoutConstraint: LayoutConstraintProtocol {
public var elementIdentifier: ObjectIdentifier? { return nil }
public /// Flag, defines that constraint may be used for layout
var isActive: Bool { return item?.inLayoutTime.superElement != nil }
public /// Main function for constrain source space by other rect
///
/// - Parameters:
/// - sourceRect: Source space
/// - rect: Rect for constrain
func formConstrain(sourceRect: inout CGRect, by rect: CGRect) {
guard let item = item else { fatalError("Constraint has not access to layout element or him super element. /n\(self)") }
let adjustedRect = item.contentConstraint.constrained(sourceRect: rect, by: rect)
anchors.forEach { (constraint) in
constraint.formConstrain(sourceRect: &sourceRect, by: adjustedRect)
}
alignment.formLayout(rect: &sourceRect, in: rect)
}
public func formConstrain(sourceRect: inout CGRect, by rect: CGRect?, in coordinateSpace: LayoutElement) {
formConstrain(sourceRect: &sourceRect, by: rect ?? sourceRect)
}
}
/// Related constraint that uses internal bounds to constrain, defined in 'layoutBounds' property
public struct ContentLayoutConstraint {
fileprivate let constraints: [RectBasedConstraint]
private(set) weak var item: LayoutElement?
internal var inLayoutTime: ElementInLayoutTime?
internal var inLayoutTimeItem: ElementInLayoutTime? {
return inLayoutTime ?? item?.inLayoutTime
}
public init(element: LayoutElement, constraints: [RectBasedConstraint]) {
self.item = element
self.inLayoutTime = element.inLayoutTime
self.constraints = constraints
}
}
extension ContentLayoutConstraint: LayoutConstraintProtocol {
public var elementIdentifier: ObjectIdentifier? { return item.map(ObjectIdentifier.init) }
/// Flag, defines that constraint may be used for layout
public var isActive: Bool { return inLayoutTimeItem?.superElement != nil }
public /// Main function for constrain source space by other rect
///
/// - Parameters:
/// - sourceRect: Source space
/// - rect: Rect for constrain
func formConstrain(sourceRect: inout CGRect, by rect: CGRect) {
constraints.forEach { (constraint) in
constraint.formConstrain(sourceRect: &sourceRect, by: rect)
}
}
public /// Converts rect from constraint coordinate space to destination coordinate space if needed.
///
/// - Parameters:
/// - rect: Initial rect
/// - coordinateSpace: Destination coordinate space
/// - Returns: Converted rect
func convert(rectIfNeeded rect: CGRect, to coordinateSpace: LayoutElement) -> CGRect {
guard let item = self.item else { fatalError("Constraint has not access to layout element or him super element. /n\(self)") }
return coordinateSpace === item ? rect : coordinateSpace.convert(rect: rect, from: item)
}
public func formConstrain(sourceRect: inout CGRect, by rect: CGRect?, in coordinateSpace: LayoutElement) {
guard let layoutItem = inLayoutTimeItem else { fatalError("Constraint has not access to layout element or him super element. /n\(self)") }
formConstrain(sourceRect: &sourceRect, by: convert(rectIfNeeded: rect ?? layoutItem.layoutBounds, to: coordinateSpace))
}
}
/// Layout constraint that creates possibility to change active state.
public class MutableLayoutConstraint: LayoutConstraintProtocol {
private var base: LayoutConstraintProtocol
private var _active = true
/// Flag, defines that constraint may be used for layout
public var isActive: Bool {
set { _active = newValue }
get { return _active && base.isActive }
}
public var elementIdentifier: ObjectIdentifier? { return base.elementIdentifier }
/// Designed initializer
///
/// - Parameters:
/// - base: Constraint for mutating
/// - isActive: Initial state
public init(base: LayoutConstraintProtocol, isActive: Bool) {
self.base = base
self._active = isActive
}
public /// Main function for constrain source space by other rect
///
/// - Parameters:
/// - sourceRect: Source space
/// - rect: Rect for constrain
func formConstrain(sourceRect: inout CGRect, by rect: CGRect) { base.formConstrain(sourceRect: &sourceRect, by: rect) }
public func formConstrain(sourceRect: inout CGRect, by rect: CGRect?, in coordinateSpace: LayoutElement) {
base.formConstrain(sourceRect: &sourceRect, by: rect, in: coordinateSpace)
}
}
// MARK: Additional constraints
/// Layout constraint for independent changing source space. Use him with anchors that not describes rect side (for example `LayoutAnchor.insets` or `LayoutAnchor.Size`).
public struct AnonymConstraint: LayoutConstraintProtocol {
let anchors: [RectBasedConstraint]
let constrainRect: ((CGRect) -> CGRect)?
public init(anchors: [RectBasedConstraint], constrainRect: ((CGRect) -> CGRect)? = nil) {
self.anchors = anchors
self.constrainRect = constrainRect
}
public var elementIdentifier: ObjectIdentifier? { return nil }
public /// Flag, defines that constraint may be used for layout
var isActive: Bool { return true }
/// Main function for constrain source space by other rect
///
/// - Parameters:
/// - sourceRect: Source space
/// - rect: Rect for constrain
public func formConstrain(sourceRect: inout CGRect, by rect: CGRect) {
anchors.forEach { (constraint) in
constraint.formConstrain(sourceRect: &sourceRect, by: rect)
}
}
public func formConstrain(sourceRect: inout CGRect, by rect: CGRect?, in coordinateSpace: LayoutElement) {
formConstrain(sourceRect: &sourceRect, by: constrainRect?(rect ?? sourceRect) ?? sourceRect)
}
}
public extension AnonymConstraint {
init(transform: @escaping (inout CGRect) -> Void) {
self.init(anchors: [Equal()]) {
var source = $0
transform(&source)
return source
}
}
}
// TODO: Create constraint for attributed string and other data oriented constraints
#if os(macOS) || os(iOS) || os(tvOS)
public extension String {
#if os(macOS)
typealias DrawingOptions = NSString.DrawingOptions
#elseif os(iOS) || os(tvOS)
typealias DrawingOptions = NSStringDrawingOptions
#endif
}
@available(OSX 10.11, *) /// Size-based constraint for constrain source rect by size of string. The size to draw gets from restrictive rect.
public struct StringLayoutAnchor: RectBasedConstraint {
let string: String?
let attributes: [NSAttributedString.Key: Any]?
let options: String.DrawingOptions
let context: NSStringDrawingContext?
/// Designed initializer
///
/// - Parameters:
/// - string: String for size calculation
/// - options: String drawing options.
/// - attributes: A dictionary of text attributes to be applied to the string. These are the same attributes that can be applied to an NSAttributedString object, but in the case of NSString objects, the attributes apply to the entire string, rather than ranges within the string.
/// - context: The string drawing context to use for the receiver, specifying minimum scale factor and tracking adjustments.
public init(string: String?, options: String.DrawingOptions = .usesLineFragmentOrigin, attributes: [NSAttributedString.Key: Any]? = nil, context: NSStringDrawingContext? = nil) {
self.string = string
self.attributes = attributes
self.context = context
self.options = options
}
public /// Main function for constrain source space by other rect
///
/// - Parameters:
/// - sourceRect: Source space
/// - rect: Rect for constrain
func formConstrain(sourceRect: inout CGRect, by rect: CGRect) {
sourceRect.size = string?.boundingRect(with: rect.size, options: options, attributes: attributes, context: context).size ?? .zero
}
}
public extension String {
/// Convenience getter for string layout constraint.
///
/// - Parameters:
/// - attributes: String attributes
/// - context: Drawing context
/// - Returns: String-based constraint
@available(OSX 10.11, iOS 10.0, *)
func layoutConstraint(with options: String.DrawingOptions = .usesLineFragmentOrigin, attributes: [NSAttributedString.Key: Any]? = nil, context: NSStringDrawingContext? = nil) -> StringLayoutAnchor {
return StringLayoutAnchor(string: self, options: options, attributes: attributes, context: context)
}
}
#endif
| mit | cf344d8148d75143eb330b5553f3a9f0 | 40.858086 | 285 | 0.696759 | 4.753748 | false | false | false | false |
Argas/10923748 | SOADemo/3. CoreLayer/Networking/Parsers/LastFMTracksParser.swift | 1 | 1139 | //
// LastFMTracksParser.swift
// SOADemo
//
// Created by Alex Zverev on 15.04.17.
// Copyright © 2017 a.y.zverev. All rights reserved.
//
import Foundation
import SwiftyJSON
struct TrackApiModel {
let artist: String
let name: String
let coverUrl: String
}
class LastFMTracksParser: IParser {
typealias Model = [TrackApiModel]
func parse(data: Data) -> [TrackApiModel]? {
let json = JSON(data)
guard let tracks = json["tracks"]["track"].array else {
return nil
}
var trackModelds: [TrackApiModel] = []
for track in tracks {
guard let name = track["name"].string,
let artist = track["artist"]["name"].string,
let coverUrl = track["image"].array?.first?["#text"].string else {
continue
}
trackModelds.append(TrackApiModel(artist: artist,
name: name,
coverUrl: coverUrl))
}
return trackModelds
}
}
| mit | 650593b752d2788e1d71968ff0b6a31a | 24.863636 | 82 | 0.508787 | 4.515873 | false | false | false | false |
guanix/swift-sodium | Sodium/PWHash.swift | 3 | 2593 | //
// PWHash.swift
// Sodium
//
// Created by Frank Denis on 4/29/15.
// Copyright (c) 2015 Frank Denis. All rights reserved.
//
import Foundation
public class PWHash {
public var scrypt = SCrypt()
public class SCrypt {
public let SaltBytes = Int(crypto_pwhash_scryptsalsa208sha256_saltbytes())
public let StrBytes = Int(crypto_pwhash_scryptsalsa208sha256_strbytes()) - (1 as Int)
public let StrPrefix = String(UTF8String: crypto_pwhash_scryptsalsa208sha256_strprefix())
public let OpsLimitInteractive = Int(crypto_pwhash_scryptsalsa208sha256_opslimit_interactive())
public let OpsLimitSensitive = Int(crypto_pwhash_scryptsalsa208sha256_opslimit_sensitive())
public let MemLimitInteractive = Int(crypto_pwhash_scryptsalsa208sha256_memlimit_interactive())
public let MemLimitSensitive = Int(crypto_pwhash_scryptsalsa208sha256_memlimit_sensitive())
public func str(passwd: NSData, opsLimit: Int, memLimit: Int) -> String? {
let output = NSMutableData(length: StrBytes)
if output == nil {
return nil
}
if crypto_pwhash_scryptsalsa208sha256_str(UnsafeMutablePointer<CChar>(output!.mutableBytes), UnsafePointer<CChar>(passwd.bytes), CUnsignedLongLong(passwd.length), CUnsignedLongLong(opsLimit), memLimit) != 0 {
return nil
}
return NSString(data: output!, encoding: NSUTF8StringEncoding) as String?
}
public func strVerify(hash: String, passwd: NSData) -> Bool {
let hashData = (hash + "\0").dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)
if hashData == nil {
return false
}
return crypto_pwhash_scryptsalsa208sha256_str_verify(UnsafePointer<CChar>(hashData!.bytes), UnsafePointer<CChar>(passwd.bytes), CUnsignedLongLong(passwd.length)) == 0
}
public func hash(outputLength: Int, passwd: NSData, salt: NSData, opsLimit: Int, memLimit: Int) -> NSData? {
if salt.length != SaltBytes {
return nil
}
let output = NSMutableData(length: outputLength)
if output == nil {
return nil
}
if crypto_pwhash_scryptsalsa208sha256(output!.mutableBytesPtr, CUnsignedLongLong(outputLength), UnsafePointer<CChar>(passwd.bytes), CUnsignedLongLong(passwd.length), salt.bytesPtr, CUnsignedLongLong(opsLimit), memLimit) != 0 {
return nil
}
return output
}
}
}
| isc | 66172a17272345a44b8ff513c4fc5458 | 45.303571 | 238 | 0.651755 | 4.175523 | false | false | false | false |
itsaboutcode/WordPress-iOS | WordPress/Classes/ViewRelated/Media/Tenor/TenorService.swift | 2 | 1573 | /// Encapsulates search parameters (text, pagination, etc)
struct TenorSearchParams {
let text: String
let pageable: Pageable?
let limit: Int
init(text: String?, pageable: Pageable?) {
self.text = text ?? ""
self.pageable = pageable
self.limit = pageable != nil ? pageable!.pageSize : TenorPageable.defaultPageSize
}
}
class TenorService {
static let tenor: TenorClient = {
TenorClient.configure(apiKey: ApiCredentials.tenorApiKey)
return TenorClient.shared
}()
func search(params: TenorSearchParams, completion: @escaping (TenorResultsPage) -> Void) {
let tenorPageable = params.pageable as? TenorPageable
let currentPageIndex = tenorPageable?.pageIndex
TenorService.tenor.search(for: params.text,
limit: params.limit,
from: tenorPageable?.position) { gifs, position, error in
guard let gifObjects = gifs, error == nil else {
completion(TenorResultsPage.empty())
return
}
let medias = gifObjects.compactMap { TenorMedia(tenorGIF: $0) }
let nextPageable = TenorPageable(itemsPerPage: params.limit,
position: position,
currentPageIndex: currentPageIndex ?? 0)
let result = TenorResultsPage(results: medias,
pageable: nextPageable)
completion(result)
}
}
}
| gpl-2.0 | 522c146bca9c297ff56aa7eb612bb815 | 36.452381 | 94 | 0.571519 | 4.653846 | false | false | false | false |
crspybits/SMCoreLib | SMCoreLib/Classes/General/SMMaskUtilities.swift | 1 | 1268 | //
// SMMaskUtilities.swift
// SMCoreLib
//
// Created by Christopher Prince on 6/16/16.
// Copyright © 2016 Spastic Muffin, LLC. All rights reserved.
//
import Foundation
open class SMMaskUtilities {
public static func enumDescription(rawValue:Int, allAsStrings: [String]) -> String {
var shift = 0
while (rawValue >> shift != 1) {
shift += 1
}
return allAsStrings[shift]
}
public static func maskDescription(stringArray:[String]) -> String {
var result = ""
for value in stringArray {
result += (result.count == 0) ? value : ",\(value)"
}
return "[\(result)]"
}
// An array of strings, possibly empty.
public static func maskArrayOfStrings
<StructType: OptionSet, EnumType: RawRepresentable>
(_ maskObj:StructType, contains:(_ maskObj:StructType, _ enumValue:EnumType)-> Bool) -> [String] where EnumType.RawValue == Int {
var result = [String]()
var shift = 0
while let enumValue = EnumType(rawValue: 1 << shift) {
shift += 1
if contains(maskObj, enumValue) {
result.append("\(enumValue)")
}
}
return result
}
}
| gpl-3.0 | ff0d7c7e919b71e050a84ea92f65eb9d | 25.957447 | 137 | 0.56985 | 4.508897 | false | false | false | false |
MLSDev/AppRouter | Sources/Route/AppRouter+route.swift | 1 | 4152 |
import UIKit
import RxSwift
import RxCocoa
import ReusableView
import AppRouter
public protocol ViewFactoryType {
func buildView<T>() throws -> T where T: UIViewController
func buildView<T, ARG>(arg: ARG) throws -> T where T: UIViewController
}
public protocol ViewModelFactoryType {
func buildViewModel<T>() throws -> T
func buildViewModel<T, ARG>(arg: ARG) throws -> T
func buildViewModel<T, ARG, ARG2>(arg: ARG, arg2: ARG2) throws -> T
func buildViewModel<T, ARG, ARG2, ARG3>(arg: ARG, arg2: ARG2, arg3: ARG3) throws -> T
}
public protocol BasicRouteProtocol {
associatedtype RouteTarget
@discardableResult func push() throws -> RouteTarget
@discardableResult func present() throws -> RouteTarget
@discardableResult func setAsRoot() throws -> RouteTarget
@discardableResult func show() throws -> RouteTarget
func onWeak(_ controller: UIViewController?) -> Self
}
open class Route<T: UIViewController> : AppRouter.Presenter.Configuration<T> where T: ViewModelHolderType{
open var viewModelProvider: () throws -> T.ViewModelType? = { nil }
public let viewFactory: ViewFactoryType
public let viewModelFactory: ViewModelFactoryType
public init(viewFactory: ViewFactoryType, viewModelFactory: ViewModelFactoryType, router: AppRouterType = AppRouter.shared) {
self.viewFactory = viewFactory
self.viewModelFactory = viewModelFactory
super.init(router: router)
}
open override func performConfiguration(for source: T) throws {
try self.performViewModelInsertion(for: source)
try super.performConfiguration(for: source)
}
open func buildViewModel() -> Self {
viewModelProvider = { [viewModelFactory] in try viewModelFactory.buildViewModel() }
return self
}
open func buildViewModel<ARG>(_ arg: ARG) -> Self {
viewModelProvider = { [viewModelFactory] in try viewModelFactory.buildViewModel(arg: arg) }
return self
}
open func buildViewModel<ARG, ARG2>(_ arg: ARG, _ arg2: ARG2) -> Self {
viewModelProvider = { [viewModelFactory] in try viewModelFactory.buildViewModel(arg: arg, arg2: arg2) }
return self
}
open func buildViewModel<ARG, ARG2, ARG3>(_ arg: ARG, _ arg2: ARG2, _ arg3: ARG3) -> Self {
viewModelProvider = { [viewModelFactory] in try viewModelFactory.buildViewModel(arg: arg, arg2: arg2, arg3: arg3) }
return self
}
open func with(viewModel: T.ViewModelType) -> Self {
viewModelProvider = { viewModel }
return self
}
open func performViewModelInsertion(for source: T) throws {
source.viewModel = try viewModelProvider()
}
open func fromFactory() -> Self {
return from{ [viewFactory] in try viewFactory.buildView() as T }
}
open func fromFactory<U>(arg: U) -> Self {
return from{ [viewFactory] in try viewFactory.buildView(arg: arg) as T }
}
}
extension ObservableConvertibleType where Self.Element: BasicRouteProtocol {
public func push() -> Disposable {
return self.asObservable().bind(onNext: {
_ = try? $0.push()
})
}
public func push(on controller: UIViewController) -> Disposable {
return self.asObservable().bind(onNext: { [weak controller] in
_ = try? $0.onWeak(controller).push()
})
}
public func present() -> Disposable {
return self.asObservable().bind(onNext: {
_ = try? $0.present()
})
}
public func setAsRoot() -> Disposable {
return self.asObservable().bind(onNext: {
_ = try? $0.setAsRoot()
})
}
public func show() -> Disposable {
return self.asObservable().bind(onNext: {
_ = try? $0.show()
})
}
}
extension AppRouter.Presenter.Configuration: BasicRouteProtocol {
public func onWeak(_ controller: UIViewController?) -> Self {
return on({ [weak controller] in
return try controller ?? AppRouter.Presenter.Errors.failedToConstructTargetController.rethrow()
})
}
}
| mit | 33b12350550ee0adf37e320ec3de89f8 | 33.31405 | 129 | 0.653179 | 4.393651 | false | false | false | false |
abertelrud/swift-package-manager | Sources/Basics/VirtualFileSystem.swift | 2 | 9128 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift open source project
//
// Copyright (c) 2021 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import Foundation
import TSCBasic
fileprivate enum DirectoryNode: Codable {
case directory(name: String, isSymlink: Bool, children: [DirectoryNode])
case file(name: String, isExecutable: Bool, isSymlink: Bool, contents: Data?)
case root(children: [DirectoryNode])
var children: [DirectoryNode] {
switch self {
case .directory(_, _, let children): return children
case .file(_, _, _, _): return []
case .root(let children): return children
}
}
var name: String {
switch self {
case .directory(let name, _, _): return name
case .file(let name, _, _, _): return name
case .root(_): return AbsolutePath.root.pathString
}
}
var fileAttributeType: FileAttributeType {
switch self {
case .directory(_, _, _): return .typeDirectory
case .file(_, _, let isSymlink, _): return isSymlink ? .typeSymbolicLink : .typeRegular
case .root(_): return .typeDirectory
}
}
var isDirectory: Bool {
switch self {
case .directory(_, _, _): return true
case .file(_, _, _, _): return false
case .root(_): return true
}
}
var isFile: Bool {
switch self {
case .directory(_, _, _): return false
case .file(_, _, _, _): return true
case .root(_): return false
}
}
var isRoot: Bool {
switch self {
case .directory(_, _, _): return false
case .file(_, _, _, _): return false
case .root(_): return true
}
}
var isSymlink: Bool {
switch self {
case .directory(_, let isSymlink, _): return isSymlink
case .file(_, _, let isSymlink, _): return isSymlink
case .root(_): return false
}
}
}
private enum Errors: Swift.Error, LocalizedError {
case noSuchFileOrDirectory(path: AbsolutePath)
case notAFile(path: AbsolutePath)
case readOnlyFileSystem
case unhandledDirectoryNode(path: AbsolutePath)
public var errorDescription: String? {
switch self {
case .noSuchFileOrDirectory(let path): return "no such file or directory: \(path.pathString)"
case .notAFile(let path): return "not a file: \(path.pathString)"
case .readOnlyFileSystem: return "read-only filesystem"
case .unhandledDirectoryNode(let path): return "unhandled directory node: \(path.pathString)"
}
}
}
private extension FileSystem {
func getDirectoryNodes(_ path: AbsolutePath, includeContents: [AbsolutePath]) throws -> [DirectoryNode] {
return try getDirectoryContents(path).compactMap {
let current = path.appending(component: $0)
let isSymlink = isSymlink(current)
if isFile(current) {
let contents: Data?
if includeContents.contains(current) {
contents = try readFileContents(current)
} else {
contents = nil
}
return .file(name: $0, isExecutable: isExecutableFile(current), isSymlink: isSymlink, contents: contents)
} else if isDirectory(current) {
if $0.hasPrefix(".") { return nil } // we ignore hidden files
return .directory(name: $0, isSymlink: isSymlink, children: try getDirectoryNodes(current, includeContents: includeContents))
} else {
throw Errors.unhandledDirectoryNode(path: current)
}
}
}
}
/// A JSON-backed, read-only virtual file system.
public class VirtualFileSystem: FileSystem {
private let root: DirectoryNode
public init(path: AbsolutePath, fs: FileSystem) throws {
self.root = try JSONDecoder.makeWithDefaults().decode(path: path, fileSystem: fs, as: DirectoryNode.self)
assert(self.root.isRoot, "VFS needs to have a root node")
}
/// Write information about the directory tree at `directoryPath` into a JSON file at `vfsPath`. This can later be used to construct a `VirtualFileSystem` object.
public static func serializeDirectoryTree(_ directoryPath: AbsolutePath, into vfsPath: AbsolutePath, fs: FileSystem, includeContents: [AbsolutePath]) throws {
let data = try JSONEncoder.makeWithDefaults().encode(DirectoryNode.root(children: fs.getDirectoryNodes(directoryPath, includeContents: includeContents)))
try data.write(to: URL(fileURLWithPath: vfsPath.pathString))
}
private func findNode(_ path: AbsolutePath, followSymlink: Bool) -> DirectoryNode? {
var current: DirectoryNode? = self.root
for component in path.components {
if component == AbsolutePath.root.pathString { continue }
guard followSymlink, current?.isSymlink == false else { return nil }
current = current?.children.first(where: { $0.name == component })
}
return current
}
public func exists(_ path: AbsolutePath, followSymlink: Bool) -> Bool {
return findNode(path, followSymlink: followSymlink) != nil
}
public func isDirectory(_ path: AbsolutePath) -> Bool {
return findNode(path, followSymlink: true)?.isDirectory == true
}
public func isFile(_ path: AbsolutePath) -> Bool {
return findNode(path, followSymlink: true)?.isFile == true
}
public func isExecutableFile(_ path: AbsolutePath) -> Bool {
guard let node = findNode(path, followSymlink: true) else { return false }
if case let .file(_, isExecutable, _, _) = node {
return isExecutable
} else {
return false
}
}
public func isSymlink(_ path: AbsolutePath) -> Bool {
return findNode(path, followSymlink: true)?.isSymlink == true
}
public func isReadable(_ path: AbsolutePath) -> Bool {
return self.exists(path)
}
public func isWritable(_ path: AbsolutePath) -> Bool {
return false
}
public func getDirectoryContents(_ path: AbsolutePath) throws -> [String] {
guard let node = findNode(path, followSymlink: true) else { throw Errors.noSuchFileOrDirectory(path: path) }
return node.children.map { $0.name }
}
public var currentWorkingDirectory: AbsolutePath? = nil
public func changeCurrentWorkingDirectory(to path: AbsolutePath) throws {
throw Errors.readOnlyFileSystem
}
public var homeDirectory = AbsolutePath.root
public var cachesDirectory: AbsolutePath? = nil
public var tempDirectory = AbsolutePath.root
public func createSymbolicLink(_ path: AbsolutePath, pointingAt destination: AbsolutePath, relative: Bool) throws {
throw Errors.readOnlyFileSystem
}
public func removeFileTree(_ path: AbsolutePath) throws {
throw Errors.readOnlyFileSystem
}
public func copy(from sourcePath: AbsolutePath, to destinationPath: AbsolutePath) throws {
throw Errors.readOnlyFileSystem
}
public func move(from sourcePath: AbsolutePath, to destinationPath: AbsolutePath) throws {
throw Errors.readOnlyFileSystem
}
public func createDirectory(_ path: AbsolutePath, recursive: Bool) throws {
throw Errors.readOnlyFileSystem
}
public func readFileContents(_ path: AbsolutePath) throws -> ByteString {
guard let node = findNode(path, followSymlink: true) else { throw Errors.noSuchFileOrDirectory(path: path) }
switch node {
case .directory(_, _, _): throw Errors.notAFile(path: path)
case .file(_, _, _, let contents):
if let contents = contents {
return ByteString(contents)
} else {
return ""
}
case .root(_): throw Errors.notAFile(path: path)
}
}
public func writeFileContents(_ path: AbsolutePath, bytes: ByteString) throws {
throw Errors.readOnlyFileSystem
}
public func chmod(_ mode: FileMode, path: AbsolutePath, options: Set<FileMode.Option>) throws {
throw Errors.readOnlyFileSystem
}
public func getFileInfo(_ path: AbsolutePath) throws -> FileInfo {
guard let node = findNode(path, followSymlink: true) else { throw Errors.noSuchFileOrDirectory(path: path) }
let attrs: [FileAttributeKey: Any] = [
.systemNumber: NSNumber(value: UInt64(0)),
.systemFileNumber: UInt64(0),
.posixPermissions: NSNumber(value: Int16(0)),
.type: node.fileAttributeType,
.size: UInt64(0),
.modificationDate: Date(),
]
return FileInfo(attrs)
}
}
| apache-2.0 | 6a3f47b39c9fd4a688b12278d1569eb5 | 35.806452 | 166 | 0.623685 | 4.868267 | false | false | false | false |
Draveness/DKChainableAnimationKit | DKChainableAnimationKit/Classes/DKChainableAnimationKit+Transform.swift | 3 | 8019 | //
// DKChainableAnimationKit+Transform.swift
// DKChainableAnimationKit
//
// Created by Draveness on 15/5/23.
// Copyright (c) 2015年 Draveness. All rights reserved.
//
import UIKit
extension DKChainableAnimationKit {
public var transformIdentity: DKChainableAnimationKit {
get {
self.addAnimationCalculationAction { (view: UIView) -> Void in
let transformAnimation = self.basicAnimationForKeyPath("transform")
let transform = CATransform3DIdentity
transformAnimation.fromValue = NSValue(caTransform3D: view.layer.transform)
transformAnimation.toValue = NSValue(caTransform3D: transform)
self.addAnimationFromCalculationBlock(transformAnimation)
}
self.addAnimationCompletionAction { (view: UIView) -> Void in
let transform = CATransform3DIdentity
view.layer.transform = transform
}
return self
}
}
public func transformX(_ x: CGFloat) -> DKChainableAnimationKit {
self.addAnimationCalculationAction { (view: UIView) -> Void in
let transformAnimation = self.basicAnimationForKeyPath("transform")
var transform = view.layer.transform
transform = CATransform3DTranslate(transform, x, 0, 0)
transformAnimation.fromValue = NSValue(caTransform3D: view.layer.transform)
transformAnimation.toValue = NSValue(caTransform3D: transform)
self.addAnimationFromCalculationBlock(transformAnimation)
}
self.addAnimationCompletionAction { (view: UIView) -> Void in
var transform = view.layer.transform
transform = CATransform3DTranslate(transform, x, 0, 0)
view.layer.transform = transform
}
return self
}
public func transformY(_ y: CGFloat) -> DKChainableAnimationKit {
self.addAnimationCalculationAction { (view: UIView) -> Void in
let transformAnimation = self.basicAnimationForKeyPath("transform")
var transform = view.layer.transform
transform = CATransform3DTranslate(transform, 0, y, 0)
transformAnimation.fromValue = NSValue(caTransform3D: view.layer.transform)
transformAnimation.toValue = NSValue(caTransform3D: transform)
self.addAnimationFromCalculationBlock(transformAnimation)
}
self.addAnimationCompletionAction { (view: UIView) -> Void in
var transform = view.layer.transform
transform = CATransform3DTranslate(transform, 0, y, 0)
view.layer.transform = transform
}
return self
}
public func transformZ(_ z: CGFloat) -> DKChainableAnimationKit {
self.addAnimationCalculationAction { (view: UIView) -> Void in
let transformAnimation = self.basicAnimationForKeyPath("transform")
var transform = view.layer.transform
transform = CATransform3DTranslate(transform, 0, 0, z)
transformAnimation.fromValue = NSValue(caTransform3D: view.layer.transform)
transformAnimation.toValue = NSValue(caTransform3D: transform)
self.addAnimationFromCalculationBlock(transformAnimation)
}
self.addAnimationCompletionAction { (view: UIView) -> Void in
var transform = view.layer.transform
transform = CATransform3DTranslate(transform, 0, 0, z)
view.layer.transform = transform
}
return self
}
public func transformXY(_ x: CGFloat, _ y: CGFloat) -> DKChainableAnimationKit {
self.addAnimationCalculationAction { (view: UIView) -> Void in
let transformAnimation = self.basicAnimationForKeyPath("transform")
var transform = view.layer.transform
transform = CATransform3DTranslate(transform, x, y, 0)
transformAnimation.fromValue = NSValue(caTransform3D: view.layer.transform)
transformAnimation.toValue = NSValue(caTransform3D: transform)
self.addAnimationFromCalculationBlock(transformAnimation)
}
self.addAnimationCompletionAction { (view: UIView) -> Void in
var transform = view.layer.transform
transform = CATransform3DTranslate(transform, x, y, 0)
view.layer.transform = transform
}
return self
}
public func transformScale(_ scale: CGFloat) -> DKChainableAnimationKit {
self.addAnimationCalculationAction { (view: UIView) -> Void in
let transformAnimation = self.basicAnimationForKeyPath("transform")
var transform = view.layer.transform
transform = CATransform3DScale(transform, scale, scale, 1)
transformAnimation.fromValue = NSValue(caTransform3D: view.layer.transform)
transformAnimation.toValue = NSValue(caTransform3D: transform)
self.addAnimationFromCalculationBlock(transformAnimation)
}
self.addAnimationCompletionAction { (view: UIView) -> Void in
var transform = view.layer.transform
transform = CATransform3DScale(transform, scale, scale, 1)
view.layer.transform = transform
}
return self
}
public func transformScaleX(_ scaleX: CGFloat) -> DKChainableAnimationKit {
self.addAnimationCalculationAction { (view: UIView) -> Void in
let transformAnimation = self.basicAnimationForKeyPath("transform")
var transform = view.layer.transform
transform = CATransform3DScale(transform, scaleX, 1, 1)
transformAnimation.fromValue = NSValue(caTransform3D: view.layer.transform)
transformAnimation.toValue = NSValue(caTransform3D: transform)
self.addAnimationFromCalculationBlock(transformAnimation)
}
self.addAnimationCompletionAction { (view: UIView) -> Void in
var transform = view.layer.transform
transform = CATransform3DScale(transform, scaleX, 1, 1)
view.layer.transform = transform
}
return self
}
public func transformScaleY(_ scaleY: CGFloat) -> DKChainableAnimationKit {
self.addAnimationCalculationAction { (view: UIView) -> Void in
let transformAnimation = self.basicAnimationForKeyPath("transform")
var transform = view.layer.transform
transform = CATransform3DScale(transform, 1, scaleY, 1)
transformAnimation.fromValue = NSValue(caTransform3D: view.layer.transform)
transformAnimation.toValue = NSValue(caTransform3D: transform)
self.addAnimationFromCalculationBlock(transformAnimation)
}
self.addAnimationCompletionAction { (view: UIView) -> Void in
var transform = view.layer.transform
transform = CATransform3DScale(transform, 1, scaleY, 1)
view.layer.transform = transform
}
return self
}
public func rotate(_ angle: Double) -> DKChainableAnimationKit {
self.addAnimationCalculationAction { (view: UIView) -> Void in
let rotationAnimation = self.basicAnimationForKeyPath("transform.rotation")
let transform = view.layer.transform
let originalRotation = Double(atan2(transform.m12, transform.m11))
rotationAnimation.fromValue = originalRotation as AnyObject!
rotationAnimation.toValue = (originalRotation + self.degreesToRadians(angle)) as AnyObject!
self.addAnimationFromCalculationBlock(rotationAnimation)
}
self.addAnimationCompletionAction { (view: UIView) -> Void in
let transform = view.layer.transform
let originalRotation = Double(atan2(transform.m12, transform.m11))
let zRotation = CATransform3DMakeRotation(CGFloat(self.degreesToRadians(angle) + originalRotation), 0.0, 0.0, 1.0)
view.layer.transform = zRotation
}
return self
}
}
| mit | 368192ef13ae2ac336b770d4963ed8d1 | 46.720238 | 126 | 0.664214 | 5.155627 | false | false | false | false |
ualch9/onebusaway-iphone | OneBusAway/externals/PromiseKit/Sources/when.swift | 3 | 8770 | import Foundation
import Dispatch
private func _when<T>(_ promises: [Promise<T>]) -> Promise<Void> {
let root = Promise<Void>.pending()
var countdown = promises.count
guard countdown > 0 else {
#if swift(>=4.0)
root.fulfill(())
#else
root.fulfill()
#endif
return root.promise
}
#if PMKDisableProgress || os(Linux)
var progress: (completedUnitCount: Int, totalUnitCount: Int) = (0, 0)
#else
let progress = Progress(totalUnitCount: Int64(promises.count))
progress.isCancellable = false
progress.isPausable = false
#endif
let barrier = DispatchQueue(label: "org.promisekit.barrier.when", attributes: .concurrent)
for promise in promises {
promise.state.pipe { resolution in
barrier.sync(flags: .barrier) {
switch resolution {
case .rejected(let error, let token):
token.consumed = true
if root.promise.isPending {
progress.completedUnitCount = progress.totalUnitCount
root.reject(error)
}
case .fulfilled:
guard root.promise.isPending else { return }
progress.completedUnitCount += 1
countdown -= 1
if countdown == 0 {
#if swift(>=4.0)
root.fulfill(())
#else
root.fulfill()
#endif
}
}
}
}
}
return root.promise
}
/**
Wait for all promises in a set to fulfill.
For example:
when(fulfilled: promise1, promise2).then { results in
//…
}.catch { error in
switch error {
case URLError.notConnectedToInternet:
//…
case CLError.denied:
//…
}
}
- Note: If *any* of the provided promises reject, the returned promise is immediately rejected with that error.
- Warning: In the event of rejection the other promises will continue to resolve and, as per any other promise, will either fulfill or reject. This is the right pattern for `getter` style asynchronous tasks, but often for `setter` tasks (eg. storing data on a server), you most likely will need to wait on all tasks and then act based on which have succeeded and which have failed, in such situations use `when(resolved:)`.
- Parameter promises: The promises upon which to wait before the returned promise resolves.
- Returns: A new promise that resolves when all the provided promises fulfill or one of the provided promises rejects.
- Note: `when` provides `NSProgress`.
- SeeAlso: `when(resolved:)`
*/
public func when<T>(fulfilled promises: [Promise<T>]) -> Promise<[T]> {
return _when(promises).then(on: zalgo) { promises.map{ $0.value! } }
}
/// Wait for all promises in a set to fulfill.
public func when(fulfilled promises: Promise<Void>...) -> Promise<Void> {
return _when(promises)
}
/// Wait for all promises in a set to fulfill.
public func when(fulfilled promises: [Promise<Void>]) -> Promise<Void> {
return _when(promises)
}
/// Wait for all promises in a set to fulfill.
public func when<U, V>(fulfilled pu: Promise<U>, _ pv: Promise<V>) -> Promise<(U, V)> {
return _when([pu.asVoid(), pv.asVoid()]).then(on: zalgo) { (pu.value!, pv.value!) }
}
/// Wait for all promises in a set to fulfill.
public func when<U, V, W>(fulfilled pu: Promise<U>, _ pv: Promise<V>, _ pw: Promise<W>) -> Promise<(U, V, W)> {
return _when([pu.asVoid(), pv.asVoid(), pw.asVoid()]).then(on: zalgo) { (pu.value!, pv.value!, pw.value!) }
}
/// Wait for all promises in a set to fulfill.
public func when<U, V, W, X>(fulfilled pu: Promise<U>, _ pv: Promise<V>, _ pw: Promise<W>, _ px: Promise<X>) -> Promise<(U, V, W, X)> {
return _when([pu.asVoid(), pv.asVoid(), pw.asVoid(), px.asVoid()]).then(on: zalgo) { (pu.value!, pv.value!, pw.value!, px.value!) }
}
/// Wait for all promises in a set to fulfill.
public func when<U, V, W, X, Y>(fulfilled pu: Promise<U>, _ pv: Promise<V>, _ pw: Promise<W>, _ px: Promise<X>, _ py: Promise<Y>) -> Promise<(U, V, W, X, Y)> {
return _when([pu.asVoid(), pv.asVoid(), pw.asVoid(), px.asVoid(), py.asVoid()]).then(on: zalgo) { (pu.value!, pv.value!, pw.value!, px.value!, py.value!) }
}
/**
Generate promises at a limited rate and wait for all to fulfill.
For example:
func downloadFile(url: URL) -> Promise<Data> {
// ...
}
let urls: [URL] = /*…*/
let urlGenerator = urls.makeIterator()
let generator = AnyIterator<Promise<Data>> {
guard url = urlGenerator.next() else {
return nil
}
return downloadFile(url)
}
when(generator, concurrently: 3).then { datum: [Data] -> Void in
// ...
}
- Warning: Refer to the warnings on `when(fulfilled:)`
- Parameter promiseGenerator: Generator of promises.
- Returns: A new promise that resolves when all the provided promises fulfill or one of the provided promises rejects.
- SeeAlso: `when(resolved:)`
*/
public func when<T, PromiseIterator: IteratorProtocol>(fulfilled promiseIterator: PromiseIterator, concurrently: Int) -> Promise<[T]> where PromiseIterator.Element == Promise<T> {
guard concurrently > 0 else {
return Promise(error: PMKError.whenConcurrentlyZero)
}
var generator = promiseIterator
var root = Promise<[T]>.pending()
var pendingPromises = 0
var promises: [Promise<T>] = []
let barrier = DispatchQueue(label: "org.promisekit.barrier.when", attributes: [.concurrent])
func dequeue() {
guard root.promise.isPending else { return } // don’t continue dequeueing if root has been rejected
var shouldDequeue = false
barrier.sync {
shouldDequeue = pendingPromises < concurrently
}
guard shouldDequeue else { return }
var index: Int!
var promise: Promise<T>!
barrier.sync(flags: .barrier) {
guard let next = generator.next() else { return }
promise = next
index = promises.count
pendingPromises += 1
promises.append(next)
}
func testDone() {
barrier.sync {
if pendingPromises == 0 {
root.fulfill(promises.compactMap{ $0.value })
}
}
}
guard promise != nil else {
return testDone()
}
promise.state.pipe { resolution in
barrier.sync(flags: .barrier) {
pendingPromises -= 1
}
switch resolution {
case .fulfilled:
dequeue()
testDone()
case .rejected(let error, let token):
token.consumed = true
root.reject(error)
}
}
dequeue()
}
dequeue()
return root.promise
}
/**
Waits on all provided promises.
`when(fulfilled:)` rejects as soon as one of the provided promises rejects. `when(resolved:)` waits on all provided promises and **never** rejects.
when(resolved: promise1, promise2, promise3).then { results in
for result in results where case .fulfilled(let value) {
//…
}
}.catch { error in
// invalid! Never rejects
}
- Returns: A new promise that resolves once all the provided promises resolve.
- Warning: The returned promise can *not* be rejected.
- Note: Any promises that error are implicitly consumed, your UnhandledErrorHandler will not be called.
*/
public func when<T>(resolved promises: Promise<T>...) -> Promise<[Result<T>]> {
return when(resolved: promises)
}
/// Waits on all provided promises.
public func when<T>(resolved promises: [Promise<T>]) -> Promise<[Result<T>]> {
guard !promises.isEmpty else { return Promise(value: []) }
var countdown = promises.count
let barrier = DispatchQueue(label: "org.promisekit.barrier.join", attributes: .concurrent)
return Promise { fulfill, reject in
for promise in promises {
promise.state.pipe { resolution in
if case .rejected(_, let token) = resolution {
token.consumed = true // all errors are implicitly consumed
}
var done = false
barrier.sync(flags: .barrier) {
countdown -= 1
done = countdown == 0
}
if done {
fulfill(promises.map { Result($0.state.get()!) })
}
}
}
}
}
| apache-2.0 | f284c74a74d275f232bc851f4ab39b2e | 33.077821 | 424 | 0.585864 | 4.310039 | false | false | false | false |
LawrenceHan/iOS-project-playground | RanchForecastSplit/RanchForecastSplit/ScheduleFetcher.swift | 2 | 4113 | //
// ScheduleFetcher.swift
// RanchForecast
//
// Created by Hanguang on 1/2/16.
// Copyright © 2016 Hanguang. All rights reserved.
//
import Cocoa
public class ScheduleFetcher {
public enum FetchCoursesResult {
case Success([Course])
case Failure(NSError)
init(throwingClosure: () throws -> [Course]) {
do {
let courses = try throwingClosure()
self = .Success(courses)
}
catch {
self = .Failure(error as NSError)
}
}
}
let session: NSURLSession
public init() {
let config = NSURLSessionConfiguration.defaultSessionConfiguration()
session = NSURLSession(configuration: config)
}
func fetchCoursesUsingCompletionHandler(completionHandler: FetchCoursesResult -> Void) {
let url = NSURL(string: "http://bookapi.bignerdranch.com/courses.json")!
let request = NSURLRequest(URL: url)
let task = session.dataTaskWithRequest(request) { data, response, error in
let result: FetchCoursesResult
= self.resultFromData(data, response: response, error: error)
NSOperationQueue.mainQueue().addOperationWithBlock {
completionHandler(result)
}
}
task.resume()
}
func errorWithCode(code: Int, localizedDescription: String) -> NSError {
return NSError(domain: "ScheduleFetcher", code: code, userInfo: [NSLocalizedDescriptionKey : localizedDescription])
}
public func courseFromDictionary(courseDict: NSDictionary) -> Course? {
if let title = courseDict["title"] as? String,
let urlString = courseDict["url"] as? String,
let upcomingArray = courseDict["upcoming"] as? [NSDictionary],
let nextUpcomingDict = upcomingArray.first,
let nextStartDateString = nextUpcomingDict["start_date"] as? String {
let url = NSURL(string: urlString)!
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
let nextStartDate = dateFormatter.dateFromString(nextStartDateString)!
return Course(title: title, url: url, nextStartDate: nextStartDate)
}
return nil
}
func coursesFromData(data: NSData) throws -> [Course] {
let topLevelDict = try NSJSONSerialization.JSONObjectWithData(data,
options: [])
as! NSDictionary
let courseDicts = topLevelDict["courses"] as! [NSDictionary]
var courses: [Course] = []
for courseDict in courseDicts {
if let course = courseFromDictionary(courseDict) {
courses.append(course)
}
}
return courses
}
public func resultFromData(data: NSData?, response: NSURLResponse?, error: NSError?)
-> FetchCoursesResult {
let result: FetchCoursesResult
if let data = data {
if let response = response as? NSHTTPURLResponse {
print("\(data.length) bytes, HTTP \(response.statusCode).")
if response.statusCode == 200 {
result = FetchCoursesResult { try self.coursesFromData(data) }
}
else {
let error =
self.errorWithCode(2, localizedDescription:
"Bad status code \(response.statusCode)")
result = .Failure(error)
}
}
else {
let error =
self.errorWithCode(1, localizedDescription:
"Unexpected response object.")
result = .Failure(error)
}
}
else {
result = .Failure(error!)
}
return result
}
}
| mit | fee78a5e01533139949ba455f41e2991 | 33.554622 | 123 | 0.540613 | 5.579376 | false | false | false | false |
inamiy/RxAutomaton | Demo/ViewController.swift | 1 | 5805 | //
// ViewController.swift
// RxAutomatonDemo
//
// Created by Yasuhiro Inami on 2016-08-15.
// Copyright © 2016 Yasuhiro Inami. All rights reserved.
//
import UIKit
import RxSwift
import RxCocoa
import RxAutomaton
import Pulsator
class AutomatonViewController: UIViewController
{
@IBOutlet weak var diagramView: UIImageView?
@IBOutlet weak var label: UILabel?
@IBOutlet weak var loginButton: UIButton?
@IBOutlet weak var logoutButton: UIButton?
@IBOutlet weak var forceLogoutButton: UIButton?
private var pulsator: Pulsator?
private var _automaton: Automaton<State, Input>?
private let _disposeBag = DisposeBag()
override func viewDidLoad()
{
super.viewDidLoad()
let (textSignal, textObserver) = Observable<String?>.pipe()
/// Count-up effect.
func countUpProducer(status: String, count: Int = 4, interval: TimeInterval = 1, nextInput: Input) -> Observable<Input>
{
return Observable<Int>.interval(interval, scheduler: MainScheduler.instance)
.take(count)
.scan(0) { x, _ in x + 1 }
.startWith(0)
.map {
switch $0 {
case 0: return "\(status)..."
case count: return "\(status) Done!"
default: return "\(status)... (\($0))"
}
}
.do(onNext: textObserver.onNext)
.then(value: nextInput)
}
let loginOKProducer = countUpProducer(status: "Login", nextInput: .loginOK)
let logoutOKProducer = countUpProducer(status: "Logout", nextInput: .logoutOK)
let forceLogoutOKProducer = countUpProducer(status: "ForceLogout", nextInput: .logoutOK)
// NOTE: predicate style i.e. `T -> Bool` is also available.
let canForceLogout: (State) -> Bool = [.loggingIn, .loggedIn].contains
/// Transition mapping.
let mappings: [Automaton<State, Input>.EffectMapping] = [
/* Input | fromState => toState | Effect */
/* ----------------------------------------------------------*/
.login | .loggedOut => .loggingIn | loginOKProducer,
.loginOK | .loggingIn => .loggedIn | .empty(),
.logout | .loggedIn => .loggingOut | logoutOKProducer,
.logoutOK | .loggingOut => .loggedOut | .empty(),
.forceLogout | canForceLogout => .loggingOut | forceLogoutOKProducer
]
let (inputSignal, inputObserver) = Observable<Input>.pipe()
let automaton = Automaton(state: .loggedOut, input: inputSignal, mapping: reduce(mappings), strategy: .latest)
self._automaton = automaton
automaton.replies
.subscribe(onNext: { reply in
print("received reply = \(reply)")
})
.disposed(by: _disposeBag)
automaton.state.asObservable()
.subscribe(onNext: { state in
print("current state = \(state)")
})
.disposed(by: _disposeBag)
// Setup buttons.
do {
self.loginButton?.rx.tap
.subscribe(onNext: { _ in inputObserver.onNext(.login) })
.disposed(by: _disposeBag)
self.logoutButton?.rx.tap
.subscribe(onNext: { _ in inputObserver.onNext(.logout) })
.disposed(by: _disposeBag)
self.forceLogoutButton?.rx.tap
.subscribe(onNext: { _ in inputObserver.onNext(.forceLogout) })
.disposed(by: _disposeBag)
}
// Setup label.
do {
textSignal
.bind(to: self.label!.rx.text)
.disposed(by: _disposeBag)
}
// Setup Pulsator.
do {
let pulsator = _createPulsator()
self.pulsator = pulsator
self.diagramView?.layer.addSublayer(pulsator)
automaton.state.asDriver()
.map(_pulsatorColor)
.map { $0.cgColor }
.drive(pulsator.rx_backgroundColor)
.disposed(by: _disposeBag)
automaton.state.asDriver()
.map(_pulsatorPosition)
.drive(pulsator.rx_position)
.disposed(by: _disposeBag)
// Overwrite the pulsator color to red if `.forceLogout` succeeded.
automaton.replies
.filter { $0.toState != nil && $0.input == .forceLogout }
.map { _ in UIColor.red.cgColor }
.bind(to: pulsator.rx_backgroundColor)
.disposed(by: _disposeBag)
}
}
}
// MARK: Pulsator
private func _createPulsator() -> Pulsator
{
let pulsator = Pulsator()
pulsator.numPulse = 5
pulsator.radius = 100
pulsator.animationDuration = 7
pulsator.backgroundColor = UIColor(red: 0, green: 0.455, blue: 0.756, alpha: 1).cgColor
pulsator.start()
return pulsator
}
private func _pulsatorPosition(state: State) -> CGPoint
{
switch state {
case .loggedOut: return CGPoint(x: 40, y: 100)
case .loggingIn: return CGPoint(x: 190, y: 20)
case .loggedIn: return CGPoint(x: 330, y: 100)
case .loggingOut: return CGPoint(x: 190, y: 180)
}
}
private func _pulsatorColor(state: State) -> UIColor
{
switch state {
case .loggedOut:
return UIColor(red: 0, green: 0.455, blue: 0.756, alpha: 1) // blue
case .loggingIn, .loggingOut:
return UIColor(red: 0.97, green: 0.82, blue: 0.30, alpha: 1) // yellow
case .loggedIn:
return UIColor(red: 0.50, green: 0.85, blue: 0.46, alpha: 1) // green
}
}
| mit | 4bb45b4cb83444a35ea295c950ad33b8 | 31.606742 | 127 | 0.552895 | 4.315242 | false | false | false | false |
yonekawa/SwiftFlux | SwiftFlux/Dispatcher.swift | 1 | 3280 | //
// Dispatcher.swift
// SwiftFlux
//
// Created by Kenichi Yonekawa on 7/31/15.
// Copyright (c) 2015 mog2dev. All rights reserved.
//
import Foundation
import Result
public typealias DispatchToken = String
public protocol Dispatcher {
func dispatch<T: Action>(action: T, result: Result<T.Payload, T.Error>)
func register<T: Action>(type: T.Type, handler: (Result<T.Payload, T.Error>) -> ()) -> DispatchToken
func unregister(dispatchToken: DispatchToken)
func waitFor<T: Action>(dispatchTokens: [DispatchToken], type: T.Type, result: Result<T.Payload, T.Error>)
}
public class DefaultDispatcher: Dispatcher {
internal enum Status {
case Waiting
case Pending
case Handled
}
private var callbacks: [DispatchToken: AnyObject] = [:]
public init() {}
deinit {
callbacks.removeAll()
}
public func dispatch<T: Action>(action: T, result: Result<T.Payload, T.Error>) {
dispatch(action.dynamicType, result: result)
}
public func register<T: Action>(type: T.Type, handler: (Result<T.Payload, T.Error>) -> Void) -> DispatchToken {
let nextDispatchToken = NSUUID().UUIDString
callbacks[nextDispatchToken] = DispatchCallback<T>(type: type, handler: handler)
return nextDispatchToken
}
public func unregister(dispatchToken: DispatchToken) {
callbacks.removeValueForKey(dispatchToken)
}
public func waitFor<T: Action>(dispatchTokens: [DispatchToken], type: T.Type, result: Result<T.Payload, T.Error>) {
for dispatchToken in dispatchTokens {
guard let callback = callbacks[dispatchToken] as? DispatchCallback<T> else { continue }
switch callback.status {
case .Handled:
continue
case .Pending:
// Circular dependency detected while
continue
default:
invokeCallback(dispatchToken, type: type, result: result)
}
}
}
private func dispatch<T: Action>(type: T.Type, result: Result<T.Payload, T.Error>) {
objc_sync_enter(self)
startDispatching(type)
for dispatchToken in callbacks.keys {
invokeCallback(dispatchToken, type: type, result: result)
}
objc_sync_exit(self)
}
private func startDispatching<T: Action>(type: T.Type) {
for (dispatchToken, _) in callbacks {
guard let callback = callbacks[dispatchToken] as? DispatchCallback<T> else { continue }
callback.status = .Waiting
}
}
private func invokeCallback<T: Action>(dispatchToken: DispatchToken, type: T.Type, result: Result<T.Payload, T.Error>) {
guard let callback = callbacks[dispatchToken] as? DispatchCallback<T> else { return }
guard callback.status == .Waiting else { return }
callback.status = .Pending
callback.handler(result)
callback.status = .Handled
}
}
private class DispatchCallback<T: Action> {
let type: T.Type
let handler: (Result<T.Payload, T.Error>) -> ()
var status = DefaultDispatcher.Status.Waiting
init(type: T.Type, handler: (Result<T.Payload, T.Error>) -> ()) {
self.type = type
self.handler = handler
}
}
| mit | c8b7f377c5145b936d21e826ddd3c4a4 | 31.156863 | 124 | 0.637805 | 4.162437 | false | false | false | false |
AlexeyBelezeko/SwiftTinyRender | swiftRenderer/NSScanner+Swift.swift | 1 | 4355 | // NSScanner+Swift.swift
// A set of Swift-idiomatic methods for NSScanner
//
// (c) 2015 Nate Cook, licensed under the MIT license
import Foundation
extension NSScanner {
// MARK: Strings
/// Returns a string, scanned as long as characters from a given character set are encountered, or `nil` if none are found.
func scanCharactersFromSet(set: NSCharacterSet) -> String? {
var value: NSString? = ""
if scanCharactersFromSet(set, intoString: &value),
let value = value as? String {
return value
}
return nil
}
/// Returns a string, scanned until a character from a given character set are encountered, or the remainder of the scanner's string. Returns `nil` if the scanner is already `atEnd`.
func scanUpToCharactersFromSet(set: NSCharacterSet) -> String? {
var value: NSString? = ""
if scanUpToCharactersFromSet(set, intoString: &value),
let value = value as? String {
return value
}
return nil
}
/// Returns the given string if scanned, or `nil` if not found.
func scanString(str: String) -> String? {
var value: NSString? = ""
if scanString(str, intoString: &value),
let value = value as? String {
return value
}
return nil
}
/// Returns a string, scanned until the given string is found, or the remainder of the scanner's string. Returns `nil` if the scanner is already `atEnd`.
func scanUpToString(str: String) -> String? {
var value: NSString? = ""
if scanUpToString(str, intoString: &value),
let value = value as? String {
return value
}
return nil
}
// MARK: Numbers
/// Returns a Double if scanned, or `nil` if not found.
func scanDouble() -> Double? {
var value = 0.0
if scanDouble(&value) {
return value
}
return nil
}
/// Returns a Float if scanned, or `nil` if not found.
func scanFloat() -> Float? {
var value: Float = 0.0
if scanFloat(&value) {
return value
}
return nil
}
/// Returns an Int if scanned, or `nil` if not found.
func scanInteger() -> Int? {
var value = 0
if scanInteger(&value) {
return value
}
return nil
}
/// Returns an Int32 if scanned, or `nil` if not found.
func scanInt() -> Int32? {
var value: Int32 = 0
if scanInt(&value) {
return value
}
return nil
}
/// Returns an Int64 if scanned, or `nil` if not found.
func scanLongLong() -> Int64? {
var value: Int64 = 0
if scanLongLong(&value) {
return value
}
return nil
}
/// Returns a UInt64 if scanned, or `nil` if not found.
func scanUnsignedLongLong() -> UInt64? {
var value: UInt64 = 0
if scanUnsignedLongLong(&value) {
return value
}
return nil
}
/// Returns an NSDecimal if scanned, or `nil` if not found.
func scanDecimal() -> NSDecimal? {
var value = NSDecimal()
if scanDecimal(&value) {
return value
}
return nil
}
// MARK: Hex Numbers
/// Returns a Double if scanned in hexadecimal, or `nil` if not found.
func scanHexDouble() -> Double? {
var value = 0.0
if scanHexDouble(&value) {
return value
}
return nil
}
/// Returns a Float if scanned in hexadecimal, or `nil` if not found.
func scanHexFloat() -> Float? {
var value: Float = 0.0
if scanHexFloat(&value) {
return value
}
return nil
}
/// Returns a UInt32 if scanned in hexadecimal, or `nil` if not found.
func scanHexInt() -> UInt32? {
var value: UInt32 = 0
if scanHexInt(&value) {
return value
}
return nil
}
/// Returns a UInt64 if scanned in hexadecimal, or `nil` if not found.
func scanHexLongLong() -> UInt64? {
var value: UInt64 = 0
if scanHexLongLong(&value) {
return value
}
return nil
}
}
| mit | fd076a3a5495e40f2d7ddd05fe4f024d | 27.279221 | 186 | 0.547646 | 4.642857 | false | false | false | false |
dehesa/Metal | books/03 - DrawingIn2D/Sources/macOS/AppDelegate.swift | 1 | 2071 | import Cocoa
extension App {
/// The delegate for this application. It receives the app events and forwards them to the window controller or SwiftUI.
final class Delegate: NSObject {
/// The main application window.
private let _window: NSWindow
override init() {
let size = (default: NSSize(width: 900, height: 600),
minimum: NSSize(width: 300, height: 300))
let mask: NSWindow.StyleMask = [.titled, .closable, .miniaturizable, .resizable]
self._window = NSWindow(contentRect: .init(origin: .zero, size: size.default), styleMask: mask, backing: .buffered, defer: false).set {
$0.minSize = size.minimum
$0.appearance = NSAppearance(named: .darkAqua)
$0.title = "\(App.name) - Clear Screen"
$0.isReleasedWhenClosed = false
}
super.init()
self._window.delegate = self
}
}
}
extension App.Delegate: NSApplicationDelegate {
func applicationDidFinishLaunching(_ notification: Notification) {
NSApp.mainMenu = NSMenu().set {
$0.addItem(NSMenuItem(title: App.name, action: nil, keyEquivalent: "").set {
$0.submenu = NSMenu(title: App.name).set {
$0.addItem(withTitle: "Hide window", action: #selector(NSApplication.hide(_:)), keyEquivalent: "h")
$0.addItem(withTitle: "Show All", action: #selector(NSApplication.unhideAllApplications(_:)), keyEquivalent: "")
$0.addItem(.separator())
$0.addItem(withTitle: "Quit sample code", action: #selector(NSApplication.terminate(_:)), keyEquivalent: "q")
}
})
}
guard let device = MTLCreateSystemDefaultDevice(),
let queue = device.makeCommandQueue() else { fatalError() }
self._window.contentView = MetalView(frame: self._window.contentLayoutRect, device: device, queue: queue)
self._window.center()
self._window.makeKeyAndOrderFront(self)
NSApp.activate(ignoringOtherApps: true)
}
}
extension App.Delegate: NSWindowDelegate {
func windowWillClose(_ notification: Notification) {
NSApp.terminate(self)
}
}
| mit | aac5c5f996976d530efcefa17cc92ae3 | 38.826923 | 141 | 0.665379 | 4.305613 | false | false | false | false |
mlibai/XZKit | Projects/Example/XZKitExample/XZKitExample/XZKitExample/Code/LaunchViewController.swift | 1 | 2369 | //
// AdvertisementViewController.swift
// XZKit
//
// Created by mlibai on 2017/8/8.
// Copyright © 2017年 mlibai. All rights reserved.
//
import UIKit
import XZKit
open class LaunchViewController: UIViewController {
unowned let rootViewController: UIViewController
public init(rootViewController: UIViewController) {
self.rootViewController = rootViewController
super.init(nibName: nil, bundle: nil)
addChild(rootViewController)
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
open var advertisementView: AdvertisementView = AdvertisementView()
open override func viewDidLoad() {
super.viewDidLoad()
advertisementView.contentInsets = UIEdgeInsets(top: 0, left: 0, bottom: 127, right: 0)
advertisementView.frame = view.bounds
advertisementView.autoresizingMask = [.flexibleHeight, .flexibleWidth]
view.addSubview(advertisementView)
advertisementView.timerButton.addTarget(self, action: #selector(timerButtonWasTimeout(_:)), for: [.touchUpInside, .timeout])
advertisementView.advertisementImageView.image = #imageLiteral(resourceName: "20170704142100")
}
open override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
advertisementView.timerButton.timekeeper.duration = 10
advertisementView.timerButton.timekeeper.resume()
}
@objc private func timerButtonWasTimeout(_ timerButton: TimerButton) {
advertisementWasTimeout()
}
open func advertisementWasTimeout() {
let bounds = view.bounds
rootViewController.view.frame = bounds
rootViewController.view.autoresizingMask = [.flexibleWidth, .flexibleHeight]
view.insertSubview(rootViewController.view, at: 0)
UIView.animate(withDuration: 0.5, animations: {
self.advertisementView.frame = bounds.offsetBy(dx: 0, dy: -bounds.height)
}) { (finished) in
self.advertisementView.isHidden = true
}
}
}
extension LaunchViewController {
open override func didRecevieRedirection(_ redirection: Any) -> UIViewController? {
print(redirection)
return nil
}
}
| mit | 28cd3c366e5de48309434485d99ab97a | 29.727273 | 132 | 0.669062 | 5.012712 | false | false | false | false |
nathawes/swift | test/ClangImporter/availability_implicit_macosx.swift | 19 | 4417 | // RUN: %swift -typecheck -verify -target %target-cpu-apple-macosx10.51 %clang-importer-sdk -I %S/Inputs/custom-modules %s %S/Inputs/availability_implicit_macosx_other.swift
// RUN: not %swift -typecheck -target %target-cpu-apple-macosx10.51 %clang-importer-sdk -I %S/Inputs/custom-modules %s %S/Inputs/availability_implicit_macosx_other.swift 2>&1 | %FileCheck %s '--implicit-check-not=<unknown>:0'
// REQUIRES: OS=macosx
// This is a temporary test for checking of availability diagnostics (explicit unavailability,
// deprecation, and potential unavailability) in synthesized code. After this checking
// is fully staged in, the tests in this file will be moved.
//
import Foundation
func useClassThatTriggersImportOfDeprecatedEnum() {
// Check to make sure that the bodies of enum methods that are synthesized
// when importing deprecated enums do not themselves trigger deprecation
// warnings in the synthesized code.
_ = NSClassWithDeprecatedOptionsInMethodSignature.sharedInstance()
}
func useClassThatTriggersImportOExplicitlyUnavailableOptions() {
_ = NSClassWithPotentiallyUnavailableOptionsInMethodSignature.sharedInstance()
}
func useClassThatTriggersImportOfPotentiallyUnavailableOptions() {
_ = NSClassWithExplicitlyUnavailableOptionsInMethodSignature.sharedInstance()
}
func directUseShouldStillTriggerDeprecationWarning() {
_ = NSDeprecatedOptions.first // expected-warning {{'NSDeprecatedOptions' was deprecated in macOS 10.51: Use a different API}}
_ = NSDeprecatedEnum.first // expected-warning {{'NSDeprecatedEnum' was deprecated in macOS 10.51: Use a different API}}
}
func useInSignature(_ options: NSDeprecatedOptions) { // expected-warning {{'NSDeprecatedOptions' was deprecated in macOS 10.51: Use a different API}}
}
class SuperClassWithDeprecatedInitializer {
@available(OSX, introduced: 10.9, deprecated: 10.51)
init() { }
}
class SubClassWithSynthesizedDesignedInitializerOverride : SuperClassWithDeprecatedInitializer {
// The synthesized designated initializer override calls super.init(), which is
// deprecated, so the synthesized initializer is marked as deprecated as well.
// This does not generate a warning here (perhaps it should?) but any call
// to Sub's initializer will cause a deprecation warning.
}
func callImplicitInitializerOnSubClassWithSynthesizedDesignedInitializerOverride() {
_ = SubClassWithSynthesizedDesignedInitializerOverride() // expected-warning {{'init()' was deprecated in macOS 10.51}}
}
@available(OSX, introduced: 10.9, deprecated: 10.51)
class NSDeprecatedSuperClass {
var i : Int = 7 // Causes initializer to be synthesized
}
class NotDeprecatedSubClassOfDeprecatedSuperClass : NSDeprecatedSuperClass { // expected-warning {{'NSDeprecatedSuperClass' was deprecated in macOS 10.51}}
}
func callImplicitInitializerOnNotDeprecatedSubClassOfDeprecatedSuperClass() {
// We do not expect a warning here because the synthesized initializer
// in NotDeprecatedSubClassOfDeprecatedSuperClass is not itself marked
// deprecated.
_ = NotDeprecatedSubClassOfDeprecatedSuperClass()
}
@available(OSX, introduced: 10.9, deprecated: 10.51)
class NSDeprecatedSubClassOfDeprecatedSuperClass : NSDeprecatedSuperClass {
}
// Tests synthesis of materializeForSet
class ClassWithLimitedAvailabilityAccessors {
var limitedGetter: Int {
@available(OSX, introduced: 10.52)
get { return 10 }
set(newVal) {}
}
var limitedSetter: Int {
get { return 10 }
@available(OSX, introduced: 10.52)
set(newVal) {}
}
}
@available(*, unavailable)
func unavailableFunction() -> Int { return 10 } // expected-note 3{{'unavailableFunction()' has been explicitly marked unavailable here}}
class ClassWithReferencesLazyInitializers {
var propWithUnavailableInInitializer: Int = unavailableFunction() // expected-error {{'unavailableFunction()' is unavailable}}
lazy var lazyPropWithUnavailableInInitializer: Int = unavailableFunction() // expected-error {{'unavailableFunction()' is unavailable}}
}
@available(*, unavailable)
func unavailableUseInUnavailableFunction() {
// Diagnose references to unavailable functions in non-implicit code
// as errors
unavailableFunction() // expected-error {{'unavailableFunction()' is unavailable}} expected-warning {{result of call to 'unavailableFunction()' is unused}}
}
@available(OSX 10.52, *)
func foo() {
let _ = SubOfOtherWithInit()
}
| apache-2.0 | 9754a0a541605dee5c1f376f88281a6a | 39.522936 | 225 | 0.776092 | 4.421421 | false | false | false | false |
Verchen/Swift-Project | JinRong/JinRong/Classes/Authentication(认证)/Controller/IdentityAuthVC.swift | 1 | 3510 | //
// IdentityAuthVC.swift
// JinRong
//
// Created by 乔伟成 on 2017/7/18.
// Copyright © 2017年 乔伟成. All rights reserved.
//
import UIKit
class IdentityAuthVC: BaseController {
override func viewDidLoad() {
super.viewDidLoad()
title = "身份认证"
setupUI()
setupLayout()
}
func setupUI() -> Void {
view.addSubview(upImage)
view.addSubview(downImage)
view.addSubview(handImage)
view.addSubview(name)
view.addSubview(carNum)
view.addSubview(commit)
}
func setupLayout() -> Void {
upImage.snp.makeConstraints { (make) in
make.left.top.equalTo(20)
make.right.equalTo(downImage.snp.left).offset(-20)
make.height.equalTo(90)
}
downImage.snp.makeConstraints { (make) in
make.left.equalTo(upImage.snp.right).offset(20)
make.top.equalTo(20)
make.right.equalTo(-20)
make.width.equalTo(upImage)
make.height.equalTo(upImage)
}
handImage.snp.makeConstraints { (make) in
make.left.equalTo(20)
make.top.equalTo(upImage.snp.bottom).offset(10)
make.right.equalTo(-20)
make.height.equalTo(150)
}
name.snp.makeConstraints { (make) in
make.left.equalTo(20)
make.top.equalTo(handImage.snp.bottom).offset(10)
make.right.equalTo(-20)
make.height.equalTo(35)
}
carNum.snp.makeConstraints { (make) in
make.left.equalTo(20)
make.top.equalTo(name.snp.bottom).offset(10)
make.right.equalTo(-20)
make.height.equalTo(35)
}
commit.snp.makeConstraints { (make) in
make.left.equalTo(20)
make.top.equalTo(carNum.snp.bottom).offset(20)
make.right.equalTo(-20)
make.height.equalTo(35)
}
}
//MARK: - 事件方法
func commitClick() -> Void {
navigationController?.popViewController(animated: true)
}
//MARK: - 懒加载
lazy var upImage: UIImageView = {
let up = UIImageView()
up.image = #imageLiteral(resourceName: "placeholder.png")
return up
}()
lazy var downImage: UIImageView = {
let down = UIImageView()
down.image = #imageLiteral(resourceName: "placeholder.png")
return down
}()
lazy var handImage: UIImageView = {
let hand = UIImageView()
hand.image = #imageLiteral(resourceName: "placeholder.png")
return hand
}()
lazy var name: UILabel = {
let nam = UILabel()
nam.backgroundColor = UIColor.init(valueRGB: 0xCCCCCC)
nam.textColor = UIColor.init(valueRGB: 0x6B6B6B)
nam.text = "张某某"
nam.textAlignment = .center
return nam
}()
lazy var carNum: UILabel = {
let num = UILabel()
num.backgroundColor = UIColor.init(valueRGB: 0xCCCCCC)
num.textColor = UIColor.init(valueRGB: 0x6B6B6B)
num.text = "621661*****9012"
num.textAlignment = .center
return num
}()
lazy var commit: UIButton = {
let btn = UIButton(type: .custom)
btn.backgroundColor = UIColor.theme
btn.setTitle("提交认证", for: .normal)
btn.addTarget(self, action: #selector(IdentityAuthVC.commitClick), for: .touchUpInside)
return btn
}()
}
| mit | d72d6613f8149a73a82ef7cb9defb0a7 | 28.067227 | 95 | 0.572709 | 4.012761 | false | false | false | false |
MetalPetal/MetalPetal | Frameworks/MetalPetal/MTIPixelFormat.swift | 1 | 536 | //
// MTIPixelFormat.swift
// Pods
//
// Created by Yu Ao on 2018/11/8.
//
import Metal
#if SWIFT_PACKAGE
import MetalPetalObjectiveC.Core
#endif
extension MTLPixelFormat {
public static let unspecified = MTLPixelFormat.invalid
public static let yCbCr8_420_2p = __MTIPixelFormatYCBCR8_420_2P
public static let yCbCr8_420_2p_srgb = __MTIPixelFormatYCBCR8_420_2P_sRGB
public static let yCbCr10_420_2p = __MTIPixelFormatYCBCR10_420_2P
public static let yCbCr10_420_2p_srgb = __MTIPixelFormatYCBCR10_420_2P_sRGB
}
| mit | 89fc8edad2aa3ba000e8f78bb41c9f1a | 25.8 | 79 | 0.744403 | 2.88172 | false | false | false | false |
RyanTech/AwesomeCache | AwesomeCache/Cache.swift | 5 | 8794 | //
// Cache.swift
// Example
//
// Created by Alexander Schuch on 12/07/14.
// Copyright (c) 2014 Alexander Schuch. All rights reserved.
//
import Foundation
/**
* Represents the expiry of a cached object
*/
public enum CacheExpiry {
case Never
case Seconds(NSTimeInterval)
case Date(NSDate)
}
/**
* A generic cache that persists objects to disk and is backed by a NSCache.
* Supports an expiry date for every cached object. Expired objects are automatically deleted upon their next access via `objectForKey:`.
* If you want to delete expired objects, call `removeAllExpiredObjects`.
*
* Subclassing notes: This class fully supports subclassing.
* The easiest way to implement a subclass is to override `objectForKey` and `setObject:forKey:expires:`, e.g. to modify values prior to reading/writing to the cache.
*/
public class Cache<T: NSCoding> {
public let name: String
public let cacheDirectory: String
private let cache = NSCache()
private let fileManager = NSFileManager()
private let diskWriteQueue: dispatch_queue_t = dispatch_queue_create("com.aschuch.cache.diskWriteQueue", DISPATCH_QUEUE_SERIAL)
private let diskReadQueue: dispatch_queue_t = dispatch_queue_create("com.aschuch.cache.diskReadQueue", DISPATCH_QUEUE_SERIAL)
// MARK: Initializers
/**
* Designated initializer.
*
* @param name Name of this cache
* @param directory Objects in this cache are persisted to this directory.
* If no directory is specified, a new directory is created in the system's Caches directory
*
* @return A new cache with the given name and directory
*
*/
public init(name: String, directory: String?) {
self.name = name
cache.name = name
if let d = directory {
cacheDirectory = d
} else {
let dir = NSSearchPathForDirectoriesInDomains(.CachesDirectory, .UserDomainMask, true).first as! String
cacheDirectory = dir.stringByAppendingFormat("/com.aschuch.cache/%@", name)
}
// Create directory on disk
if !fileManager.fileExistsAtPath(cacheDirectory) {
fileManager.createDirectoryAtPath(cacheDirectory, withIntermediateDirectories: true, attributes: nil, error: nil)
}
}
/**
* @param name Name of this cache
*
* @return A new cache with the given name and the default cache directory
*/
public convenience init(name: String) {
self.init(name: name, directory: nil)
}
// MARK: Awesome caching
/**
* Returns a cached object immediately or evaluates a cacheBlock. The cacheBlock will not be re-evaluated until the object is expired or manually deleted.
*
* If the cache already contains an object, the completion block is called with the cached object immediately.
*
* If no object is found or the cached object is already expired, the `cacheBlock` is called.
* You might perform any tasks (e.g. network calls) within this block. Upon completion of these tasks, make sure to call the `success` or `failure` block that is passed to the `cacheBlock`.
* The completion block is invoked as soon as the cacheBlock is finished and the object is cached.
*
* @param key The key to lookup the cached object
* @param cacheBlock This block gets called if there is no cached object or the cached object is already expired.
* The supplied success or failure blocks must be called upon completion.
* If the error block is called, the object is not cached and the completion block is invoked with this error.
* @param completion Called as soon as a cached object is available to use. The second parameter is true if the object was already cached.
*/
public func setObjectForKey(key: String, cacheBlock: ((T, CacheExpiry) -> (), (NSError?) -> ()) -> (), completion: (T?, Bool, NSError?) -> ()) {
if let object = objectForKey(key) {
completion(object, true, nil)
} else {
let successBlock: (T, CacheExpiry) -> () = { (obj, expires) in
self.setObject(obj, forKey: key, expires: expires)
completion(obj, false, nil)
}
let failureBlock: (NSError?) -> () = { (error) in
completion(nil, false, error)
}
cacheBlock(successBlock, failureBlock)
}
}
// MARK: Get object
/**
* Looks up and returns an object with the specified name if it exists.
* If an object is already expired, it is automatically deleted and `nil` will be returned.
*
* @param name The name of the object that should be returned
* @return The cached object for the given name, or nil
*/
public func objectForKey(key: String) -> T? {
var possibleObject: CacheObject?
// Check if object exists in local cache
possibleObject = cache.objectForKey(key) as? CacheObject
if possibleObject == nil {
// Try to load object from disk (synchronously)
dispatch_sync(diskReadQueue) {
let path = self.pathForKey(key)
if self.fileManager.fileExistsAtPath(path) {
possibleObject = NSKeyedUnarchiver.unarchiveObjectWithFile(path) as? CacheObject
}
}
}
// Check if object is not already expired and return
// Delete object if expired
if let object = possibleObject {
if !object.isExpired() {
return object.value as? T
} else {
removeObjectForKey(key)
}
}
return nil
}
// MARK: Set object
/**
* Adds a given object to the cache.
*
* @param object The object that should be cached
* @param forKey A key that represents this object in the cache
*/
public func setObject(object: T, forKey key: String) {
self.setObject(object, forKey: key, expires: .Never)
}
/**
* Adds a given object to the cache.
* The object is automatically marked as expired as soon as its expiry date is reached.
*
* @param object The object that should be cached
* @param forKey A key that represents this object in the cache
*/
public func setObject(object: T, forKey key: String, expires: CacheExpiry) {
let expiryDate = expiryDateForCacheExpiry(expires)
let cacheObject = CacheObject(value: object, expiryDate: expiryDate)
// Set object in local cache
cache.setObject(cacheObject, forKey: key)
// Write object to disk (asyncronously)
dispatch_async(diskWriteQueue) {
let path = self.pathForKey(key)
NSKeyedArchiver.archiveRootObject(cacheObject, toFile: path)
}
}
// MARK: Remove objects
/**
* Removes an object from the cache.
*
* @param key The key of the object that should be removed
*/
public func removeObjectForKey(key: String) {
cache.removeObjectForKey(key)
dispatch_async(diskWriteQueue) {
let path = self.pathForKey(key)
self.fileManager.removeItemAtPath(path, error: nil)
}
}
/**
* Removes all objects from the cache.
*
* @param completion Called as soon as all cached objects are removed from disk.
*/
public func removeAllObjects(completion: (() -> Void)? = nil) {
cache.removeAllObjects()
dispatch_async(diskWriteQueue) {
let paths = self.fileManager.contentsOfDirectoryAtPath(self.cacheDirectory, error: nil) as! [String]
let keys = paths.map { $0.stringByDeletingPathExtension }
for key in keys {
let path = self.pathForKey(key)
self.fileManager.removeItemAtPath(path, error: nil)
}
dispatch_async(dispatch_get_main_queue()) {
completion?()
}
}
}
// MARK: Remove Expired Objects
/**
* Removes all expired objects from the cache.
*/
public func removeExpiredObjects() {
dispatch_async(diskWriteQueue) {
let paths = self.fileManager.contentsOfDirectoryAtPath(self.cacheDirectory, error: nil) as! [String]
let keys = paths.map { $0.stringByDeletingPathExtension }
for key in keys {
// `objectForKey:` deletes the object if it is expired
self.objectForKey(key)
}
}
}
// MARK: Subscripting
public subscript(key: String) -> T? {
get {
return objectForKey(key)
}
set(newValue) {
if let value = newValue {
setObject(value, forKey: key)
} else {
removeObjectForKey(key)
}
}
}
// MARK: Private Helper
private func pathForKey(key: String) -> String {
let k = sanitizedKey(key)
return cacheDirectory.stringByAppendingPathComponent(k).stringByAppendingPathExtension("cache")!
}
private func sanitizedKey(key: String) -> String {
let regex = NSRegularExpression(pattern: "[^a-zA-Z0-9_]+", options: NSRegularExpressionOptions(), error: nil)!
let range = NSRange(location: 0, length: count(key))
return regex.stringByReplacingMatchesInString(key, options: NSMatchingOptions(), range: range, withTemplate: "-")
}
private func expiryDateForCacheExpiry(expiry: CacheExpiry) -> NSDate {
switch expiry {
case .Never:
return NSDate.distantFuture() as! NSDate
case .Seconds(let seconds):
return NSDate().dateByAddingTimeInterval(seconds)
case .Date(let date):
return date
}
}
}
| mit | c6f67128c0b1ac1ecb5139ffdb91a5b7 | 29.964789 | 190 | 0.702638 | 3.83515 | false | false | false | false |
lionchina/RxSwiftBook | RxPickerView/RxPickerView/AppDelegate.swift | 1 | 4603 | //
// AppDelegate.swift
// RxPickerView
//
// Created by MaxChen on 03/08/2017.
// Copyright © 2017 com.linglustudio. All rights reserved.
//
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
self.saveContext()
}
// MARK: - Core Data stack
lazy var persistentContainer: NSPersistentContainer = {
/*
The persistent container for the application. This implementation
creates and returns a container, having loaded the store for the
application to it. This property is optional since there are legitimate
error conditions that could cause the creation of the store to fail.
*/
let container = NSPersistentContainer(name: "RxPickerView")
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
if let error = error as NSError? {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
/*
Typical reasons for an error here include:
* The parent directory does not exist, cannot be created, or disallows writing.
* The persistent store is not accessible, due to permissions or data protection when the device is locked.
* The device is out of space.
* The store could not be migrated to the current model version.
Check the error message to determine what the actual problem was.
*/
fatalError("Unresolved error \(error), \(error.userInfo)")
}
})
return container
}()
// MARK: - Core Data Saving support
func saveContext () {
let context = persistentContainer.viewContext
if context.hasChanges {
do {
try context.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nserror = error as NSError
fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
}
}
}
}
| apache-2.0 | c1441b493e9e35f729397df1e396b2e7 | 48.483871 | 285 | 0.686658 | 5.847522 | false | false | false | false |
noppoMan/SwiftKnex | Sources/SwiftKnex/DDL/Create.swift | 1 | 1916 | //
// Create.swift
// SwiftKnex
//
// Created by Yuki Takei on 2017/01/15.
//
//
import Foundation
public struct Create: DDLBuildable {
let table: String
let builder: Schema.Buiulder
public init(table: String, fields: [Schema.Field]){
self.table = table
self.builder = Schema.Buiulder(table, fields)
}
public func index(name: String? = nil, columns: [String], unique: Bool = false) -> Create {
builder.index(name: name, columns: columns, unique: unique)
return self
}
public func hasTimestamps(forCreated: String = "created_at", forUpdated: String = "updated_at") -> Create {
builder.hasTimestamps(Schema.TimeStampFields(forCreated: forCreated, forUpdated: forUpdated))
return self
}
public func engine(_ engine: Schema.MYSQLEngine) -> Create {
builder.engine(engine)
return self
}
public func charset(_ char: Schema.Charset) -> Create {
builder.charset(char)
return self
}
public func toDDL() throws -> String {
let fieldDefiniations = builder.buildFields()
let indexes = builder.buildIndexes()
let primaryKey = try builder.buildPrimaryKey()
var ddl = ""
ddl += "CREATE TABLE"
ddl += "\(pack(key: table))"
ddl += "(\n"
ddl += fieldDefiniations.joined(separator: ", \n")
if let pri = primaryKey {
ddl += ","
ddl += "\n"
ddl += "\(pri)"
} else {
ddl += "\n"
}
if indexes.count > 0 {
ddl += ","
ddl += "\n"
}
ddl += indexes.joined(separator: ",\n")
ddl += "\n"
ddl += ")"
ddl += "ENGINE=\(builder.engine) DEFAULT CHARSET=\(builder.charset ?? .utf8)"
ddl += ";"
return ddl
}
}
| mit | 23f2b1e556bf1d1b6153a2304cd09e03 | 24.891892 | 111 | 0.530793 | 4.05074 | false | false | false | false |
AvdLee/Moya-JASONMapper | Example/Moya-JASONMapper_Tests/Moya_JASONMapper_Tests.swift | 1 | 6480 | //
// Moya_JASONMapper_Tests.swift
// Moya-JASONMapper_Tests
//
// Created by Antoine van der Lee on 07/06/16.
// Copyright © 2016 CocoaPods. All rights reserved.
//
import UIKit
import XCTest
import Moya_JASONMapper
import Moya
@testable import Moya_JASONMapper_Example
class Moya_JASONMapper_Tests: XCTestCase {
func testCoreMappingObject(){
let expectation = self.expectation(description: "This call call a Get API call and returns a GetResponse.")
var getResponseObject:GetResponse?
var errorValue:Moya.Error?
let cancellableRequest:Cancellable = stubbedProvider.request(ExampleAPI.getObject) { (result) -> () in
switch result {
case let .success(response):
do {
getResponseObject = try response.map(to: GetResponse.self)
expectation.fulfill()
} catch {
expectation.fulfill()
}
case let .failure(error):
errorValue = error
expectation.fulfill()
}
}
waitForExpectations(timeout: 10.0) { (error) in
XCTAssertNil(errorValue, "We have an unexpected error value")
XCTAssertNotNil(getResponseObject, "We should have a parsed getResponseObject")
cancellableRequest.cancel()
}
}
func testReactiveCocoaMappingObject(){
let expectation = self.expectation(description: "This call call a Get API call and returns a GetResponse through a ReactiveCocoa signal.")
var getResponseObject:GetResponse?
var errorValue:Moya.Error?
let disposable = RCStubbedProvider.request(ExampleAPI.getObject).map(to: GetResponse.self)
.on(failed: { (error) -> () in
errorValue = error
},
completed: { () -> () in
expectation.fulfill()
},
value: { (response) -> () in
getResponseObject = response
}
).start()
waitForExpectations(timeout: 10.0) { (error) in
XCTAssertNil(errorValue, "We have an unexpected error value")
XCTAssertNotNil(getResponseObject, "We should have a parsed getResponseObject")
disposable.dispose()
}
}
func testRxSwiftMappingObject(){
let expectation = self.expectation(description: "This call call a Get API call and returns a GetResponse through a ReactiveCocoa signal.")
var getResponseObject:GetResponse?
var errorValue:Moya.Error?
let disposable = RXStubbedProvider.request(ExampleAPI.getObject).map(to: GetResponse.self).subscribe(onNext: { (response) -> Void in
getResponseObject = response
}, onError: { (error) -> Void in
errorValue = error as? Moya.Error
expectation.fulfill()
}, onCompleted: { () -> Void in
expectation.fulfill()
})
waitForExpectations(timeout: 10.0) { (error) in
XCTAssertNil(errorValue, "We have an unexpected error value")
XCTAssertNotNil(getResponseObject, "We should have a parsed getResponseObject")
disposable.dispose()
}
}
func testCoreMappingArray(){
let expectation = self.expectation(description: "This call call a Get API call and returns a GetResponse.")
var getResponseArray:[GetResponse]?
var errorValue:Moya.Error?
let cancellableRequest:Cancellable = stubbedProvider.request(ExampleAPI.getArray) { (result) -> () in
switch result {
case let .success(response):
do {
getResponseArray = try response.map(to: [GetResponse.self])
expectation.fulfill()
} catch {
expectation.fulfill()
}
case let .failure(error):
errorValue = error
expectation.fulfill()
}
}
waitForExpectations(timeout: 10.0) { (error) in
XCTAssertNil(errorValue, "We have an unexpected error value")
XCTAssertNotNil(getResponseArray, "We should have a parsed getResponseObject")
cancellableRequest.cancel()
}
}
func testReactiveCocoaMappingArray(){
let expectation = self.expectation(description: "This call call a Get API call and returns a GetResponse through a ReactiveCocoa signal.")
var getResponseArray:[GetResponse]?
var errorValue:Moya.Error?
let disposable = RCStubbedProvider.request(ExampleAPI.getArray).map(to: [GetResponse.self])
.on(failed: { (error) -> () in
errorValue = error
},
completed: { () -> () in
expectation.fulfill()
},
value: { (response) -> () in
getResponseArray = response
}).start()
waitForExpectations(timeout: 10.0) { (error) in
XCTAssertNil(errorValue, "We have an unexpected error value")
XCTAssertNotNil(getResponseArray, "We should have a parsed getResponseObject")
disposable.dispose()
}
}
func testRxSwiftMappingArray(){
let expectation = self.expectation(description: "This call call a Get API call and returns a GetResponse through a ReactiveCocoa signal.")
var getResponseArray:[GetResponse]?
var errorValue:Moya.Error?
let disposable = RXStubbedProvider.request(ExampleAPI.getArray).map(to: [GetResponse.self]).subscribe(onNext: { (response) -> Void in
getResponseArray = response
}, onError: { (error) -> Void in
errorValue = error as? Moya.Error
expectation.fulfill()
}, onCompleted: { () -> Void in
expectation.fulfill()
})
waitForExpectations(timeout: 10.0) { (error) in
XCTAssertNil(errorValue, "We have an unexpected error value")
XCTAssertNotNil(getResponseArray, "We should have a parsed getResponseObject")
disposable.dispose()
}
}
}
| mit | ecb2f280c729a10a69262c359cc4df6e | 36.668605 | 146 | 0.572156 | 5.276059 | false | true | false | false |
tomas789/JustLog | JustLog/Classes/FileDestination.swift | 1 | 2066 | //
// FileDestination.swift
// JustLog
//
// Created by Alberto De Bortoli on 20/12/2016.
// Copyright © 2017 Just Eat. All rights reserved.
//
import Foundation
import SwiftyBeaver
public class FileDestination: BaseDestination {
public var logFileURL: URL?
var fileHandle: FileHandle? = nil
public override init() {
super.init()
levelColor.verbose = "📣 "
levelColor.debug = "📝 "
levelColor.info = "ℹ️ "
levelColor.warning = "⚠️ "
levelColor.error = "☠️ "
}
override public func send(_ level: SwiftyBeaver.Level, msg: String, thread: String, file: String,
function: String, line: Int, context: Any? = nil) -> String? {
let formattedString = super.send(level, msg: msg, thread: thread, file: file, function: function, line: line)
if let str = formattedString {
let _ = saveToFile(str: str)
}
return formattedString
}
deinit {
if let fileHandle = fileHandle {
fileHandle.closeFile()
}
}
func saveToFile(str: String) -> Bool {
guard let url = logFileURL else { return false }
do {
if FileManager.default.fileExists(atPath: url.path) == false {
let line = str + "\n"
try line.write(to: url, atomically: true, encoding: .utf8)
} else {
if fileHandle == nil {
fileHandle = try FileHandle(forWritingTo: url as URL)
}
if let fileHandle = fileHandle {
let _ = fileHandle.seekToEndOfFile()
let line = str + "\n"
if let data = line.data(using: String.Encoding.utf8) {
fileHandle.write(data)
}
}
}
return true
} catch {
print("SwiftyBeaver File Destination could not write to file \(url).")
return false
}
}
}
| apache-2.0 | d6471d8ea638d2043b432648351614eb | 28.666667 | 117 | 0.522716 | 4.705747 | false | false | false | false |
madewithray/ray-broadcast | RayBroadcast/AdvertiseViewControllerExtension.swift | 1 | 930 | //
// AdvertiseViewControllerExtension.swift
// RayBroadcast
//
// Created by Sean Ooi on 7/3/15.
// Copyright (c) 2015 Yella Inc. All rights reserved.
//
import UIKit
import CoreBluetooth
extension AdvertiseViewController: CBPeripheralManagerDelegate {
func peripheralManagerDidUpdateState(peripheral: CBPeripheralManager!) {
switch peripheral.state {
case .Unknown:
peripheralState = "Bluetooth state Unknown"
case .Resetting:
peripheralState = "Bluetooth Resetting"
case .Unsupported:
peripheralState = "Bluetooth Unsupported"
case .Unauthorized:
peripheralState = "Bluetooth Unauthorized"
case .PoweredOn:
peripheralState = "Bluetooth PoweredOn"
case .PoweredOff:
peripheralState = "Bluetooth PoweredOff"
}
}
}
| mit | 088c777105c7bbc701b218240afb3d4a | 26.352941 | 76 | 0.616129 | 5.470588 | false | false | false | false |
tombuildsstuff/swiftcity | SwiftCity/Entities/Project.swift | 1 | 1473 | public struct Project {
public let project : ProjectLocator
public let parentProject : ProjectLocator?
// NOTE: you might think this is odd these being nullable - but the TC API doesn't return the elements if you don't have the right permissions, so..
public let buildTypes: BuildTypes?
public let templates : BuildTypes?
public let parameters : Parameters?
public let vcsRoots : VCSRoots?
public let projects: Projects?
init?(dictionary: [String: AnyObject]) {
self.project = ProjectLocator(dictionary: dictionary)
func map<T>(dictionary: [String: AnyObject]?, builder: (dictionary: [String: AnyObject]) -> T?) -> T? {
guard let properties = dictionary else {
return nil
}
return builder(dictionary: properties)
}
self.parentProject = map(dictionary["parentProject"] as? [String: AnyObject], builder: ProjectLocator.init)
self.buildTypes = map(dictionary["buildTypes"] as? [String: AnyObject], builder: BuildTypes.init)
self.templates = map(dictionary["templates"] as? [String: AnyObject], builder: BuildTypes.init)
self.parameters = map(dictionary["parameters"] as? [String: AnyObject], builder: Parameters.init)
self.vcsRoots = map(dictionary["vcsRoots"] as? [String: AnyObject], builder: VCSRoots.init)
self.projects = map(dictionary["projects"] as? [String: AnyObject], builder: Projects.init)
}
}
| mit | c9e2b9da26df31618ca1176e16a41128 | 46.516129 | 152 | 0.674813 | 4.463636 | false | false | false | false |
hollyschilling/EssentialElements | EssentialElements/EssentialElements/Interface/Views/BorderedButton.swift | 1 | 5188 | //
// BorderedButton.swift
// EssentialElements
//
// Created by Holly Schilling on 6/24/16.
// Copyright © 2016 Better Practice Solutions. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import UIKit
@IBDesignable
open class BorderedButton: UIButton {
fileprivate static let TextColorKey = "textColor"
//MARK: - Inspectable Properties
@IBInspectable
open var cornerRadius: CGFloat = 5 {
didSet {
layer.cornerRadius = cornerRadius
}
}
@IBInspectable
open var borderWidth: CGFloat = 2 {
didSet {
layer.borderWidth = borderWidth
}
}
@IBInspectable
open var borderColor: UIColor? {
didSet {
applyStyle()
}
}
@IBInspectable
open var normalColor: UIColor? {
didSet {
let image = normalColor.flatMap({ UIImage(color: $0) })
setBackgroundImage(image, for: .normal)
}
}
@IBInspectable
open var disabledColor: UIColor? {
didSet {
let image = disabledColor.flatMap({ UIImage(color: $0) })
setBackgroundImage(image, for: .disabled)
}
}
@IBInspectable
open var highlightedColor: UIColor? {
didSet {
let image = highlightedColor.flatMap({ UIImage(color: $0) })
setBackgroundImage(image, for: .highlighted)
}
}
@IBInspectable
open var selectedColor: UIColor? {
didSet {
let image = selectedColor.flatMap({ UIImage(color: $0) })
setBackgroundImage(image, for: .selected)
}
}
@IBInspectable
open var highlightedSelectedColor: UIColor? {
didSet {
let image = highlightedSelectedColor.flatMap({ UIImage(color: $0) })
setBackgroundImage(image, for: [.highlighted, .selected])
}
}
//MARK: - Lifecycle
public override init(frame: CGRect) {
super.init(frame: frame)
applyStyle()
#if !TARGET_INTERFACE_BUILDER
addTitleColorChangeObserver()
#endif
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
applyStyle()
#if !TARGET_INTERFACE_BUILDER
addTitleColorChangeObserver()
#endif
}
open override func prepareForInterfaceBuilder() {
applyStyle()
}
deinit {
#if !TARGET_INTERFACE_BUILDER
titleLabel?.removeObserver(self, forKeyPath: BorderedButton.TextColorKey)
#endif
}
//MARK: - Overrides
open override func setTitleColor(_ color: UIColor?, for state: UIControlState) {
super.setTitleColor(color, for: state)
applyStyle()
}
//MARK: - KVO
open override func observeValue(forKeyPath keyPath: String?,
of object: Any?,
change: [NSKeyValueChangeKey : Any]?,
context: UnsafeMutableRawPointer?) {
// Accessing self.titleLabel triggers a recursion into this method, so we
// can't explicitly check triggeringLabel==titleLabel
guard let _ = object as? UILabel , BorderedButton.TextColorKey == keyPath else {
super.observeValue(forKeyPath: keyPath, of: object, change: change, context: context)
return
}
applyStyle()
}
//MARK: - Private Helpers
fileprivate func addTitleColorChangeObserver() {
// titleLabel is nil for types other than System or Custom
titleLabel?.addObserver(self,
forKeyPath: BorderedButton.TextColorKey,
options: [],
context: nil)
}
fileprivate func applyStyle() {
layer.cornerRadius = cornerRadius
layer.borderWidth = borderWidth
let color = borderColor ?? currentTitleColor
layer.borderColor = color.cgColor
}
}
| mit | a380de3279f2d14c610c70fec15af2d6 | 29.511765 | 97 | 0.603624 | 5.25 | false | false | false | false |
jaropawlak/Signal-iOS | Signal/src/environment/PushRegistrationManager.swift | 1 | 11497 | //
// Copyright (c) 2017 Open Whisper Systems. All rights reserved.
//
import Foundation
import PromiseKit
import PushKit
public enum PushRegistrationError: Error {
case assertionError(description: String)
case pushNotSupported(description: String)
case timeout
}
/**
* Singleton used to integrate with push notification services - registration and routing received remote notifications.
*/
@objc class PushRegistrationManager: NSObject, PKPushRegistryDelegate {
let TAG = "[PushRegistrationManager]"
// MARK - Dependencies
private var pushManager: PushManager {
return PushManager.shared()
}
// MARK - Singleton class
@objc(sharedManager)
static let shared = PushRegistrationManager()
private override init() {
super.init()
}
private var userNotificationSettingsPromise: Promise<Void>?
private var fulfillUserNotificationSettingsPromise: (() -> Void)?
private var vanillaTokenPromise: Promise<Data>?
private var fulfillVanillaTokenPromise: ((Data) -> Void)?
private var rejectVanillaTokenPromise: ((Error) -> Void)?
private var voipRegistry: PKPushRegistry?
private var voipTokenPromise: Promise<Data>?
private var fulfillVoipTokenPromise: ((Data) -> Void)?
// MARK: Public interface
public func requestPushTokens() -> Promise<(pushToken: String, voipToken: String)> {
Logger.info("\(self.TAG) in \(#function)")
return self.registerUserNotificationSettings().then {
guard !Platform.isSimulator else {
throw PushRegistrationError.pushNotSupported(description:"Push not supported on simulators")
}
return self.registerForVanillaPushToken().then { vanillaPushToken in
self.registerForVoipPushToken().then { voipPushToken in
(pushToken: vanillaPushToken, voipToken: voipPushToken)
}
}
}
}
// Notification registration is confirmed via AppDelegate
// Before this occurs, it is not safe to assume push token requests will be acknowledged.
//
// e.g. in the case that Background Fetch is disabled, token requests will be ignored until
// we register user notification settings.
@objc
public func didRegisterUserNotificationSettings() {
guard let fulfillUserNotificationSettingsPromise = self.fulfillUserNotificationSettingsPromise else {
owsFail("\(TAG) promise completion in \(#function) unexpectedly nil")
return
}
fulfillUserNotificationSettingsPromise()
}
// MARK: Vanilla push token
// Vanilla push token is obtained from the system via AppDelegate
@objc
public func didReceiveVanillaPushToken(_ tokenData: Data) {
guard let fulfillVanillaTokenPromise = self.fulfillVanillaTokenPromise else {
owsFail("\(TAG) promise completion in \(#function) unexpectedly nil")
return
}
fulfillVanillaTokenPromise(tokenData)
}
// Vanilla push token is obtained from the system via AppDelegate
@objc
public func didFailToReceiveVanillaPushToken(error: Error) {
guard let rejectVanillaTokenPromise = self.rejectVanillaTokenPromise else {
owsFail("\(TAG) promise completion in \(#function) unexpectedly nil")
return
}
rejectVanillaTokenPromise(error)
}
// MARK: PKPushRegistryDelegate - voIP Push Token
public func pushRegistry(_ registry: PKPushRegistry, didReceiveIncomingPushWith payload: PKPushPayload, forType type: PKPushType) {
Logger.info("\(self.TAG) in \(#function)")
assert(type == .voIP)
self.pushManager.application(UIApplication.shared, didReceiveRemoteNotification: payload.dictionaryPayload)
}
public func pushRegistry(_ registry: PKPushRegistry, didUpdate credentials: PKPushCredentials, forType type: PKPushType) {
Logger.info("\(self.TAG) in \(#function)")
assert(type == .voIP)
assert(credentials.type == .voIP)
guard let fulfillVoipTokenPromise = self.fulfillVoipTokenPromise else {
owsFail("\(TAG) fulfillVoipTokenPromise was unexpectedly nil")
return
}
fulfillVoipTokenPromise(credentials.token)
}
public func pushRegistry(_ registry: PKPushRegistry, didInvalidatePushTokenForType type: PKPushType) {
// It's not clear when this would happen. We've never previously handled it, but we should at
// least start learning if it happens.
owsFail("\(TAG) in \(#function)")
}
// MARK: helpers
// User notification settings must be registered *before* AppDelegate will
// return any requested push tokens. We don't consider the notifications settings registration
// *complete* until AppDelegate#didRegisterUserNotificationSettings is called.
private func registerUserNotificationSettings() -> Promise<Void> {
AssertIsOnMainThread()
guard self.userNotificationSettingsPromise == nil else {
let promise = self.userNotificationSettingsPromise!
Logger.info("\(TAG) already registered user notification settings")
return promise
}
let (promise, fulfill, _) = Promise<Void>.pending()
self.userNotificationSettingsPromise = promise
self.fulfillUserNotificationSettingsPromise = fulfill
Logger.info("\(TAG) registering user notification settings")
UIApplication.shared.registerUserNotificationSettings(self.pushManager.userNotificationSettings)
return promise
}
/**
* When users have disabled notifications and background fetch, the system hangs when returning a push token.
* More specifically, after registering for remote notification, the app delegate calls neither
* `didFailToRegisterForRemoteNotificationsWithError` nor `didRegisterForRemoteNotificationsWithDeviceToken`
* This behavior is identical to what you'd see if we hadn't previously registered for user notification settings, though
* in this case we've verified that we *have* properly registered notification settings.
*/
private var isSusceptibleToFailedPushRegistration: Bool {
// Only affects users who have disabled both: background refresh *and* notifications
guard UIApplication.shared.backgroundRefreshStatus == .denied else {
return false
}
guard let notificationSettings = UIApplication.shared.currentUserNotificationSettings else {
return false
}
guard notificationSettings.types == [] else {
return false
}
return true
}
private func registerForVanillaPushToken() -> Promise<String> {
Logger.info("\(self.TAG) in \(#function)")
AssertIsOnMainThread()
guard self.vanillaTokenPromise == nil else {
let promise = vanillaTokenPromise!
assert(promise.isPending)
Logger.info("\(TAG) alreay pending promise for vanilla push token")
return promise.then { $0.hexEncodedString }
}
// No pending vanilla token yet. Create a new promise
let (promise, fulfill, reject) = Promise<Data>.pending()
self.vanillaTokenPromise = promise
self.fulfillVanillaTokenPromise = fulfill
self.rejectVanillaTokenPromise = reject
UIApplication.shared.registerForRemoteNotifications()
let kTimeout: TimeInterval = 10
let timeout: Promise<Data> = after(seconds: kTimeout).then { throw PushRegistrationError.timeout }
let promiseWithTimeout: Promise<Data> = race(promise, timeout)
return promiseWithTimeout.recover { error -> Promise<Data> in
switch error {
case PushRegistrationError.timeout:
if self.isSusceptibleToFailedPushRegistration {
// If we've timed out on a device known to be susceptible to failures, quit trying
// so the user doesn't remain indefinitely hung for no good reason.
throw PushRegistrationError.pushNotSupported(description: "Device configuration disallows push notifications")
} else {
// Sometimes registration can just take a while.
// If we're not on a device known to be susceptible to push registration failure,
// just return the original promise.
return promise
}
default:
throw error
}
}.then { (pushTokenData: Data) -> String in
if self.isSusceptibleToFailedPushRegistration {
// Sentinal in case this bug is fixed.
owsFail("Device was unexpectedly able to complete push registration even though it was susceptible to failure.")
}
Logger.info("\(self.TAG) successfully registered for vanilla push notifications")
return pushTokenData.hexEncodedString
}.always {
self.vanillaTokenPromise = nil
}
}
private func registerForVoipPushToken() -> Promise<String> {
AssertIsOnMainThread()
Logger.info("\(self.TAG) in \(#function)")
guard self.voipTokenPromise == nil else {
let promise = self.voipTokenPromise!
assert(promise.isPending)
return promise.then { $0.hexEncodedString }
}
// No pending voip token yet. Create a new promise
let (promise, fulfill, reject) = Promise<Data>.pending()
self.voipTokenPromise = promise
self.fulfillVoipTokenPromise = fulfill
if self.voipRegistry == nil {
// We don't create the voip registry in init, because it immediately requests the voip token,
// potentially before we're ready to handle it.
let voipRegistry = PKPushRegistry(queue: nil)
self.voipRegistry = voipRegistry
voipRegistry.desiredPushTypes = [.voIP]
voipRegistry.delegate = self
}
guard let voipRegistry = self.voipRegistry else {
owsFail("\(TAG) failed to initialize voipRegistry in \(#function)")
reject(PushRegistrationError.assertionError(description: "\(TAG) failed to initialize voipRegistry in \(#function)"))
return promise.then { _ in
// coerce expected type of returned promise - we don't really care about the value,
// since this promise has been rejected. In practice this shouldn't happen
String()
}
}
// If we've already completed registering for a voip token, resolve it immediately,
// rather than waiting for the delegate method to be called.
if let voipTokenData = voipRegistry.pushToken(forType: .voIP) {
Logger.info("\(self.TAG) using pre-registered voIP token")
fulfill(voipTokenData)
}
return promise.then { (voipTokenData: Data) -> String in
Logger.info("\(self.TAG) successfully registered for voip push notifications")
return voipTokenData.hexEncodedString
}.always {
self.voipTokenPromise = nil
}
}
}
// We transmit pushToken data as hex encoded string to the server
fileprivate extension Data {
var hexEncodedString: String {
return map { String(format: "%02hhx", $0) }.joined()
}
}
| gpl-3.0 | b5a133655015f422c65fe5481f53f1a6 | 39.340351 | 135 | 0.663651 | 5.237813 | false | false | false | false |
gerardogrisolini/Webretail | Sources/Webretail/Models/PdfDocument.swift | 1 | 295 | //
// Email.swift
// Webretail
//
// Created by Gerardo Grisolini on 12/04/17.
//
//
class PdfDocument: Codable {
public var address : String = ""
public var subject : String = ""
public var content : String = ""
public var size : String = "A4"
public var zoom : String = "1.0"
}
| apache-2.0 | 7e50879dfea1daf89d76d400c7800907 | 18.666667 | 45 | 0.620339 | 3.072917 | false | false | false | false |
inamiy/ReactiveCocoaCatalog | ReactiveCocoaCatalog/Samples/PhotosDetailViewController.swift | 1 | 2018 | //
// PhotosDetailViewController.swift
// ReactiveCocoaCatalog
//
// Created by Yasuhiro Inami on 2016-04-18.
// Copyright © 2016 Yasuhiro Inami. All rights reserved.
//
import UIKit
import Result
import ReactiveSwift
import APIKit
final class PhotosDetailViewController: UIViewController, StoryboardSceneProvider
{
static let storyboardScene = StoryboardScene<PhotosDetailViewController>(name: "PhotosLike")
@IBOutlet weak var imageView: UIImageView?
@IBOutlet weak var titleLabel: UILabel?
@IBOutlet weak var likeButton: UIButton?
let viewModel = PhotosLikeDetailViewModel()
var photo: FlickrAPI.Photo? // var, because it's storyboard
override func viewDidLoad()
{
super.viewDidLoad()
guard let photo = self.photo else {
fatalError("`FlickrAPI.Photo` is not set.")
}
self.titleLabel!.text = photo.title
// Set image.
self.imageView!.reactive.image
<~ self.viewModel.imageProperty.producer
// Set alpha.
self.imageView!.reactive.alpha
<~ self.viewModel.imageProperty.producer
.flatMap(.merge) { _ -> SignalProducer<CGFloat, NoError> in
// Fade-in animation.
return SignalProducer(value: 1.0)
.animate(duration: 0.5)
.prefix(value: 0.0)
}
// Update `likeButton.title` on `like` change.
self.likeButton!.reactive.title
<~ PhotosLikeManager.likes[photo.imageURL].producer
.map { $0.detailText }
// Send change to `PhotosLikeManager` on `likeButton` tap.
PhotosLikeManager.likes[photo.imageURL]
<~ self.likeButton!.reactive.controlEvents(.touchUpInside)
.withLatest(from: PhotosLikeManager.likes[photo.imageURL].producer)
.map { $1.inverse }
}
}
final class PhotosLikeDetailViewModel
{
let imageProperty = MutableProperty<UIImage?>(nil)
}
| mit | bfc1db39227cad8e9e092e07a7ec7117 | 29.560606 | 96 | 0.63411 | 4.768322 | false | false | false | false |
Daij-Djan/CoprightModifier | Helpers/GTTreeEntry+EntryWithSHA.swift | 1 | 1661 | //
// GTTreeEntry+EntryWithSHA.swift
// GitLogView
//
// Created by Dominik Pich on 11/24/15.
// Copyright © 2015 Dominik Pich. All rights reserved.
//
import Foundation
import ObjectiveGit
extension GTTree {
/// Get an entry by it's BLOBs sha
///
/// SHA - the SHA of the entry's blob
///
/// returns a GTTreeEntry and its relative path or nil if there is nothing with the specified Blob SHA
public func entryWithBlobSHA(_ SHA: String) -> (GTTreeEntry, String)? {
var item : GTTreeEntry?
var path : String?
do {
try self.enumerateEntries(with: GTTreeEnumerationOptions.post, block: { (entry, relativePath, stopPointer) -> Bool in
guard entry.type == .blob else {
return false;
}
var br = false
autoreleasepool {
let entryPath = relativePath + entry.name
do {
let obj = try entry.gtObject()
let sha2 = obj.sha
if SHA == sha2 {
item = entry
path = entryPath
stopPointer.pointee = true
br = true
}
}
catch {
}
}
return br
})
}
catch {
}
if item != nil && path != nil {
return (item!, path!)
}
return nil
}
}
| gpl-2.0 | 12765a5534e18b4b44c04029d21fc0b6 | 27.135593 | 129 | 0.425904 | 5.15528 | false | false | false | false |
nsgeek/ELRouter | ELRouterTests/MockNavigator.swift | 1 | 1138 | //
// MockNavigator.swift
// ELRouter
//
// Created by Angelo Di Paolo on 12/22/15.
// Copyright © 2015 Walmart. All rights reserved.
//
import Foundation
import ELRouter
@objc final class MockNavigator: NSObject, Navigator {
var viewControllers: [UIViewController]? = nil
var selectedViewController: UIViewController? {
willSet(newValue) {
if let controller = newValue {
if let index = viewControllers?.indexOf(controller) {
selectedIndex = index
}
}
}
}
var selectedIndex: Int = 0
var testNavigationController: UINavigationController?
override init() {
let navigationConroller = UINavigationController(rootViewController: UIViewController(nibName: nil, bundle: nil))
testNavigationController = navigationConroller
selectedViewController = navigationConroller
}
func setViewControllers(viewControllers: [UIViewController]?, animated: Bool) {
self.viewControllers = viewControllers
selectedViewController = viewControllers?.first
}
}
| mit | 8cb1a91d2221f36a9dc6653abadd156e | 28.153846 | 121 | 0.656113 | 5.600985 | false | true | false | false |
naoyashiga/CatsForInstagram | Nekobu/ReviewManager.swift | 1 | 1057 | //
// ReviewManager.swift
// Nekobu
//
// Created by naoyashiga on 2015/08/22.
// Copyright (c) 2015年 naoyashiga. All rights reserved.
//
import Foundation
final class ReviewManager: BaseUserDefaultManager {
static var isReview = true
struct Cycle {
static var top = 8
}
struct keyName {
static let reviewCounter = "reviewCounter"
static let isReview = "isReview"
}
static func initialSetting() {
mySetCounter(keyName.reviewCounter)
setIsReview()
}
private static func setIsReview(){
if ud.objectForKey(keyName.isReview) == nil {
ud.setObject(true, forKey: keyName.isReview)
isReview = true
} else {
isReview = ud.boolForKey(keyName.isReview)
}
}
static func updateReviewStatus() {
if ud.objectForKey(keyName.isReview) == nil {
ud.setObject(false, forKey: keyName.isReview)
} else {
ud.setBool(false, forKey: keyName.isReview)
}
}
} | mit | 5d7b75ac15f310e86d8af385723f8133 | 23 | 57 | 0.595261 | 4.22 | false | false | false | false |
benlangmuir/swift | stdlib/public/Concurrency/GlobalActor.swift | 14 | 2149 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2021 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import Swift
/// A type that represents a globally-unique actor that can be used to isolate
/// various declarations anywhere in the program.
///
/// A type that conforms to the `GlobalActor` protocol and is marked with
/// the `@globalActor` attribute can be used as a custom attribute. Such types
/// are called global actor types, and can be applied to any declaration to
/// specify that such types are isolated to that global actor type. When using
/// such a declaration from another actor (or from nonisolated code),
/// synchronization is performed through the shared actor instance to ensure
/// mutually-exclusive access to the declaration.
@available(SwiftStdlib 5.1, *)
public protocol GlobalActor {
/// The type of the shared actor instance that will be used to provide
/// mutually-exclusive access to declarations annotated with the given global
/// actor type.
associatedtype ActorType: Actor
/// The shared actor instance that will be used to provide mutually-exclusive
/// access to declarations annotated with the given global actor type.
///
/// The value of this property must always evaluate to the same actor
/// instance.
static var shared: ActorType { get }
/// The shared executor instance that will be used to provide
/// mutually-exclusive access for the global actor.
///
/// The value of this property must be equivalent to `shared.unownedExecutor`.
static var sharedUnownedExecutor: UnownedSerialExecutor { get }
}
@available(SwiftStdlib 5.1, *)
extension GlobalActor {
public static var sharedUnownedExecutor: UnownedSerialExecutor {
shared.unownedExecutor
}
}
| apache-2.0 | d045569f4e78c1aba50a87401e7ae291 | 40.326923 | 80 | 0.695207 | 5.021028 | false | false | false | false |
Tornquist/cocoaconfappextensionsclass | CocoaConf App Extensions Class/CocoaConfExtensions_06_Action+JavaScript_Begin/CocoaConf Keyboard/KeyboardViewController.swift | 6 | 1887 | //
// KeyboardViewController.swift
// CocoaConf Keyboard
//
// Created by Chris Adamson on 3/25/15.
// Copyright (c) 2015 Subsequently & Furthermore, Inc. All rights reserved.
//
import UIKit
class KeyboardViewController: UIInputViewController, UICollectionViewDataSource, UICollectionViewDelegate {
let keys = ["α", "β", "γ", "δ", "ε", "ζ", "η", "θ", "ι", "κ", "λ",
"μ", "ν", "ξ", "ο", "π", "ρ", "ς", "σ", "τ", "υ", "φ", "χ", "ψ",
"ω", "ϊ", "ϋ", "ό", "ύ", "ώ"]
override func textDidChange(textInput: UITextInput) {
// The app has just changed the document's contents, the document context has been updated.
var textColor: UIColor
var proxy = self.textDocumentProxy as! UITextDocumentProxy
if proxy.keyboardAppearance == UIKeyboardAppearance.Dark {
textColor = UIColor.whiteColor()
} else {
textColor = UIColor.blackColor()
}
}
@IBAction func handleNextKeyboardButtonTapped(sender: AnyObject) {
self.advanceToNextInputMode()
}
@IBAction func handleKeyPress(sender: UIButton) {
if let keyInputProxy = textDocumentProxy as? UIKeyInput {
keyInputProxy.insertText(sender.titleLabel!.text!)
}
}
// MARK: collection view data source
func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return keys.count
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("KeyCell", forIndexPath: indexPath) as! UICollectionViewCell
let button = cell.viewWithTag(1000) as! UIButton
button.setTitle(keys[indexPath.row], forState: .Normal)
return cell
}
}
| cc0-1.0 | a4c0c70f622f7a8095366ee63864f53e | 31.578947 | 127 | 0.695746 | 4.054585 | false | false | false | false |
Lickability/PinpointKit | PinpointKit/PinpointKit/Sources/Core/BezierPath.swift | 2 | 3463 | //
// BezierPath.swift
// Pinpoint
//
// Created by Brian Capps on 5/5/15.
// Copyright (c) 2015 Lickability. All rights reserved.
//
import UIKit
extension UIBezierPath {
private static let PaintCodeArrowPathWidth: CGFloat = 267.0
/**
Creates a bezier path in the shape of an arrow.
- parameter startPoint: The starting control point of the shape.
- parameter endPoint: The ending control point of the shape.
- returns: A `UIBezierPath` in the shape of an arrow.
*/
static func arrowBezierPath(_ startPoint: CGPoint, endPoint: CGPoint) -> UIBezierPath {
let length = hypot(endPoint.x - startPoint.x, endPoint.y - startPoint.y)
// Shape 267x120 from PaintCode. 0 is the mid Y of the arrow to match the original arrow Y.
let bezierPath = UIBezierPath()
bezierPath.move(to: CGPoint(x: 197.29, y: -57.56))
bezierPath.addLine(to: CGPoint(x: 194.32, y: -54.58))
bezierPath.addCurve(to: CGPoint(x: 193.82, y: -43.36), controlPoint1: CGPoint(x: 191.31, y: -51.53), controlPoint2: CGPoint(x: 191.09, y: -46.67))
bezierPath.addLine(to: CGPoint(x: 215.25, y: -17.45))
bezierPath.addCurve(to: CGPoint(x: 213.11, y: -12.74), controlPoint1: CGPoint(x: 216.79, y: -15.59), controlPoint2: CGPoint(x: 215.5, y: -12.77))
bezierPath.addLine(to: CGPoint(x: 8.15, y: -10.22))
bezierPath.addCurve(to: CGPoint(x: 0, y: -1.9), controlPoint1: CGPoint(x: 3.63, y: -10.17), controlPoint2: CGPoint(x: 0, y: -6.46))
bezierPath.addLine(to: CGPoint(x: 0, y: 1.81))
bezierPath.addCurve(to: CGPoint(x: 8.15, y: 10.13), controlPoint1: CGPoint(x: 0, y: 6.37), controlPoint2: CGPoint(x: 3.63, y: 10.08))
bezierPath.addLine(to: CGPoint(x: 213.18, y: 12.65))
bezierPath.addCurve(to: CGPoint(x: 215.33, y: 17.36), controlPoint1: CGPoint(x: 215.58, y: 12.68), controlPoint2: CGPoint(x: 216.86, y: 15.5))
bezierPath.addLine(to: CGPoint(x: 193.82, y: 43.36))
bezierPath.addCurve(to: CGPoint(x: 194.32, y: 54.58), controlPoint1: CGPoint(x: 191.09, y: 46.67), controlPoint2: CGPoint(x: 191.31, y: 51.53))
bezierPath.addLine(to: CGPoint(x: 197.29, y: 57.56))
bezierPath.addCurve(to: CGPoint(x: 208.95, y: 57.56), controlPoint1: CGPoint(x: 200.51, y: 60.81), controlPoint2: CGPoint(x: 205.73, y: 60.81))
bezierPath.addLine(to: CGPoint(x: 266, y: -0))
bezierPath.addLine(to: CGPoint(x: 208.95, y: -57.56))
bezierPath.addCurve(to: CGPoint(x: 197.29, y: -57.56), controlPoint1: CGPoint(x: 205.73, y: -60.81), controlPoint2: CGPoint(x: 200.51, y: -60.81))
bezierPath.close()
bezierPath.usesEvenOddFillRule = true
bezierPath.apply(transform(forStartPoint: startPoint, endPoint: endPoint, length: length))
return bezierPath
}
private static func transform(forStartPoint startPoint: CGPoint, endPoint: CGPoint, length: CGFloat) -> CGAffineTransform {
let cosine = (endPoint.x - startPoint.x) / length
let sine = (endPoint.y - startPoint.y) / length
let scale: CGFloat = length / PaintCodeArrowPathWidth
let scaleTransform = CGAffineTransform(scaleX: scale, y: scale)
let rotationAndSizeTransform = CGAffineTransform(a: cosine, b: sine, c: -sine, d: cosine, tx: startPoint.x, ty: startPoint.y)
return scaleTransform.concatenating(rotationAndSizeTransform)
}
}
| mit | 8b2772783aef27161f18baa83e462a70 | 53.968254 | 154 | 0.649726 | 3.395098 | false | false | false | false |
volodg/LotterySRV | Sources/App/Controllers/PowerBallController.swift | 1 | 1493 | import Foundation
final class PowerBallController: ResourceRepresentable {
func statistic(_ req: Request) throws -> ResponseRepresentable {
tryUpdateResultsIfNeeds()
let results: [LotteryWithSpecialBall] = try PowerBallResult.makeQuery().all().map { $0 }
return results.statistic()
}
func index(req: Request) throws -> ResponseRepresentable {
tryUpdateResultsIfNeeds()
return try PowerBallResult.makeQuery().sort("draw_date", .descending).all().makeJSON()
}
/// When making a controller, it is pretty flexible in that it
/// only expects closures, this is useful for advanced scenarios, but
/// most of the time, it should look almost identical to this
/// implementation
func makeResource() -> Resource<PowerBallResult> {
let resource = Resource<PowerBallResult>(
index: index
)
return resource
}
}
/// Since PostController doesn't require anything to
/// be initialized we can conform it to EmptyInitializable.
///
/// This will allow it to be passed by type.
extension PowerBallController: EmptyInitializable { }
extension PowerBallController: RefreshResultsLogic {
typealias ModelT = PowerBallResult
var lotteryPath: String {
return "power_ball"
}
func fetchFreshModels() throws -> [ModelT] {
let url = try URL(string: "http://www.powerball.com/powerball/winnums-text.txt").unwrap()
let data = try Data(contentsOf: url)
return try PowerBallResult.models(withData: data)
}
}
| mit | fb98057ac14ce84260560cf451822967 | 29.469388 | 93 | 0.713329 | 4.524242 | false | false | false | false |
r14r/fork_swift_intro-playgrounds | FunctionalProgamming.playground/section-1.swift | 2 | 809 | import UIKit
func makeIncrementer() -> (Int -> Int) {
func addOne(number: Int) -> Int {
return 1 + number
}
return addOne
}
var inc=makeIncrementer()
inc(7)
// ***********
func hasAnyMatches(list: Int[], condition: Int -> Bool) -> Bool {
for item in list {
if condition(item) {
return true
}
}
return false
}
func lessThanTen(number: Int) -> Bool {
return number < 10
}
var numbers = [20, 19, 7, 12]
hasAnyMatches(numbers, lessThanTen)
let result = numbers.map({
(number: Int) -> Int in
let result = 3 * number
return result
})
numbers
result
let result2 = numbers.map({ number in 3 * number })
result2
let sortedNumbers = sort(numbers){ $0 < $1 }
sortedNumbers
let result3 = numbers.filter() { $0 % 2 == 0 }
result3
| mit | e70c1f6e2c91c1476f6b76a404c60050 | 15.854167 | 65 | 0.595797 | 3.413502 | false | false | false | false |
iWeslie/Ant | Ant/Ant/Me/Login/LoginWithPwd.swift | 2 | 3839 | //
// RegisterVC.swift
// Ant
//
// Created by Weslie on 2017/7/11.
// Copyright © 2017年 LiuXinQiang. All rights reserved.
//
import UIKit
import SVProgressHUD
class LoginWithPwd: UIViewController {
@IBOutlet weak var phoneNumber: UITextField!
@IBOutlet weak var password: UITextField!
@IBOutlet weak var Nav: UINavigationBar!
@IBAction func login(_ sender: UIButton) {
if phoneNumber.text == "" {
self.presentHintMessage(target: self, hintMessgae: "请输入手机号码")
} else if phoneNumber.text?.isValidePhoneNumber == false {
self.presentHintMessage(target: self, hintMessgae: "请输入正确的手机号码")
} else if password.text == "" {
self.presentHintMessage(target: self, hintMessgae: "请输入密码")
} else if phoneNumber.text?.isValidePhoneNumber == true {
//检查密码是否与服务器数据匹配
weak var weakSelf = self
NetWorkTool.shareInstance.UserLogin((weakSelf?.phoneNumber.text)!, password: (weakSelf?.password.text)!, type: "pas", finished: { (userInfo, error) in
if error == nil {
let userInfoDict = userInfo!
let loginStaus = userInfoDict["code"] as? String
if loginStaus == "200" {
let resultDict = userInfoDict["result"] as? NSDictionary
let token = resultDict?["token"]
// 存储手机号码
sender.savePhoneNumber(phone: (weakSelf?.phoneNumber.text!)!, token: token as! String)
let alert = UIAlertController(title: "提示", message: "登录成功", preferredStyle: .alert)
let ok = UIAlertAction(title: "好的", style: .default, handler: { (_) in
isLogin = true
//发送值到profileVC
NotificationCenter.default.post(name: isLoginNotification, object: nil)
//登陆界面销毁
weakSelf?.navigationController?.popToRootViewController(animated: true)
})
alert.addAction(ok)
weakSelf?.present(alert, animated: true, completion: nil)
}else{
SVProgressHUD.showError(withStatus:userInfoDict["msg"]! as! String )
}
}
})
} else {
self.presentHintMessage(target: self, hintMessgae: "请输入正确的手机号码")
}
}
@IBAction func loginWithIDNumber(_ sender: UIButton) {
self.navigationController?.popViewController(animated: true)
}
@IBAction func forgetPwd(_ sender: UIButton) {
print("forgetpwd")
}
@IBAction func back(_ sender: UIBarButtonItem) {
self.navigationController?.popViewController(animated: true)
}
@IBOutlet weak var bg1: UIImageView!
@IBOutlet weak var bg2: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
loadCustomAttrs()
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
view.endEditing(true)
}
func loadCustomAttrs() {
phoneNumber.changeColor()
phoneNumber.delegate = self
password.changeColor()
password.delegate = self
bg1.changeAttrs()
bg2.changeAttrs()
Nav.subviews[0].alpha = 0.5
}
}
extension LoginWithPwd: UITextFieldDelegate {
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
phoneNumber.endEditing(true)
password.endEditing(true)
return true
}
}
| apache-2.0 | 25b27d07c9b8314c5ee2afe11012323a | 32.297297 | 162 | 0.564665 | 4.934579 | false | false | false | false |
Fenrikur/ef-app_ios | Eurofurence/Modules/Announcements/View/UIKit/AnnouncementsViewController.swift | 1 | 2665 | import UIKit
class AnnouncementsViewController: UIViewController, AnnouncementsScene {
// MARK: Properties
@IBOutlet private weak var tableView: UITableView!
private var tableController: TableController? {
didSet {
tableView.dataSource = tableController
tableView.delegate = tableController
}
}
// MARK: Overrides
override func viewDidLoad() {
super.viewDidLoad()
tableView.register(AnnouncementTableViewCell.self)
delegate?.announcementsSceneDidLoad()
}
// MARK: AnnouncementsScene
private var delegate: AnnouncementsSceneDelegate?
func setDelegate(_ delegate: AnnouncementsSceneDelegate) {
self.delegate = delegate
}
func setAnnouncementsTitle(_ title: String) {
navigationItem.title = title
}
func bind(numberOfAnnouncements: Int, using binder: AnnouncementsBinder) {
tableController = TableController(numberOfAnnouncements: numberOfAnnouncements,
binder: binder,
onDidSelectRowAtIndexPath: didSelectRowAtIndexPath)
}
func deselectAnnouncement(at index: Int) {
let indexPath = IndexPath(item: index, section: 0)
tableView.deselectRow(at: indexPath, animated: true)
}
// MARK: Private
private func didSelectRowAtIndexPath(_ indexPath: IndexPath) {
delegate?.announcementsSceneDidSelectAnnouncement(at: indexPath.item)
}
private class TableController: NSObject, UITableViewDataSource, UITableViewDelegate {
private let numberOfAnnouncements: Int
private let binder: AnnouncementsBinder
private let onDidSelectRowAtIndexPath: (IndexPath) -> Void
init(numberOfAnnouncements: Int,
binder: AnnouncementsBinder,
onDidSelectRowAtIndexPath: @escaping (IndexPath) -> Void) {
self.numberOfAnnouncements = numberOfAnnouncements
self.binder = binder
self.onDidSelectRowAtIndexPath = onDidSelectRowAtIndexPath
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return numberOfAnnouncements
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeue(AnnouncementTableViewCell.self)
binder.bind(cell, at: indexPath.row)
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
onDidSelectRowAtIndexPath(indexPath)
}
}
}
| mit | 4da2ea0195d0d9430204e118dbf4ba1c | 31.5 | 104 | 0.665291 | 6.056818 | false | false | false | false |
mercadopago/px-ios | MercadoPagoSDK/MercadoPagoSDK/UI/PXHeader/PXHeaderViewModelHelper.swift | 1 | 4648 | import UIKit
// MARK: Build Helpers
extension PXResultViewModel {
func iconImageHeader() -> UIImage? {
if paymentResult.isAccepted() {
if self.paymentResult.isApproved() {
return preference.getHeaderApprovedIcon() // * **
} else if self.paymentResult.isWaitingForPayment() {
return preference.getHeaderPendingIcon()
} else if self.paymentResult.isPixOrOfflinePayment() {
return ResourceManager.shared.getImage("default_item_icon")
} else {
return preference.getHeaderImageFor(paymentResult.paymentData?.paymentMethod)
}
} else if let iconUrl = remedy?.displayInfo?.header?.iconUrl, paymentResult.isRejectedWithRemedy() {
return ViewUtils.loadImageFromUrl(iconUrl)
} else {
return preference.getHeaderRejectedIcon(paymentResult.paymentData?.paymentMethod)
}
}
func badgeImage() -> UIImage? {
if let badgeUrl = remedy?.displayInfo?.header?.badgeUrl, paymentResult.isRejectedWithRemedy() {
return ViewUtils.loadImageFromUrl(badgeUrl)
}
return ResourceManager.shared.getBadgeImageWith(status: paymentResult.status, statusDetail: paymentResult.statusDetail)
}
func titleHeader(forNewResult: Bool = false) -> NSAttributedString {
let fontSize = forNewResult ? PXNewResultHeader.TITLE_FONT_SIZE : PXHeaderRenderer.TITLE_FONT_SIZE
if self.instructionsInfo != nil {
return titleForInstructions()
}
if paymentResult.isAccepted() {
if self.paymentResult.isApproved() {
return getHeaderAttributedString(string: preference.getApprovedTitle(), size: fontSize)
} else {
return getHeaderAttributedString(string: "Estamos procesando el pago".localized, size: fontSize)
}
}
if preference.rejectedTitleSetted {
return getHeaderAttributedString(string: preference.getRejectedTitle(), size: fontSize)
}
if let title = remedy?.displayInfo?.header?.title, paymentResult.isRejectedWithRemedy() {
return getHeaderAttributedString(string: title, size: fontSize)
}
return titleForStatusDetail(statusDetail: self.paymentResult.statusDetail, paymentMethod: self.paymentResult.paymentData?.paymentMethod)
}
func titleForStatusDetail(statusDetail: String, paymentMethod: PXPaymentMethod?) -> NSAttributedString {
// Set title for remedy
if let title = remedy?.title {
return title.toAttributedString()
}
guard let paymentMethod = paymentMethod else {
return "".toAttributedString()
}
// Set title for paymentMethod
var statusDetail = statusDetail
let badFilledKey = "cc_rejected_bad_filled"
if statusDetail.contains(badFilledKey) {
statusDetail = badFilledKey
}
// Handle rejected title for custom rejected congrats
if statusDetail == PXPayment.StatusDetails.REJECTED_RAW_INSUFFICIENT_AMOUNT {
return getHeaderAttributedString(string: "px_congrats_rejected_insufficient_amount_title".localized)
} else if statusDetail == PXPayment.StatusDetails.REJECTED_CAP_EXCEEDED {
return getHeaderAttributedString(string: "px_congrats_rejected_cap_exceeded_title".localized)
}
let title = PXResourceProvider.getErrorTitleKey(statusDetail: statusDetail).localized
return getTitleForRejected(paymentMethod, title)
}
func titleForInstructions() -> NSAttributedString {
guard let instructionsInfo = self.instructionsInfo else { return "".toAttributedString() }
return getHeaderAttributedString(string: instructionsInfo.title, size: 26)
}
func getTitleForRejected(_ paymentMethod: PXPaymentMethod, _ title: String) -> NSAttributedString {
guard let paymentMethodName = paymentMethod.name else {
return getDefaultRejectedTitle()
}
return getHeaderAttributedString(string: (title.localized as NSString).replacingOccurrences(of: "{0}", with: "\(paymentMethodName)"))
}
func getDefaultRejectedTitle() -> NSAttributedString {
return getHeaderAttributedString(string: PXHeaderResutlConstants.REJECTED_HEADER_TITLE.localized)
}
func getHeaderAttributedString(string: String, size: CGFloat = PXHeaderRenderer.TITLE_FONT_SIZE) -> NSAttributedString {
return NSAttributedString(string: string, attributes: [NSAttributedString.Key.font: Utils.getFont(size: size)])
}
}
| mit | 057b49ca4659d270b7821fbcb27b3e0c | 43.692308 | 144 | 0.68438 | 5.014024 | false | false | false | false |
DianQK/rx-sample-code | YepRecord/Utils/Proposer.swift | 1 | 9633 | //
// Proposer.swift
// Lady
//
// Created by NIX on 15/7/11.
// Copyright (c) 2015年 nixWork. All rights reserved.
//
import Foundation
import AVFoundation
import Photos
import AddressBook
import Contacts
import EventKit
import CoreLocation
class LocationDelegate: NSObject, CLLocationManagerDelegate {
let locationUsage: PrivateResource.LocationUsage
let successAction: ProposerAction
let failureAction: ProposerAction
init(locationUsage: PrivateResource.LocationUsage, successAction: @escaping ProposerAction, failureAction: @escaping ProposerAction) {
self.locationUsage = locationUsage
self.successAction = successAction
self.failureAction = failureAction
}
func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
DispatchQueue.main.async {
switch status {
case .authorizedWhenInUse:
self.locationUsage == .whenInUse ? self.successAction() : self.failureAction()
Proposer._locationManager = nil
Proposer._locationDelegate = nil
case .authorizedAlways:
self.locationUsage == .always ? self.successAction() : self.failureAction()
Proposer._locationManager = nil
Proposer._locationDelegate = nil
case .denied:
self.failureAction()
Proposer._locationManager = nil
Proposer._locationDelegate = nil
default:
break
}
}
}
}
struct Proposer {
static fileprivate var _locationManager: LocationDelegate?
static fileprivate var _locationDelegate: LocationDelegate? // as strong ref
}
public enum PrivateResource {
case photos
case camera
case microphone
case contacts
case reminders
case calendar
public enum LocationUsage {
case whenInUse
case always
}
case location(LocationUsage)
public var isNotDeterminedAuthorization: Bool {
switch self {
case .photos:
return PHPhotoLibrary.authorizationStatus() == .notDetermined
case .camera:
return AVCaptureDevice.authorizationStatus(forMediaType: AVMediaTypeVideo) == .notDetermined
case .microphone:
return AVAudioSession.sharedInstance().recordPermission() == .undetermined
case .contacts:
return CNContactStore.authorizationStatus(for: CNEntityType.contacts) == .notDetermined
case .reminders:
return EKEventStore.authorizationStatus(for: .reminder) == .notDetermined
case .calendar:
return EKEventStore.authorizationStatus(for: .event) == .notDetermined
case .location:
return CLLocationManager.authorizationStatus() == .notDetermined
}
}
public var isAuthorized: Bool {
switch self {
case .photos:
return PHPhotoLibrary.authorizationStatus() == .authorized
case .camera:
return AVCaptureDevice.authorizationStatus(forMediaType: AVMediaTypeVideo) == .authorized
case .microphone:
return AVAudioSession.sharedInstance().recordPermission() == .granted
case .contacts:
return CNContactStore.authorizationStatus(for: CNEntityType.contacts) == .authorized
case .reminders:
return EKEventStore.authorizationStatus(for: .reminder) == .authorized
case .calendar:
return EKEventStore.authorizationStatus(for: .event) == .authorized
case let .location(usage):
switch usage {
case .whenInUse:
return CLLocationManager.authorizationStatus() == .authorizedWhenInUse
case .always:
return CLLocationManager.authorizationStatus() == .authorizedAlways
}
}
}
}
public typealias Propose = () -> Void
public typealias ProposerAction = () -> Void
public func proposeToAccess(_ resource: PrivateResource, agreed successAction: @escaping ProposerAction, rejected failureAction: @escaping ProposerAction) {
func proposeToAccessEvent(for entityYype: EKEntityType, agreed successAction: @escaping ProposerAction, rejected failureAction: @escaping ProposerAction) {
switch EKEventStore.authorizationStatus(for: entityYype) {
case .authorized:
successAction()
case .notDetermined:
EKEventStore().requestAccess(to: entityYype) { granted, error in
DispatchQueue.main.async {
if granted {
successAction()
} else {
failureAction()
}
}
}
default:
failureAction()
}
}
switch resource {
case .photos:
proposeToAccessPhotos(agreed: successAction, rejected: failureAction)
case .camera:
proposeToAccessCamera(agreed: successAction, rejected: failureAction)
case .microphone:
func proposeToAccessMicrophone(agreed successAction: @escaping ProposerAction, rejected failureAction: @escaping ProposerAction) {
AVAudioSession.sharedInstance().requestRecordPermission { granted in
DispatchQueue.main.async {
granted ? successAction() : failureAction()
}
}
}
proposeToAccessMicrophone(agreed: successAction, rejected: failureAction)
case .contacts:
proposeToAccessPhotos(agreed: successAction, rejected: failureAction)
case .reminders:
proposeToAccessEvent(for: .reminder, agreed: successAction, rejected: failureAction)
case .calendar:
proposeToAccessEvent(for: .event, agreed: successAction, rejected: failureAction)
case .location(let usage):
func proposeToAccessLocation(_ locationUsage: PrivateResource.LocationUsage, agreed successAction: ProposerAction, rejected failureAction: ProposerAction) {
switch CLLocationManager.authorizationStatus() {
case .authorizedWhenInUse:
if locationUsage == .whenInUse {
successAction()
} else {
failureAction()
}
case .authorizedAlways:
successAction()
case .notDetermined:
if CLLocationManager.locationServicesEnabled() {
// let locationManager = CLLocationManager()
// Proposer._locationManager = locationManager
// let delegate = LocationDelegate(locationUsage: locationUsage, successAction: successAction, failureAction: failureAction)
// Proposer._locationDelegate = delegate
//// locationManager.delegate = delegate
//
// switch locationUsage {
//
// case .whenInUse:
// locationManager.requestWhenInUseAuthorization()
//
// case .always:
// locationManager.requestAlwaysAuthorization()
// }
//
// locationManager.startUpdatingLocation()
//
} else {
failureAction()
}
default:
failureAction()
}
}
proposeToAccessLocation(usage, agreed: successAction, rejected: failureAction)
}
}
private func proposeToAccessPhotos(agreed successAction: @escaping ProposerAction, rejected failureAction: @escaping ProposerAction) {
PHPhotoLibrary.requestAuthorization { status in
DispatchQueue.main.async {
switch status {
case .authorized:
successAction()
default:
failureAction()
}
}
}
}
private func proposeToAccessCamera(agreed successAction: @escaping ProposerAction, rejected failureAction: @escaping ProposerAction) {
AVCaptureDevice.requestAccess(forMediaType: AVMediaTypeVideo) { granted in
DispatchQueue.main.async {
granted ? successAction() : failureAction()
}
}
func proposeToAccessMicrophone(agreed successAction: @escaping ProposerAction, rejected failureAction: @escaping ProposerAction) {
AVAudioSession.sharedInstance().requestRecordPermission { granted in
DispatchQueue.main.async {
granted ? successAction() : failureAction()
}
}
}
//private func proposeToAccessContacts(agreed successAction: ProposerAction, rejected failureAction: ProposerAction) {
//
// switch CNContactStore.authorizationStatus(for: .contacts) {
//
// case .authorized:
// successAction()
//
// case .notDetermined:
// CNContactStore().requestAccess(for: .contacts) { granted, error in
// DispatchQueue.main.async {
// if granted {
// successAction()
// } else {
// failureAction()
// }
// }
// }
//
// default:
// failureAction()
// }
//
//}
}
| mit | b3433c65785b6fb14da9e95e8de0bc19 | 33.031802 | 164 | 0.592877 | 5.69208 | false | false | false | false |
KevinYangGit/DYTV | DYZB/DYZB/Classes/Main/View/CollectionBaseCell.swift | 1 | 1077 | //
// CollectionBaseCell.swift
// DYZB
//
// Created by boxfishedu on 2016/10/15.
// Copyright © 2016年 杨琦. All rights reserved.
//
import UIKit
import Kingfisher
class CollectionBaseCell: UICollectionViewCell {
@IBOutlet weak var iconImageView: UIImageView!
@IBOutlet weak var onlineBtn: UIButton!
@IBOutlet weak var nickNameLabel: UILabel!
var anchor : AnchorModel? {
didSet {
//校验模型是否有值
guard let anchor = anchor else { return }
var onlineStr : String = ""
if anchor.online >= 10000 {
onlineStr = "\(Int(anchor.online / 10000))万在线"
} else {
onlineStr = "\(Int(anchor.online))在线"
}
onlineBtn.setTitle(onlineStr, for: .normal)
nickNameLabel.text = anchor.nickname
guard let iconURL = URL(string: anchor.vertical_src) else { return }
iconImageView.kf.setImage(with: iconURL)
}
}
}
| mit | 18e796be4cd4bb0f069b81aff71731ec | 25.1 | 80 | 0.554598 | 4.833333 | false | false | false | false |
Swift3Home/Swift3_Object-oriented | TLReflection/TLReflection/AppDelegate.swift | 1 | 4009 | //
// AppDelegate.swift
// TLReflection
//
// Created by lichuanjun on 2017/6/8.
// Copyright © 2017年 lichuanjun. All rights reserved.
//
import UIKit
/// Xcode 8.0 OC的NSLog 都不能在控制台输出,所有和OC相关的错误,控制台同样无法显示
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
/**
1. 知道 Swift 中有命名空间
- 在同一个命名空间,全局共享
- 第三方框架使用 Swift 如果直接拖拽到项目中,从属于同一个命名空间,很有可能冲突
- 以后尽量都要用 cocoapod
2. 重点要知道 Swift 中 NSClassFromString(反射机制)的写法
- 反射最重要的目的,就是为了解耦
- 搜索`反射机制和工厂方法`
- 提示:第一印象会发现一个简单的功能,写的很复杂
- 但是,封装的很好,而且弹性很大
*/
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// 代码中的 ?都是 `可选`解包,发送消息,不参与计算
// 1. 实例化 window
window = UIWindow()
window?.backgroundColor = UIColor.white
// 输出 info.plist 的内容
// [String : Any]?
// print(Bundle.main.infoDictionary)
// Any?
// let ns = Bundle.main.infoDictionary?["CFBundleName"] as? String ?? ""
// 利用函数调用
// let ns = Bundle.main.namespace()
// 利用计算型属性
let ns = Bundle.main.namespace
// 2. 设置 根控制器,需要添加命令空间 -> 默认就是`项目名称(最好不要有数字和特殊符号)`
// 2.1 反射机制
let clsName = ns + "." + "ViewController"
// AnyClass? -> 视图控制器的类型
let cls = NSClassFromString(clsName) as? UIViewController.Type
// 使用类创建视图控制器
// UIViewController?
let vc = cls?.init()
// 2.2常规用法
// let vc = ViewController()
window?.rootViewController = vc
// 3. 显示 window
window?.makeKeyAndVisible()
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| mit | f8b96d8acf713da2cfcd1a9f3a982be7 | 36.978022 | 285 | 0.666088 | 4.453608 | false | false | false | false |
ontouchstart/swift3-playground | Learn to Code 2.playgroundbook/Contents/Sources/Scene.swift | 2 | 11898 | //
// Scene.swift
//
// Copyright (c) 2016 Apple Inc. All Rights Reserved.
//
import SceneKit
/// Reports changes to the worlds state.
protocol SceneStateDelegate: class {
func scene(_ scene: Scene, didEnterState: Scene.State)
}
extension Notification.Name {
/// Indicates that the `Scene.state == .done`.
static let scenePlaybackDidComplete = Notification.Name(rawValue: "ScenePlaybackDidComplete")
}
public final class Scene: NSObject {
// MARK: Types
enum State {
/// The starting state of the scene before anything has been added.
case initial
/// The state after all inanimate elements have been placed.
case built
/// The state which rewinds the `commandQueue` in preparation for playback.
case ready
/// The state which starts running commands in the `commandQueue`.
case run
/// The final state after all commands have been run.
case done
}
enum EffectsLevel: Int {
case high, med, low
}
// MARK: Properties
private let source: SCNSceneSource
var backgroundAudio: SCNAudioPlayer?
let gridWorld: GridWorld
/// The queue which all commands are added to before being run.
public var commandQueue: CommandQueue {
return gridWorld.commandQueue
}
lazy var scnScene: SCNScene = {
let scene: SCNScene
do {
scene = try self.source.scene(options: nil)
}
catch {
presentAlert(title: "Failed To Load Scene.", message: "\(error)")
fatalError("Failed To Load Scene.\n\(error)")
}
// Remove the old grid node that exists in loaded scenes.
scene.rootNode.childNode(withName: GridNodeName, recursively: false)?.removeFromParentNode()
scene.rootNode.addChildNode(self.gridWorld.grid.scnNode)
// Give the `rootNode` a name for easy lookup.
scene.rootNode.name = "rootNode"
// Load the skybox.
let skyBoxPath = WorldConfiguration.texturesDir + "zon_bg_skyBox_a_DIFF"
scene.background.contents = Bundle.main.url(forResource: skyBoxPath, withExtension: "png") as? AnyObject
// self.positionCameraToFitGrid(around: scene.rootNode)
self.adjustDirectionalLight(in: scene.rootNode)
self.cleanupScene(scene)
scene.rootNode.childNode(withName: "Templates", recursively: false)?.removeFromParentNode()
return scene
}()
var rootNode: SCNNode {
return scnScene.rootNode
}
weak var delegate: SceneStateDelegate?
/// Actors operating within this scene.
var actors: [Actor] {
return gridWorld.grid.actors
}
var mainActor: Actor? {
return actors.first
}
/// The duration used when rewinding the scene.
var resetDuration: TimeInterval = 0.0
var state: State = .initial {
didSet {
let newState = state
enterState(newState)
delegate?.scene(self, didEnterState: newState)
}
}
// Effect Nodes
lazy var highEffectsNode: SCNNode? = self.rootNode.childNode(withName: "HIGH_QUALITY_FX", recursively: true)
lazy var lowEffectsNode: SCNNode? = self.rootNode.childNode(withName: "LOW_QUALITY_FX", recursively: true)
var directionLight: SCNLight? = nil
var effectsLevel: EffectsLevel = .high {
didSet {
let med = EffectsLevel.med.rawValue
highEffectsNode?.isHidden = effectsLevel != .high
lowEffectsNode?.isHidden = effectsLevel.rawValue > med
directionLight?.shadowMapSize = effectsLevel.rawValue >= med ? CGSize(width: 1024, height: 1024) : CGSize(width: 2048, height: 2048)
let shadowPath = WorldConfiguration.texturesDir + "blobShadow"
directionLight?.gobo!.contents = effectsLevel.rawValue >= med ? Bundle.main.url(forResource: shadowPath, withExtension: "jpg") : nil
// Destructive
if effectsLevel == .low {
rootNode.enumerateChildNodes { node, _ in
for system in node.particleSystems ?? [] {
node.removeParticleSystem(system)
}
}
scnScene.fogStartDistance = 0
scnScene.fogEndDistance = 0
}
}
}
// MARK: Initialization
public init(world: GridWorld) {
gridWorld = world
// Load template scene.
let worldTemplatePath = WorldConfiguration.customDir + "WorldTemplate"
let worldURL = Bundle.main.url(forResource: worldTemplatePath, withExtension: "scn")!
source = SCNSceneSource(url: worldURL, options: nil)!
}
public init(source: SCNSceneSource) throws {
self.source = source
// Check for `GridNodeName` node.
guard let baseGridNode = source.entry(withID: GridNodeName, ofType: SCNNode.self) else {
throw GridLoadingError.missingGridNode(GridNodeName)
}
gridWorld = GridWorld(node: baseGridNode)
super.init()
// Ensure at least one tile node is contained in the scene as the floor node.
guard !gridWorld.existingNodes(ofType: Block.self, at: gridWorld.allPossibleCoordinates).isEmpty else {
throw GridLoadingError.missingFloor("No nodes of with name `Block` were found.")
}
let cols = gridWorld.columnCount
let rows = gridWorld.rowCount
guard cols > 0 && rows > 0 else { throw GridLoadingError.invalidDimensions(cols, rows) }
}
/// Expects an ".scn" scene.
public convenience init(named sceneName: String) throws {
let path = WorldConfiguration.resourcesDir + "_Scenes/" + sceneName
guard
let sceneURL = Bundle.main.url(forResource: path, withExtension: "scn"),
let source = SCNSceneSource(url: sceneURL, options: nil) else {
throw GridLoadingError.invalidSceneName(sceneName)
}
try self.init(source: source)
}
// MARK: Scene Adjustments
func enterState(_ newState: State) {
switch newState {
case .initial:
break
case .built:
// Never animate `built` steps.
gridWorld.applyChanges() {
gridWorld.verifyNodePositions()
}
case .ready:
SCNTransaction.begin()
SCNTransaction.animationDuration = resetDuration
// Reset the state of the world for playback.
commandQueue.rewind()
SCNTransaction.commit()
// Remove quads between blocks.
gridWorld.removeHiddenQuads()
gridWorld.calculateRowColumnCount()
case .run:
if commandQueue.isFinished {
// If there are no commands, mark the scene as done.
state = .done
}
else {
commandQueue.runMode = .continuous
commandQueue.runCommand(atIndex: 0)
}
case .done:
// Recalculate the dimensions of the world for any placed items.
gridWorld.calculateRowColumnCount()
NotificationCenter.default.post(name: .scenePlaybackDidComplete, object: self)
}
}
func adjustDirectionalLight(in node: SCNNode) {
guard let lightNode = node.childNode(withName: DirectionalLightName, recursively: true) else { return }
var light: SCNLight?
lightNode.enumerateHierarchy { node, stop in
if let directional = node.light {
light = directional
stop.initialize(to: true)
}
}
directionLight = light
light?.orthographicScale = 10
light?.shadowMapSize = CGSize(width: 2048, height: 2048)
let childNodes = Set(node.childNodes).subtracting([gridWorld.grid.scnNode])
for node in childNodes {
node.enumerateChildNodes { child, _ in
child.castsShadow = false
}
}
}
func positionCameraToFitGrid(around node: SCNNode) {
// Set up the camera.
let cameraNode = node.childNode(withName: "camera", recursively: true)!
if let gridRootNode = node.childNode(withName: "Scenery", recursively: true)?.childNode(withName: "base", recursively: true) {
var (_, sceneWidth) = gridRootNode.boundingSphere
sceneWidth *= 2.5 // expand to 300% so we make sure to get the whole thing with a bit of overlap
// set original FOV, camera FOV and current FOV
let cameraDistance = Double(cameraNode.position.z)
let halfSceneWidth = Double(sceneWidth / 2.0)
let distanceToEdge = sqrt(cameraDistance * cameraDistance + halfSceneWidth * halfSceneWidth)
let cos = cameraDistance / distanceToEdge
let sin = halfSceneWidth / distanceToEdge
let halfAngle = atan2(sin, cos)
cameraNode.camera?.yFov = 2.0 * halfAngle * 180.0 / M_PI
}
else {
let dominateDimension = SCNFloat(max(gridWorld.rowCount, gridWorld.columnCount))
// Formula calculated from linear regression of 7 maps.
cameraNode.position.z = 3.8488 * dominateDimension - 9.5
}
}
/// Removes unnecessary adornments in scene file.
func cleanupScene(_ scene: SCNScene) {
let root = scene.rootNode
let bokeh = root.childNode(withName: "bokeh particles", recursively: true)
bokeh?.removeFromParentNode()
let reflectionPlane = root.childNode(withName: "reflections", recursively: true)
reflectionPlane?.removeFromParentNode()
// Flatten scenery elements.
func flattenSwap(node: SCNNode) {
let flatNode = node.flattenedClone()
flatNode.transform = node.transform
node.parent?.addChildNode(flatNode)
node.removeFromParentNode()
}
let sceneryNode = root.childNode(withName: "Scenery", recursively: false)
let flattenableIdentifiers = [
"",
// "PROPS_BELOW",
// "PROPS_ABOVE",
// "ACTIVE_FLOOR"
]
for id in flattenableIdentifiers {
if let node = sceneryNode?.childNode(withName: id, recursively: true) {
flattenSwap(node: node)
}
}
}
/// Adds `backgroundAudio` to the rootNode, starting playback.
func startBackgroundAudio() {
guard let url = Bundle.main.url(forResource: "Background", withExtension: "wav", subdirectory: "Audio") else { return }
let source = SCNAudioSource(url: url)!
source.load()
source.isPositional = false
source.loops = true
source.volume = 0.2
backgroundAudio = SCNAudioPlayer(source: source)
rootNode.addAudioPlayer(backgroundAudio!)
}
/// Reset's the scene in preparation for another run.
func reset(duration: TimeInterval) {
resetDuration = duration
// Rewinds the commandQueue to correct all world state.
state = .ready
// Remove all commands from previous run.
commandQueue.clear()
// Clear any items no longer in the world from the previous run.
// (Before receiving more commands).
gridWorld.grid.removeItemsNotInWorld()
}
}
| mit | 307cc88919223231460b0ffa27842d81 | 33.789474 | 148 | 0.5922 | 4.951311 | false | false | false | false |
icapps/ios-air-rivet | Example/Tests/TestHelpers/MockModel.swift | 3 | 723 | import Faro
class MockModel: Decodable {
var uuid: String?
}
extension MockModel: Updatable {
func update(_ model: AnyObject) throws {
guard let model = model as? MockModel else {
return
}
uuid = model.uuid
}
func update(array: [AnyObject]) throws {
guard let array = array as? [MockModel] else {
return
}
let set = Set(array)
guard let model = (set.first {$0 == self}) else {
return
}
try update(model)
}
var hashValue: Int {
return uuid?.hashValue ?? 0
}
static func == (lhs: MockModel, rhs: MockModel) -> Bool {
return lhs.hashValue == rhs.hashValue
}
}
| mit | d8ad16d30856504744907fffdc2ac597 | 20.264706 | 61 | 0.540802 | 4.179191 | false | false | false | false |
macemmi/HBCI4Swift | HBCI4Swift/HBCI4Swift/Source/Syntax/HBCISyntaxElementReference.swift | 1 | 1189 | //
// HBCISyntaxElementReference.swift
// HBCIBackend
//
// Created by Frank Emminghaus on 22.12.14.
// Copyright (c) 2014 Frank Emminghaus. All rights reserved.
//
import Foundation
class HBCISyntaxElementReference {
let name:String!
let minnum:Int
let maxnum:Int
let elemDescr: HBCISyntaxElementDescription;
init(element:XMLElement, description: HBCISyntaxElementDescription) throws {
self.elemDescr = description;
var num = element.valueForAttribute("minnum")
if num != nil {
self.minnum = Int(num!) ?? 1
} else {
self.minnum = 1;
}
num = element.valueForAttribute("maxnum")
if num != nil {
self.maxnum = Int(num!) ?? 1
} else {
self.maxnum = 1;
}
if let name = element.valueForAttribute("name") {
self.name = name;
} else if let name = element.valueForAttribute("type") {
self.name = name;
} else {
logInfo("Missing attribute 'name' in element \(element.description)");
self.name = "<unknown>";
throw HBCIError.syntaxFileError;
}
}
}
| gpl-2.0 | d59d62259a923c2aef5dab8472285319 | 26.022727 | 82 | 0.577796 | 4.276978 | false | false | false | false |
AutosoftDMS/SignalR-Swift | SignalR-Swift/Transports/HttpTransport.swift | 1 | 4750 | //
// HttpTransport.swift
// SignalR-Swift
//
//
// Copyright © 2017 Jordan Camara. All rights reserved.
//
import Foundation
import Alamofire
public class HttpTransport: ClientTransportProtocol {
public var name: String? {
return ""
}
public var supportsKeepAlive: Bool {
return false
}
var startedAbort: Bool = false
public func negotiate(connection: ConnectionProtocol, connectionData: String?, completionHandler: ((NegotiationResponse?, Error?) -> ())?) {
let url = connection.url.appending("negotiate")
let parameters = self.getConnectionParameters(connection: connection, connectionData: connectionData)
let encodedRequest = connection.getRequest(url: url, httpMethod: .get, encoding: URLEncoding.default, parameters: parameters, timeout: 30.0)
encodedRequest.validate().responseJSON { (response: DataResponse<Any>) in
switch response.result {
case .success(let result):
if let json = result as? [String: Any] {
completionHandler?(NegotiationResponse(jsonObject: json), nil)
}
else {
completionHandler?(nil, AFError.responseSerializationFailed(reason: .inputDataNil))
}
case .failure(let error):
completionHandler?(nil, error)
}
}
}
public func start(connection: ConnectionProtocol, connectionData: String?, completionHandler: ((Any?, Error?) -> ())?) {
}
public func send(connection: ConnectionProtocol, data: Any, connectionData: String?, completionHandler: ((Any?, Error?) -> ())?) {
let url = connection.url.appending("send")
let parameters = self.getConnectionParameters(connection: connection, connectionData: connectionData)
var encodedRequestURL = url
do {
let originalRequest = try URLRequest(url: url, method: .get, headers: nil)
encodedRequestURL = try URLEncoding.queryString.encode(originalRequest, with: parameters).url!.absoluteString
} catch {
}
var requestParams = [String: Any]()
if let dataString = data as? String {
requestParams["data"] = dataString
} else if let dataDict = data as? [String: Any] {
requestParams = dataDict
}
let request = connection.getRequest(url: encodedRequestURL, httpMethod: .post, encoding: URLEncoding.httpBody, parameters: requestParams)
request.validate().responseJSON { (response: DataResponse<Any>) in
switch response.result {
case .success(let result):
connection.didReceiveData(data: result)
if let handler = completionHandler {
handler(result, nil)
}
case .failure(let error):
connection.didReceiveError(error: error)
if let handler = completionHandler {
handler(nil, error)
}
}
}
}
func completeAbort() {
self.startedAbort = true
}
func tryCompleteAbort() -> Bool {
return startedAbort
}
public func lostConnection(connection: ConnectionProtocol) {
}
public func abort(connection: ConnectionProtocol, timeout: Double, connectionData: String?) {
guard timeout > 0, !self.startedAbort else { return }
self.startedAbort = true
let url = connection.url.appending("abort")
let parameters = self.getConnectionParameters(connection: connection, connectionData: connectionData)
let encodedRequest = connection.getRequest(url: url, httpMethod: .get, encoding: URLEncoding.default, parameters: parameters, timeout: 2.0)
let request = connection.getRequest(url: encodedRequest.request!.url!.absoluteString, httpMethod: .post, encoding: URLEncoding.httpBody, parameters: nil)
request.validate().response { response in
if response.error != nil {
self.completeAbort()
}
}
}
func getConnectionParameters(connection: ConnectionProtocol, connectionData: String?) -> [String: Any] {
var parameters: [String: Any] = [
"clientProtocol": connection.version.description,
"transport": self.name ?? "",
"connectionData": connectionData ?? "",
"connectionToken": connection.connectionToken ?? "",
]
if let queryString = connection.queryString {
for (key, value) in queryString {
parameters[key] = value
}
}
return parameters
}
}
| mit | 431cd9e3db3436044382a28e608965a4 | 33.919118 | 161 | 0.610444 | 5.247514 | false | false | false | false |
m-schmidt/PopoverRestoration | PopoverRestoration/UIViewControllerRestorationExtension.swift | 1 | 2697 | //
// UIViewControllerRestorationExtension.swift
//
import UIKit
// Protocol for view controllers that want to present restorable popovers
protocol PopoverRestorationDelegate: UIPopoverPresentationControllerDelegate {
// The source view and rectangle that presents the popover
func popoverSourceView() -> UIView?
func popoverSourceRect() -> CGRect
// Allowed arrow directions for the popover
func popoverArrowDirection() -> UIPopoverArrowDirection
}
// Default implementations
extension PopoverRestorationDelegate {
func popoverSourceRect() -> CGRect {
return popoverSourceView()?.bounds ?? CGRect.zero
}
func popoverArrowDirection() -> UIPopoverArrowDirection {
return .any
}
}
// Key for encoding of popoverPresentationController's configuration
private let keySourceViewController = "popoverRestorationSourceViewController"
extension UIViewController {
func encodePopoverState(with coder: NSCoder) {
if let pc = presentingViewController as? PopoverRestorationDelegate {
if (pc.popoverSourceView()) != nil {
// Store a reference to the presenting view controller
coder.encode(presentingViewController, forKey: keySourceViewController)
}
}
}
func decodePopoverState(with coder: NSCoder) {
if let sourceViewController = coder.decodeObject(forKey: keySourceViewController) as? PopoverRestorationDelegate {
if let sourceView = sourceViewController.popoverSourceView() {
// Original style as from storyboard
let originalModalPresentationStyle = modalPresentationStyle
// Switch to popover-style and access presentationController to trigger creation of a UIPopoverPresentationController
modalPresentationStyle = .popover
if let pc = presentationController as? UIPopoverPresentationController {
// Enforce layout to place sourceView at correct location
if let svc = sourceViewController as? UIViewController {
svc.view.layoutIfNeeded()
}
// Restore configuration for popoverPresentationController
pc.delegate = sourceViewController
pc.sourceView = sourceView
pc.sourceRect = sourceViewController.popoverSourceRect()
pc.permittedArrowDirections = sourceViewController.popoverArrowDirection()
}
// Revert to original style
modalPresentationStyle = originalModalPresentationStyle
}
}
}
}
| bsd-3-clause | 74cc09b3dee71faffe02bc4003ad5840 | 32.7125 | 133 | 0.670004 | 6.827848 | false | false | false | false |
zhaoxiangyulove/Zachary-s-Programs | Weather/Weather/libs/ElasticTransition/ElasticTransition.swift | 2 | 18671 | /*
The MIT License (MIT)
Copyright (c) 2015 Luke Zhao <[email protected]>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
import UIKit
public enum ElasticTransitionBackgroundTransform:Int{
case None, Rotate, TranslateMid, TranslatePull, TranslatePush
}
@available(iOS 7.0, *)
@objc
public protocol ElasticMenuTransitionDelegate{
optional var contentLength:CGFloat {get}
optional var dismissByBackgroundTouch:Bool {get}
optional var dismissByBackgroundDrag:Bool {get}
optional var dismissByForegroundDrag:Bool {get}
}
func avg(a:CGFloat, _ b:CGFloat) -> CGFloat{
return (a+b)/2
}
@available(iOS 7.0, *)
public class ElasticTransition: EdgePanTransition, UIGestureRecognizerDelegate{
override
public var edge:Edge{
didSet{
navigationExitPanGestureRecognizer.edges = [edge.opposite().toUIRectEdge()]
}
}
/**
The curvature of the elastic edge.
lower radiusFactor means higher curvature
value is clamped between 0 to 0.5
*/
public var radiusFactor:CGFloat = 0.5
/**
Determines whether or not the view edge will stick to
the initial position when dragged.
**Only effective when doing a interactive transition**
*/
public var sticky:Bool = true
/**
The initial position of the simulated drag when static animation is performed
i.e. The static animation will behave like user is dragging from this point
**Only effective when doing a static transition**
*/
public var startingPoint:CGPoint?
/**
The background color of the container when doing the transition
default:
```
UIColor(red: 152/255, green: 174/255, blue: 196/255, alpha: 1.0)
```
*/
public var containerColor:UIColor = UIColor(red: 152/255, green: 174/255, blue: 196/255, alpha: 1.0)
/**
The color of the overlay when doing the transition
default:
```
UIColor(red: 152/255, green: 174/255, blue: 196/255, alpha: 0.5)
```
*/
public var overlayColor:UIColor = UIColor(red: 152/255, green: 174/255, blue: 196/255, alpha: 0.5)
/**
Whether or not to display the shadow. Will decrease performance.
default: false
*/
public var showShadow:Bool = false
/**
The shadow color of the container when doing the transition
default:
```
UIColor(red: 100/255, green: 122/255, blue: 144/255, alpha: 1.0)
```
*/
public var shadowColor:UIColor = UIColor(red: 100/255, green: 122/255, blue: 144/255, alpha: 1.0)
/**
The shadow color of the container when doing the transition
default:
```
UIColor(red: 100/255, green: 122/255, blue: 144/255, alpha: 1.0)
```
*/
public var frontViewBackgroundColor:UIColor?
/**
The shadow radius of the container when doing the transition
default:
```
50
```
*/
public var shadowRadius:CGFloat = 50
// custom transform function
public var transform:((progress:CGFloat, view:UIView) -> Void)?
// Transform Type
public var transformType:ElasticTransitionBackgroundTransform = .TranslateMid{
didSet{
if container != nil{
container.layoutIfNeeded()
}
}
}
// track using translation or direct touch position
public var useTranlation = true
public var damping:CGFloat = 0.2{
didSet{
damping = min(1.0, max(0.0, damping))
}
}
var maskLayer = CALayer()
var animator:UIDynamicAnimator!
var cc:DynamicItem!
var lc:DynamicItem!
var cb:CustomSnapBehavior!
var lb:CustomSnapBehavior!
var contentLength:CGFloat = 0
var lastPoint:CGPoint = CGPointZero
var stickDistance:CGFloat{
return sticky ? contentLength * panThreshold : 0
}
var overlayView = UIView()
var shadowView = UIView()
var shadowMaskLayer = ElasticShapeLayer()
func finalPoint(presenting:Bool? = nil) -> CGPoint{
let p = presenting ?? self.presenting
switch edge{
case .Left:
return p ? CGPointMake(contentLength, dragPoint.y) : CGPointMake(0, dragPoint.y)
case .Right:
return p ? CGPointMake(size.width - contentLength, dragPoint.y) : CGPointMake(size.width, dragPoint.y)
case .Bottom:
return p ? CGPointMake(dragPoint.x, size.height - contentLength) : CGPointMake(dragPoint.x, size.height)
case .Top:
return p ? CGPointMake(dragPoint.x, contentLength) : CGPointMake(dragPoint.x, 0)
}
}
func translatedPoint() -> CGPoint{
let initialPoint = self.finalPoint(!self.presenting)
switch edge{
case .Left, .Right:
return CGPointMake(max(0,min(size.width,initialPoint.x+translation.x)), initialPoint.y)
case .Top,.Bottom:
return CGPointMake(initialPoint.x, max(0,min(size.height,initialPoint.y+translation.y)))
}
}
var pushedControllers:[UIViewController] = []
var backgroundExitPanGestureRecognizer = UIPanGestureRecognizer()
var foregroundExitPanGestureRecognizer = UIPanGestureRecognizer()
var navigationExitPanGestureRecognizer = UIScreenEdgePanGestureRecognizer()
public func gestureRecognizerShouldBegin(gestureRecognizer: UIGestureRecognizer) -> Bool {
return !transitioning
}
public func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldReceiveTouch touch: UITouch) -> Bool {
if touch.view!.isKindOfClass(UISlider.self) {
return false
}
if gestureRecognizer == navigationExitPanGestureRecognizer{
return true
}
if let vc = pushedControllers.last{
if let delegate = vc as? ElasticMenuTransitionDelegate {
if gestureRecognizer==backgroundExitPanGestureRecognizer{
return delegate.dismissByBackgroundDrag ?? false
}else if gestureRecognizer==foregroundExitPanGestureRecognizer{
return delegate.dismissByForegroundDrag ?? false
}
}
}
return false;
}
func handleOffstagePan(pan: UIPanGestureRecognizer){
if let vc = pushedControllers.last{
switch (pan.state) {
case UIGestureRecognizerState.Began:
if pan == navigationExitPanGestureRecognizer{
navigation = true
}
dissmissInteractiveTransition(vc, gestureRecognizer: pan, completion: nil)
default:
updateInteractiveTransition(gestureRecognizer: pan)
}
}
}
public override init(){
super.init()
backgroundExitPanGestureRecognizer.delegate = self
backgroundExitPanGestureRecognizer.addTarget(self, action:"handleOffstagePan:")
foregroundExitPanGestureRecognizer.delegate = self
foregroundExitPanGestureRecognizer.addTarget(self, action:"handleOffstagePan:")
navigationExitPanGestureRecognizer.delegate = self
navigationExitPanGestureRecognizer.addTarget(self, action:"handleOffstagePan:")
navigationExitPanGestureRecognizer.edges = [edge.opposite().toUIRectEdge()]
shadowView.layer.addSublayer(shadowMaskLayer)
let tapGR = UITapGestureRecognizer(target: self, action: "overlayTapped:")
overlayView.opaque = false
overlayView.addGestureRecognizer(tapGR)
shadowView.opaque = false
shadowView.layer.masksToBounds = false
}
func overlayTapped(tapGR:UITapGestureRecognizer){
if let vc = pushedControllers.last,
let delegate = vc as? ElasticMenuTransitionDelegate {
let touchToDismiss = delegate.dismissByBackgroundTouch ?? false
if touchToDismiss{
vc.dismissViewControllerAnimated(true, completion:nil)
}
}
}
override func update() {
super.update()
if cb != nil && lb != nil{
let initialPoint = self.finalPoint(!self.presenting)
let p = (useTranlation && interactive) ? translatedPoint() : dragPoint
switch edge{
case .Left:
cb.point = CGPointMake(p.x < contentLength ? p.x : (p.x-contentLength)/3+contentLength, dragPoint.y)
lb.point = CGPointMake(min(contentLength, p.distance(initialPoint) < stickDistance ? initialPoint.x : p.x), dragPoint.y)
case .Right:
let maxX = size.width - contentLength
cb.point = CGPointMake(p.x > maxX ? p.x : maxX - (maxX - p.x)/3, dragPoint.y)
lb.point = CGPointMake(max(maxX, p.distance(initialPoint) < stickDistance ? initialPoint.x : p.x), dragPoint.y)
case .Bottom:
let maxY = size.height - contentLength
cb.point = CGPointMake(dragPoint.x, p.y > maxY ? p.y : maxY - (maxY - p.y)/3)
lb.point = CGPointMake(dragPoint.x, max(maxY, p.distance(initialPoint) < stickDistance ? initialPoint.y : p.y))
case .Top:
cb.point = CGPointMake(dragPoint.x, p.y < contentLength ? p.y : (p.y-contentLength)/3+contentLength)
lb.point = CGPointMake(dragPoint.x, min(contentLength, p.distance(initialPoint) < stickDistance ? initialPoint.y : p.y))
}
}
}
func updateShape(){
if animator == nil{
return
}
backView.layer.zPosition = 0
overlayView.layer.zPosition = 298
shadowView.layer.zPosition = 299
frontView.layer.zPosition = 300
let finalPoint = self.finalPoint(true)
let initialPoint = self.finalPoint(false)
let progress = 1 - lc.center.distance(finalPoint) / initialPoint.distance(finalPoint)
switch edge{
case .Left:
frontView.frame.origin.x = min(cc.center.x, lc.center.x) - contentLength
shadowMaskLayer.frame = CGRectMake(0, 0, lc.center.x, size.height)
case .Right:
frontView.frame.origin.x = max(cc.center.x, lc.center.x)
shadowMaskLayer.frame = CGRectMake(lc.center.x, 0, size.width - lc.center.x, size.height)
case .Bottom:
frontView.frame.origin.y = max(cc.center.y, lc.center.y)
shadowMaskLayer.frame = CGRectMake(0, lc.center.y, size.width, size.height - lc.center.y)
case .Top:
frontView.frame.origin.y = min(cc.center.y, lc.center.y) - contentLength
shadowMaskLayer.frame = CGRectMake(0, 0, size.width, lc.center.y)
}
shadowMaskLayer.dragPoint = shadowMaskLayer.convertPoint(cc.center, fromLayer: container.layer)
if transform != nil{
transform!(progress: progress, view: backView)
}else{
// transform backView
switch transformType{
case .Rotate:
let scale:CGFloat = min(1, 1 - 0.2 * progress)
let rotate = max(0, 0.15 * progress)
let rotateY:CGFloat = edge == .Left ? -1.0 : edge == .Right ? 1.0 : 0
let rotateX:CGFloat = edge == .Bottom ? -1.0 : edge == .Top ? 1.0 : 0
var t = CATransform3DMakeScale(scale, scale, 1)
t.m34 = 1.0 / -500;
t = CATransform3DRotate(t, rotate, rotateX, rotateY, 0.0)
backView.layer.transform = t
case .TranslateMid, .TranslatePull, .TranslatePush:
var x:CGFloat = 0, y:CGFloat = 0
container.backgroundColor = backView.backgroundColor
let minFunc = transformType == .TranslateMid ? avg : transformType == .TranslatePull ? max : min
let maxFunc = transformType == .TranslateMid ? avg : transformType == .TranslatePull ? min : max
switch edge{
case .Left:
x = minFunc(cc.center.x, lc.center.x)
case .Right:
x = maxFunc(cc.center.x, lc.center.x) - size.width
case .Bottom:
y = maxFunc(cc.center.y, lc.center.y) - size.height
case .Top:
y = minFunc(cc.center.y, lc.center.y)
}
backView.layer.transform = CATransform3DMakeTranslation(x, y, 0)
default:
backView.layer.transform = CATransform3DIdentity
}
}
overlayView.alpha = progress
updateShadow(progress)
transitionContext.updateInteractiveTransition(presenting ? progress : 1 - progress)
}
override func setup(){
super.setup()
// 1. get content length
frontView.layoutIfNeeded()
switch edge{
case .Left, .Right:
contentLength = frontView.bounds.width
case .Top, .Bottom:
contentLength = frontView.bounds.height
}
if let vc = frontViewController as? ElasticMenuTransitionDelegate,
let vcl = vc.contentLength{
contentLength = vcl
}
// 2. setup shadow and background view
shadowView.frame = container.bounds
if let frontViewBackgroundColor = frontViewBackgroundColor{
shadowMaskLayer.fillColor = frontViewBackgroundColor.CGColor
}else if let vc = frontViewController as? UINavigationController,
let rootVC = vc.childViewControllers.last{
shadowMaskLayer.fillColor = rootVC.view.backgroundColor?.CGColor
}else{
shadowMaskLayer.fillColor = frontView.backgroundColor?.CGColor
}
shadowMaskLayer.edge = edge.opposite()
shadowMaskLayer.radiusFactor = radiusFactor
container.addSubview(shadowView)
// 3. setup overlay view
overlayView.frame = container.bounds
overlayView.backgroundColor = overlayColor
overlayView.addGestureRecognizer(backgroundExitPanGestureRecognizer)
container.addSubview(overlayView)
// 4. setup front view
var rect = container.bounds
switch edge{
case .Right, .Left:
rect.size.width = contentLength
case .Bottom, .Top:
rect.size.height = contentLength
}
frontView.frame = rect
if navigation{
frontViewController.navigationController?.view.addGestureRecognizer(navigationExitPanGestureRecognizer)
}else{
frontView.addGestureRecognizer(foregroundExitPanGestureRecognizer)
}
frontView.layoutIfNeeded()
// 5. container color
switch transformType{
case .TranslateMid, .TranslatePull, .TranslatePush:
container.backgroundColor = backView.backgroundColor
default:
container.backgroundColor = containerColor
}
// 6. setup uikitdynamic
setupDynamics()
// 7. do a initial update (put everything into its place)
updateShape()
// if not doing an interactive transition, move the drag point to the final position
if !interactive{
let duration = self.transitionDuration(transitionContext)
lb.action = {
if self.animator != nil && self.animator.elapsedTime() >= duration {
self.cc.center = self.dragPoint
self.lc.center = self.dragPoint
self.updateShape()
self.clean(true)
}
}
dragPoint = self.startingPoint ?? container.center
dragPoint = finalPoint()
update()
}
}
func updateShadow(progress:CGFloat){
if showShadow{
shadowView.layer.shadowColor = shadowColor.CGColor
shadowView.layer.shadowRadius = shadowRadius
shadowView.layer.shadowOffset = CGSizeMake(0, 0)
shadowView.layer.shadowOpacity = Float(progress)
shadowView.layer.masksToBounds = false
}else{
shadowView.layer.shadowColor = nil
shadowView.layer.shadowRadius = 0
shadowView.layer.shadowOffset = CGSizeMake(0, 0)
shadowView.layer.shadowOpacity = 0
shadowView.layer.masksToBounds = true
}
}
func setupDynamics(){
animator = UIDynamicAnimator(referenceView: container)
let initialPoint = finalPoint(!presenting)
cc = DynamicItem(center: initialPoint)
lc = DynamicItem(center: initialPoint)
cb = CustomSnapBehavior(item: cc, point: dragPoint)
cb.damping = damping
cb.frequency = 2.5
lb = CustomSnapBehavior(item: lc, point: dragPoint)
lb.damping = min(1.0, damping * 1.5)
lb.frequency = 2.5
update()
cb.action = {
self.updateShape()
}
animator.addBehavior(cb)
animator.addBehavior(lb)
}
override func clean(finished:Bool){
animator.removeAllBehaviors()
animator = nil
frontView.layer.zPosition = 0
if navigation{
shadowView.removeFromSuperview()
overlayView.removeFromSuperview()
}
if presenting && finished{
pushedControllers.append(frontViewController)
}else if !presenting && finished{
pushedControllers.popLast()
}
super.clean(finished)
}
override func cancelInteractiveTransition(){
super.cancelInteractiveTransition()
let finalPoint = self.finalPoint(!self.presenting)
cb.point = finalPoint
lb.point = finalPoint
lb.action = {
if finalPoint.distance(self.cc.center) < 1 &&
finalPoint.distance(self.lc.center) < 1 &&
self.lastPoint.distance(self.cc.center) < 0.05{
self.cc.center = finalPoint
self.lc.center = finalPoint
self.updateShape()
self.clean(false)
}else{
self.updateShape()
}
self.lastPoint = self.cc.center
}
}
override func finishInteractiveTransition(){
super.finishInteractiveTransition()
let finalPoint = self.finalPoint()
cb.point = finalPoint
lb.point = finalPoint
lb.action = {
if finalPoint.distance(self.cc.center) < 1 &&
finalPoint.distance(self.lc.center) < 1 &&
self.lastPoint.distance(self.cc.center) < 0.05{
self.cc.center = finalPoint
self.lc.center = finalPoint
self.updateShape()
self.clean(true)
}else{
self.updateShape()
}
self.lastPoint = self.cc.center
}
}
override func endInteractiveTransition() -> Bool{
let finalPoint = self.finalPoint()
let initialPoint = self.finalPoint(!self.presenting)
let p = (useTranlation && interactive) ? translatedPoint() : dragPoint
if (p.distance(initialPoint) >= contentLength * panThreshold) &&
initialPoint.distance(finalPoint) > p.distance(finalPoint){
self.finishInteractiveTransition()
return true
} else {
self.cancelInteractiveTransition()
return false
}
}
override public func transitionDuration(transitionContext: UIViewControllerContextTransitioning?) -> NSTimeInterval {
return NSTimeInterval(abs(damping - 0.2) * 0.5 + 0.6)
}
}
| apache-2.0 | d82b5eff6b5c6c3e713792117ae64f9f | 32.28164 | 128 | 0.682502 | 4.386983 | false | false | false | false |
iOS-mamu/SS | P/Library/Eureka/Source/Core/Section.swift | 1 | 13900 | // Section.swift
// Eureka ( https://github.com/xmartlabs/Eureka )
//
// Copyright (c) 2016 Xmartlabs ( http://xmartlabs.com )
//
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
/// The delegate of the Eureka sections.
public protocol SectionDelegate: class {
func rowsHaveBeenAdded(_ rows: [BaseRow], atIndexes:IndexSet)
func rowsHaveBeenRemoved(_ rows: [BaseRow], atIndexes:IndexSet)
func rowsHaveBeenReplaced(oldRows:[BaseRow], newRows: [BaseRow], atIndexes: IndexSet)
}
// MARK: Section
extension Section : Equatable {}
public func ==(lhs: Section, rhs: Section) -> Bool{
return lhs === rhs
}
extension Section : Hidable, SectionDelegate {}
extension Section {
public func reload(_ rowAnimation: UITableViewRowAnimation = .none) {
guard let tableView = (form?.delegate as? FormViewController)?.tableView, let index = index else { return }
tableView.reloadSections(IndexSet(integer: index), with: rowAnimation)
}
}
extension Section {
internal class KVOWrapper : NSObject{
dynamic var _rows = NSMutableArray()
var rows : NSMutableArray {
get {
return mutableArrayValue(forKey: "_rows")
}
}
var _allRows = [BaseRow]()
weak var section: Section?
init(section: Section){
self.section = section
super.init()
addObserver(self, forKeyPath: "_rows", options: NSKeyValueObservingOptions.new.union(.old), context:nil)
}
deinit{
removeObserver(self, forKeyPath: "_rows")
}
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
let newRows = change![NSKeyValueChangeKey.newKey] as? [BaseRow] ?? []
let oldRows = change![NSKeyValueChangeKey.oldKey] as? [BaseRow] ?? []
guard let keyPathValue = keyPath, let changeType = change?[NSKeyValueChangeKey.kindKey] else{ return }
let delegateValue = section?.form?.delegate
guard keyPathValue == "_rows" else { return }
switch (changeType as AnyObject).uintValue {
case NSKeyValueChange.setting.rawValue:
section?.rowsHaveBeenAdded(newRows, atIndexes:IndexSet(integer: 0))
delegateValue?.rowsHaveBeenAdded(newRows, atIndexPaths:[IndexPath(index: 0)])
case NSKeyValueChange.insertion.rawValue:
let indexSet = change![NSKeyValueChangeKey.indexesKey] as! IndexSet
section?.rowsHaveBeenAdded(newRows, atIndexes: indexSet)
if let _index = section?.index {
delegateValue?.rowsHaveBeenAdded(newRows, atIndexPaths: indexSet.map { IndexPath(row: $0, section: _index ) } )
}
case NSKeyValueChange.removal.rawValue:
let indexSet = change![NSKeyValueChangeKey.indexesKey] as! IndexSet
section?.rowsHaveBeenRemoved(oldRows, atIndexes: indexSet)
if let _index = section?.index {
delegateValue?.rowsHaveBeenRemoved(oldRows, atIndexPaths: indexSet.map { IndexPath(row: $0, section: _index ) } )
}
case NSKeyValueChange.replacement.rawValue:
let indexSet = change![NSKeyValueChangeKey.indexesKey] as! IndexSet
section?.rowsHaveBeenReplaced(oldRows: oldRows, newRows: newRows, atIndexes: indexSet)
if let _index = section?.index {
delegateValue?.rowsHaveBeenReplaced(oldRows: oldRows, newRows: newRows, atIndexPaths: indexSet.map { IndexPath(row: $0, section: _index)})
}
default:
assertionFailure()
}
}
}
/**
* If this section contains a row (hidden or not) with the passed parameter as tag then that row will be returned.
* If not, it returns nil.
*/
public func rowByTag<Row: RowType>(_ tag: String) -> Row? {
guard let index = kvoWrapper._allRows.index(where: { $0.tag == tag }) else { return nil }
return kvoWrapper._allRows[index] as? Row
}
}
/// The class representing the sections in a Eureka form.
open class Section {
/// The tag is used to uniquely identify a Section. Must be unique among sections and rows.
open var tag: String?
/// The form that contains this section
open fileprivate(set) weak var form: Form?
/// The header of this section.
open var header: HeaderFooterViewRepresentable? {
willSet {
headerView = nil
}
}
/// The footer of this section
open var footer: HeaderFooterViewRepresentable? {
willSet {
footerView = nil
}
}
/// Index of this section in the form it belongs to.
open var index: Int? { return form?.index(of: self) }
/// Condition that determines if the section should be hidden or not.
open var hidden : Condition? {
willSet { removeFromRowObservers() }
didSet { addToRowObservers() }
}
/// Returns if the section is currently hidden or not
open var isHidden : Bool { return hiddenCache }
public required init(){}
public required init(_ initializer: (Section) -> ()){
initializer(self)
}
public init(_ header: String, _ initializer: (Section) -> () = { _ in }){
self.header = HeaderFooterView(stringLiteral: header)
initializer(self)
}
public init(header: String, footer: String, _ initializer: (Section) -> () = { _ in }){
self.header = HeaderFooterView(stringLiteral: header)
self.footer = HeaderFooterView(stringLiteral: footer)
initializer(self)
}
public init(footer: String, _ initializer: (Section) -> () = { _ in }){
self.footer = HeaderFooterView(stringLiteral: footer)
initializer(self)
}
//MARK: SectionDelegate
/**
* Delegate method called by the framework when one or more rows have been added to the section.
*/
open func rowsHaveBeenAdded(_ rows: [BaseRow], atIndexes:IndexSet) {}
/**
* Delegate method called by the framework when one or more rows have been removed from the section.
*/
open func rowsHaveBeenRemoved(_ rows: [BaseRow], atIndexes:IndexSet) {}
/**
* Delegate method called by the framework when one or more rows have been replaced in the section.
*/
open func rowsHaveBeenReplaced(oldRows:[BaseRow], newRows: [BaseRow], atIndexes: IndexSet) {}
//MARK: Private
lazy var kvoWrapper: KVOWrapper = { [unowned self] in return KVOWrapper(section: self) }()
var headerView: UIView?
var footerView: UIView?
var hiddenCache = false
}
extension Section : MutableCollection {
/// Returns the position immediately after the given index.
///
/// - Parameter i: A valid index of the collection. `i` must be less than
/// `endIndex`.
/// - Returns: The index value immediately after `i`.
public func index(after i: Int) -> Int {
return i+1;
}
//MARK: MutableCollectionType
public var startIndex: Int { return 0 }
public var endIndex: Int { return kvoWrapper.rows.count }
public subscript (position: Int) -> BaseRow {
get {
if position >= kvoWrapper.rows.count{
assertionFailure("Section: Index out of bounds")
}
return kvoWrapper.rows[position] as! BaseRow
}
set { kvoWrapper.rows[position] = newValue }
}
}
extension Section : RangeReplaceableCollection {
// MARK: RangeReplaceableCollectionType
public func append(_ formRow: BaseRow){
kvoWrapper.rows.insert(formRow, at: kvoWrapper.rows.count)
kvoWrapper._allRows.append(formRow)
formRow.wasAddedToFormInSection(self)
}
public func append<S : Sequence>(contentsOf newElements: S) where S.Iterator.Element == BaseRow {
kvoWrapper.rows.addObjects(from: newElements.map { $0 })
kvoWrapper._allRows.append(contentsOf: newElements)
for row in newElements{
row.wasAddedToFormInSection(self)
}
}
public func reserveCapacity(_ n: Int){}
public func replaceSubrange<C : Collection>(_ subRange: Range<Int>, with newElements: C) where C.Iterator.Element == BaseRow {
for i in subRange.lowerBound..<subRange.upperBound {
if let row = kvoWrapper.rows.object(at: i) as? BaseRow {
row.willBeRemovedFromForm()
kvoWrapper._allRows.remove(at: kvoWrapper._allRows.index(of: row)!)
}
}
kvoWrapper.rows.replaceObjects(in: NSMakeRange(subRange.lowerBound, subRange.upperBound - subRange.lowerBound), withObjectsFrom: newElements.map { $0 })
kvoWrapper._allRows.insert(contentsOf: newElements, at: indexForInsertionAtIndex(subRange.lowerBound))
for row in newElements{
row.wasAddedToFormInSection(self)
}
}
public func removeAll(keepingCapacity keepCapacity: Bool = false) {
// not doing anything with capacity
for row in kvoWrapper._allRows{
row.willBeRemovedFromForm()
}
kvoWrapper.rows.removeAllObjects()
kvoWrapper._allRows.removeAll()
}
fileprivate func indexForInsertionAtIndex(_ index: Int) -> Int {
guard index != 0 else { return 0 }
let row = kvoWrapper.rows[index-1]
if let i = kvoWrapper._allRows.index(of: row as! BaseRow){
return i + 1
}
return kvoWrapper._allRows.count
}
}
extension Section /* Condition */{
//MARK: Hidden/Disable Engine
/**
Function that evaluates if the section should be hidden and updates it accordingly.
*/
public func evaluateHidden(){
if let h = hidden, let f = form {
switch h {
case .function(_ , let callback):
hiddenCache = callback(f)
case .predicate(let predicate):
hiddenCache = predicate.evaluate(with: self, substitutionVariables: f.dictionaryValuesToEvaluatePredicate())
}
if hiddenCache {
form?.hideSection(self)
}
else{
form?.showSection(self)
}
}
}
/**
Internal function called when this section was added to a form.
*/
func wasAddedToForm(_ form: Form) {
self.form = form
addToRowObservers()
evaluateHidden()
for row in kvoWrapper._allRows {
row.wasAddedToFormInSection(self)
}
}
/**
Internal function called to add this section to the observers of certain rows. Called when the hidden variable is set and depends on other rows.
*/
func addToRowObservers(){
guard let h = hidden else { return }
switch h {
case .function(let tags, _):
form?.addRowObservers(self, rowTags: tags, type: .hidden)
case .predicate(let predicate):
form?.addRowObservers(self, rowTags: predicate.predicateVars, type: .hidden)
}
}
/**
Internal function called when this section was removed from a form.
*/
func willBeRemovedFromForm(){
for row in kvoWrapper._allRows {
row.willBeRemovedFromForm()
}
removeFromRowObservers()
self.form = nil
}
/**
Internal function called to remove this section from the observers of certain rows. Called when the hidden variable is changed.
*/
func removeFromRowObservers(){
guard let h = hidden else { return }
switch h {
case .function(let tags, _):
form?.removeRowObservers(self, rows: tags, type: .hidden)
case .predicate(let predicate):
form?.removeRowObservers(self, rows: predicate.predicateVars, type: .hidden)
}
}
func hideRow(_ row: BaseRow){
row.baseCell.cellResignFirstResponder()
(row as? BaseInlineRowType)?.collapseInlineRow()
kvoWrapper.rows.remove(row)
}
func showRow(_ row: BaseRow){
guard !kvoWrapper.rows.contains(row) else { return }
guard var index = kvoWrapper._allRows.index(of: row) else { return }
var formIndex = NSNotFound
while (formIndex == NSNotFound && index > 0){
index = index - 1
let previous = kvoWrapper._allRows[index]
formIndex = kvoWrapper.rows.index(of: previous)
}
kvoWrapper.rows.insert(row, at: formIndex == NSNotFound ? 0 : formIndex + 1)
}
}
| mit | 9c51ef9cc75aecf438b1c6cb28fcc89a | 35.772487 | 160 | 0.625683 | 4.882332 | false | false | false | false |
adrfer/swift | test/SILGen/objc_thunks.swift | 2 | 20390 | // RUN: %target-swift-frontend -sdk %S/Inputs -I %S/Inputs -enable-source-import %s -emit-silgen -emit-verbose-sil | FileCheck %s
// REQUIRES: objc_interop
import gizmo
import ansible
class Hoozit : Gizmo {
func typical(x: Int, y: Gizmo) -> Gizmo { return y }
// CHECK-LABEL: sil hidden [thunk] @_TToFC11objc_thunks6Hoozit7typical{{.*}} : $@convention(objc_method) (Int, Gizmo, Hoozit) -> @autoreleased Gizmo {
// CHECK: bb0([[X:%.*]] : $Int, [[Y:%.*]] : $Gizmo, [[THIS:%.*]] : $Hoozit):
// CHECK-NEXT: retain [[Y]]
// CHECK-NEXT: retain [[THIS]]
// CHECK-NEXT: // function_ref
// CHECK-NEXT: [[NATIVE:%.*]] = function_ref @_TFC11objc_thunks6Hoozit7typical{{.*}} : $@convention(method) (Int, @owned Gizmo, @guaranteed Hoozit) -> @owned Gizmo
// CHECK-NEXT: [[RES:%.*]] = apply [[NATIVE]]([[X]], [[Y]], [[THIS]]) {{.*}} line:[[@LINE-7]]:8:auto_gen
// CHECK-NEXT: strong_release [[THIS]] : $Hoozit // {{.*}}
// CHECK-NEXT: return [[RES]] : $Gizmo // {{.*}} line:[[@LINE-9]]:8:auto_gen
// CHECK-NEXT: }
// NS_CONSUMES_SELF by inheritance
override func fork() { }
// CHECK-LABEL: sil hidden [thunk] @_TToFC11objc_thunks6Hoozit4fork{{.*}} : $@convention(objc_method) (@owned Hoozit) -> () {
// CHECK: bb0([[THIS:%.*]] : $Hoozit):
// CHECK-NEXT: // function_ref
// CHECK-NEXT: [[NATIVE:%.*]] = function_ref @_TFC11objc_thunks6Hoozit4fork{{.*}} : $@convention(method) (@guaranteed Hoozit) -> ()
// CHECK-NEXT: apply [[NATIVE]]([[THIS]])
// CHECK-NEXT: strong_release [[THIS]]
// CHECK-NEXT: return
// CHECK-NEXT: }
// NS_CONSUMED 'gizmo' argument by inheritance
override class func consume(gizmo: Gizmo?) { }
// CHECK-LABEL: sil hidden [thunk] @_TToZFC11objc_thunks6Hoozit7consume{{.*}} : $@convention(objc_method) (@owned Optional<Gizmo>, @objc_metatype Hoozit.Type) -> () {
// CHECK: bb0([[GIZMO:%.*]] : $Optional<Gizmo>, [[THIS:%.*]] : $@objc_metatype Hoozit.Type):
// CHECK-NEXT: [[THICK_THIS:%[0-9]+]] = objc_to_thick_metatype [[THIS]] : $@objc_metatype Hoozit.Type to $@thick Hoozit.Type
// CHECK: [[NATIVE:%.*]] = function_ref @_TZFC11objc_thunks6Hoozit7consume{{.*}} : $@convention(thin) (@owned Optional<Gizmo>, @thick Hoozit.Type) -> ()
// CHECK-NEXT: apply [[NATIVE]]([[GIZMO]], [[THICK_THIS]])
// CHECK-NEXT: return
// CHECK-NEXT: }
// NS_RETURNS_RETAINED by family (-copy)
func copyFoo() -> Gizmo { return self }
// CHECK-LABEL: sil hidden [thunk] @_TToFC11objc_thunks6Hoozit7copyFoo{{.*}} : $@convention(objc_method) (Hoozit) -> @owned Gizmo
// CHECK: bb0([[THIS:%.*]] : $Hoozit):
// CHECK-NEXT: retain [[THIS]]
// CHECK-NEXT: // function_ref
// CHECK-NEXT: [[NATIVE:%.*]] = function_ref @_TFC11objc_thunks6Hoozit7copyFoo{{.*}} : $@convention(method) (@guaranteed Hoozit) -> @owned Gizmo
// CHECK-NEXT: [[RES:%.*]] = apply [[NATIVE]]([[THIS]])
// CHECK: release [[THIS]]
// CHECK-NEXT: return [[RES]]
// CHECK-NEXT: }
var typicalProperty: Gizmo
// -- getter
// CHECK-LABEL: sil hidden [transparent] [thunk] @_TToFC11objc_thunks6Hoozitg15typicalPropertyCSo5Gizmo : $@convention(objc_method) (Hoozit) -> @autoreleased Gizmo {
// CHECK: bb0(%0 : $Hoozit):
// CHECK-NEXT: strong_retain %0
// CHECK-NEXT: // function_ref objc_thunks.Hoozit.typicalProperty.getter
// CHECK-NEXT: [[GETIMPL:%.*]] = function_ref @_TFC11objc_thunks6Hoozitg15typicalPropertyCSo5Gizmo
// CHECK-NEXT: [[RES:%.*]] = apply [[GETIMPL]](%0)
// CHECK-NEXT: strong_release %0
// CHECK-NEXT: return [[RES]] : $Gizmo
// CHECK-NEXT: }
// CHECK-LABEL: sil hidden [transparent] @_TFC11objc_thunks6Hoozitg15typicalPropertyCSo5Gizmo : $@convention(method) (@guaranteed Hoozit) -> @owned Gizmo
// CHECK: bb0(%0 : $Hoozit):
// CHECK-NEXT: debug_value %0
// CHECK-NEXT: [[ADDR:%.*]] = ref_element_addr %0 : {{.*}}, #Hoozit.typicalProperty {{.*}}
// CHECK-NEXT: [[RES:%.*]] = load [[ADDR]] {{.*}}
// CHECK-NEXT: strong_retain [[RES]] : $Gizmo
// CHECK-NEXT: return [[RES]]
// -- setter
// CHECK-LABEL: sil hidden [transparent] [thunk] @_TToFC11objc_thunks6Hoozits15typicalPropertyCSo5Gizmo : $@convention(objc_method) (Gizmo, Hoozit) -> () {
// CHECK: bb0([[VALUE:%.*]] : $Gizmo, [[THIS:%.*]] : $Hoozit):
// CHECK-NEXT: retain [[VALUE]] : $Gizmo
// CHECK-NEXT: retain [[THIS]] : $Hoozit
// CHECK-NEXT: // function_ref objc_thunks.Hoozit.typicalProperty.setter
// CHECK-NEXT: [[FR:%.*]] = function_ref @_TFC11objc_thunks6Hoozits15typicalPropertyCSo5Gizmo
// CHECK-NEXT: [[RES:%.*]] = apply [[FR]](%0, %1)
// CHECK_NEXT: return [[RES]] line:[[@LINE-19]]:7:auto_gen
// CHECK-LABEL: sil hidden [transparent] @_TFC11objc_thunks6Hoozits15typicalPropertyCSo5Gizmo
// CHECK: bb0(%0 : $Gizmo, %1 : $Hoozit):
// CHECK: [[ADDR:%.*]] = ref_element_addr %1 : {{.*}}, #Hoozit.typicalProperty
// CHECK-NEXT: assign %0 to [[ADDR]] : $*Gizmo
// NS_RETURNS_RETAINED getter by family (-copy)
var copyProperty: Gizmo
// -- getter
// CHECK-LABEL: sil hidden [transparent] [thunk] @_TToFC11objc_thunks6Hoozitg12copyPropertyCSo5Gizmo : $@convention(objc_method) (Hoozit) -> @owned Gizmo {
// CHECK: bb0(%0 : $Hoozit):
// CHECK-NEXT: strong_retain %0
// CHECK-NEXT: // function_ref objc_thunks.Hoozit.copyProperty.getter
// CHECK-NEXT: [[FR:%.*]] = function_ref @_TFC11objc_thunks6Hoozitg12copyPropertyCSo5Gizmo
// CHECK-NEXT: [[RES:%.*]] = apply [[FR]](%0)
// CHECK-NEXT: strong_release %0
// CHECK-NEXT: return [[RES]]
// CHECK-NEXT: }
// CHECK-LABEL: sil hidden [transparent] @_TFC11objc_thunks6Hoozitg12copyPropertyCSo5Gizmo
// CHECK: bb0(%0 : $Hoozit):
// CHECK: [[ADDR:%.*]] = ref_element_addr %0 : {{.*}}, #Hoozit.copyProperty
// CHECK-NEXT: [[RES:%.*]] = load [[ADDR]]
// CHECK-NEXT: retain [[RES]]
// CHECK-NEXT: return [[RES]]
// -- setter is normal
// CHECK-LABEL: sil hidden [transparent] [thunk] @_TToFC11objc_thunks6Hoozits12copyPropertyCSo5Gizmo : $@convention(objc_method) (Gizmo, Hoozit) -> () {
// CHECK: bb0([[VALUE:%.*]] : $Gizmo, [[THIS:%.*]] : $Hoozit):
// CHECK-NEXT: retain [[VALUE]]
// CHECK-NEXT: retain [[THIS]]
// CHECK-NEXT: // function_ref objc_thunks.Hoozit.copyProperty.setter
// CHECK-NEXT: [[FR:%.*]] = function_ref @_TFC11objc_thunks6Hoozits12copyPropertyCSo5Gizmo
// CHECK-NEXT: [[RES:%.*]] = apply [[FR]](%0, %1)
// CHECK-NEXT: strong_release [[THIS]]
// CHECK-NEXT: return [[RES]]
// CHECK-LABEL: sil hidden [transparent] @_TFC11objc_thunks6Hoozits12copyPropertyCSo5Gizmo
// CHECK: bb0(%0 : $Gizmo, %1 : $Hoozit):
// CHECK: [[ADDR:%.*]] = ref_element_addr %1 : {{.*}}, #Hoozit.copyProperty
// CHECK-NEXT: assign %0 to [[ADDR]]
var roProperty: Gizmo { return self }
// -- getter
// CHECK-LABEL: sil hidden [thunk] @_TToFC11objc_thunks6Hoozitg10roPropertyCSo5Gizmo : $@convention(objc_method) (Hoozit) -> @autoreleased Gizmo {
// CHECK: bb0([[THIS:%.*]] : $Hoozit):
// CHECK-NEXT: retain [[THIS]]
// CHECK-NEXT: // function_ref
// CHECK-NEXT: [[NATIVE:%.*]] = function_ref @_TFC11objc_thunks6Hoozitg10roPropertyCSo5Gizmo : $@convention(method) (@guaranteed Hoozit) -> @owned Gizmo
// CHECK-NEXT: [[RES:%.*]] = apply [[NATIVE]]([[THIS]])
// CHECK-NEXT: release [[THIS]] : $Hoozit
// CHECK-NEXT: return [[RES]] : $Gizmo
// CHECK-NEXT: }
// -- no setter
// CHECK-NOT: sil hidden [thunk] @_TToFC11objc_thunks6Hoozits10roPropertyCSo5Gizmo
var rwProperty: Gizmo {
get {
return self
}
set {}
}
// -- getter
// CHECK-LABEL: sil hidden [thunk] @_TToFC11objc_thunks6Hoozitg10rwPropertyCSo5Gizmo : $@convention(objc_method) (Hoozit) -> @autoreleased Gizmo
// -- setter
// CHECK-LABEL: sil hidden [thunk] @_TToFC11objc_thunks6Hoozits10rwPropertyCSo5Gizmo : $@convention(objc_method) (Gizmo, Hoozit) -> () {
// CHECK: bb0([[VALUE:%.*]] : $Gizmo, [[THIS:%.*]] : $Hoozit):
// CHECK-NEXT: retain [[VALUE]]
// CHECK-NEXT: retain [[THIS]]
// CHECK-NEXT: // function_ref
// CHECK-NEXT: [[NATIVE:%.*]] = function_ref @_TFC11objc_thunks6Hoozits10rwPropertyCSo5Gizmo : $@convention(method) (@owned Gizmo, @guaranteed Hoozit) -> ()
// CHECK-NEXT: apply [[NATIVE]]([[VALUE]], [[THIS]])
// CHECK-NEXT: release [[THIS]]
// CHECK-NEXT: return
// CHECK-NEXT: }
var copyRWProperty: Gizmo {
get {
return self
}
set {}
}
// -- getter
// CHECK-LABEL: sil hidden [thunk] @_TToFC11objc_thunks6Hoozitg14copyRWPropertyCSo5Gizmo : $@convention(objc_method) (Hoozit) -> @owned Gizmo {
// CHECK: bb0([[THIS:%.*]] : $Hoozit):
// CHECK-NEXT: retain [[THIS]]
// CHECK-NEXT: // function_ref
// CHECK-NEXT: [[NATIVE:%.*]] = function_ref @_TFC11objc_thunks6Hoozitg14copyRWPropertyCSo5Gizmo : $@convention(method) (@guaranteed Hoozit) -> @owned Gizmo
// CHECK-NEXT: [[RES:%.*]] = apply [[NATIVE]]([[THIS]])
// CHECK-NEXT: release [[THIS]]
// CHECK-NOT: return
// CHECK-NEXT: return [[RES]]
// CHECK-NEXT: }
// -- setter is normal
// CHECK-LABEL: sil hidden [thunk] @_TToFC11objc_thunks6Hoozits14copyRWPropertyCSo5Gizmo : $@convention(objc_method) (Gizmo, Hoozit) -> () {
// CHECK: bb0([[VALUE:%.*]] : $Gizmo, [[THIS:%.*]] : $Hoozit):
// CHECK-NEXT: retain [[VALUE]]
// CHECK-NEXT: retain [[THIS]]
// CHECK-NEXT: // function_ref
// CHECK-NEXT: [[NATIVE:%.*]] = function_ref @_TFC11objc_thunks6Hoozits14copyRWPropertyCSo5Gizmo : $@convention(method) (@owned Gizmo, @guaranteed Hoozit) -> ()
// CHECK-NEXT: apply [[NATIVE]]([[VALUE]], [[THIS]])
// CHECK-NEXT: release [[THIS]]
// CHECK-NEXT: return
// CHECK-NEXT: }
// Don't export generics to ObjC yet
func generic<T>(x: T) {}
// CHECK-NOT: sil hidden [thunk] @_TToFC11objc_thunks6Hoozit7generic{{.*}}
// Constructor.
// CHECK-LABEL: sil hidden @_TFC11objc_thunks6Hoozitc{{.*}} : $@convention(method) (Int, @owned Hoozit) -> @owned Hoozit {
// CHECK: [[SELF_BOX:%[0-9]+]] = alloc_box $Hoozit
// CHECK: [[PB:%.*]] = project_box [[SELF_BOX]]
// CHECK: [[SELFMUI:%[0-9]+]] = mark_uninitialized [derivedself] [[PB]]
// CHECK: [[GIZMO:%[0-9]+]] = upcast [[SELF:%[0-9]+]] : $Hoozit to $Gizmo
// CHECK: [[SUPERMETHOD:%[0-9]+]] = super_method [volatile] [[SELF]] : $Hoozit, #Gizmo.init!initializer.1.foreign : Gizmo.Type -> (bellsOn: Int) -> Gizmo! , $@convention(objc_method) (Int, @owned Gizmo) -> @owned ImplicitlyUnwrappedOptional<Gizmo>
// CHECK-NEXT: [[SELF_REPLACED:%[0-9]+]] = apply [[SUPERMETHOD]](%0, [[X:%[0-9]+]]) : $@convention(objc_method) (Int, @owned Gizmo) -> @owned ImplicitlyUnwrappedOptional<Gizmo>
// CHECK-NOT: unconditional_checked_cast downcast [[SELF_REPLACED]] : $Gizmo to $Hoozit
// CHECK: function_ref @_TFs36_getImplicitlyUnwrappedOptionalValue
// CHECK: unchecked_ref_cast
// CHECK: return
override init(bellsOn x : Int) {
super.init(bellsOn: x)
other()
}
// Subscript
subscript (i: Int) -> Hoozit {
// Getter
// CHECK-LABEL: sil hidden [thunk] @_TToFC11objc_thunks6Hoozitg9subscript{{.*}} : $@convention(objc_method) (Int, Hoozit) -> @autoreleased Hoozit
// CHECK: bb0([[I:%[0-9]+]] : $Int, [[SELF:%[0-9]+]] : $Hoozit):
// CHECK-NEXT: strong_retain [[SELF]] : $Hoozit
// CHECK: [[NATIVE:%[0-9]+]] = function_ref @_TFC11objc_thunks6Hoozitg9subscript{{.*}} : $@convention(method) (Int, @guaranteed Hoozit) -> @owned Hoozit
// CHECK-NEXT: [[RESULT:%[0-9]+]] = apply [[NATIVE]]([[I]], [[SELF]]) : $@convention(method) (Int, @guaranteed Hoozit) -> @owned Hoozit
// CHECK-NEXT: strong_release [[SELF]]
// CHECK-NEXT: return [[RESULT]] : $Hoozit
get {
return self
}
// Setter
// CHECK-LABEL: sil hidden [thunk] @_TToFC11objc_thunks6Hoozits9subscript{{.*}} : $@convention(objc_method) (Hoozit, Int, Hoozit) -> ()
// CHECK: bb0([[SELF:%[0-9]+]] : $Hoozit, [[I:%[0-9]+]] : $Int, [[VALUE:%[0-9]+]] : $Hoozit):
// CHECK-NEXT: strong_retain [[SELF]] : $Hoozit
// CHECK_NEXT: strong_retain [[VALUE]] : $Hoozit
// CHECK: [[NATIVE:%[0-9]+]] = function_ref @_TFC11objc_thunks6Hoozits9subscript{{.*}} : $@convention(method) (@owned Hoozit, Int, @guaranteed Hoozit) -> ()
// CHECK-NEXT: [[RESULT:%[0-9]+]] = apply [[NATIVE]]([[SELF]], [[I]], [[VALUE]]) : $@convention(method) (@owned Hoozit, Int, @guaranteed Hoozit) -> ()
// CHECK-NEXT: strong_release [[VALUE]]
// CHECK-NEXT: return [[RESULT]] : $()
set {}
}
}
class Wotsit<T> : Gizmo {
// CHECK-LABEL: sil hidden [thunk] @_TToFC11objc_thunks6Wotsit5plain{{.*}} : $@convention(objc_method) <T> (Wotsit<T>) -> () {
// CHECK: bb0([[SELF:%.*]] : $Wotsit<T>):
// CHECK-NEXT: strong_retain [[SELF]] : $Wotsit<T>
// CHECK-NEXT: // function_ref
// CHECK-NEXT: [[NATIVE:%.*]] = function_ref @_TFC11objc_thunks6Wotsit5plain{{.*}} : $@convention(method) <τ_0_0> (@guaranteed Wotsit<τ_0_0>) -> ()
// CHECK-NEXT: [[RESULT:%.*]] = apply [[NATIVE]]<T>([[SELF]]) : $@convention(method) <τ_0_0> (@guaranteed Wotsit<τ_0_0>) -> ()
// CHECK-NEXT: strong_release [[SELF]] : $Wotsit<T>
// CHECK-NEXT: return [[RESULT]] : $()
// CHECK-NEXT: }
func plain() { }
func generic<U>(x: U) {}
var property : T
init(t: T) {
self.property = t
super.init()
}
// CHECK-LABEL: sil hidden [thunk] @_TToFC11objc_thunks6Wotsitg11descriptionSS : $@convention(objc_method) <T> (Wotsit<T>) -> @autoreleased NSString {
// CHECK: bb0([[SELF:%.*]] : $Wotsit<T>):
// CHECK-NEXT: strong_retain [[SELF]] : $Wotsit<T>
// CHECK-NEXT: // function_ref
// CHECK-NEXT: [[NATIVE:%.*]] = function_ref @_TFC11objc_thunks6Wotsitg11descriptionSS : $@convention(method) <τ_0_0> (@guaranteed Wotsit<τ_0_0>) -> @owned String
// CHECK-NEXT: [[RESULT:%.*]] = apply [[NATIVE:%.*]]<T>([[SELF]]) : $@convention(method) <τ_0_0> (@guaranteed Wotsit<τ_0_0>) -> @owned String
// CHECK-NEXT: strong_release [[SELF]] : $Wotsit<T>
// CHECK-NEXT: // function_ref
// CHECK-NEXT: [[BRIDGE:%.*]] = function_ref @swift_StringToNSString : $@convention(thin) (@owned String) -> @owned NSString
// CHECK-NEXT: [[NSRESULT:%.*]] = apply [[BRIDGE]]([[RESULT]]) : $@convention(thin) (@owned String) -> @owned NSString
// CHECK-NEXT: return [[NSRESULT]] : $NSString
// CHECK-NEXT: }
override var description : String {
return "Hello, world."
}
// Ivar destroyer
// CHECK: sil hidden @_TToF{{.*}}WotsitE
}
// CHECK-NOT: sil hidden [thunk] @_TToF{{.*}}Wotsit{{.*}}
// Extension initializers, properties and methods need thunks too.
extension Hoozit {
// CHECK-LABEL: sil hidden [thunk] @_TToFC11objc_thunks6Hoozitc{{.*}} : $@convention(objc_method) (Int, @owned Hoozit) -> @owned Hoozit
dynamic convenience init(int i: Int) { self.init(bellsOn: i) }
// CHECK-LABEL: sil hidden @_TFC11objc_thunks6Hoozitc{{.*}} : $@convention(method) (Double, @owned Hoozit) -> @owned Hoozit
convenience init(double d: Double) {
// CHECK: [[SELF_BOX:%[0-9]+]] = alloc_box $Hoozit
// CHECK: [[PB:%.*]] = project_box [[SELF_BOX]]
// CHECK: [[SELFMUI:%[0-9]+]] = mark_uninitialized [delegatingself] [[PB]]
// CHECK: [[X_BOX:%[0-9]+]] = alloc_box $X
var x = X()
// CHECK: [[CTOR:%[0-9]+]] = class_method [volatile] [[SELF:%[0-9]+]] : $Hoozit, #Hoozit.init!initializer.1.foreign : Hoozit.Type -> (int: Int) -> Hoozit , $@convention(objc_method) (Int, @owned Hoozit) -> @owned Hoozit
// CHECK: [[NEW_SELF:%[0-9]+]] = apply [[CTOR]]
// CHECK: store [[NEW_SELF]] to [[SELFMUI]] : $*Hoozit
// CHECK: [[NONNULL:%[0-9]+]] = is_nonnull [[NEW_SELF]] : $Hoozit
// CHECK-NEXT: cond_br [[NONNULL]], [[NONNULL_BB:bb[0-9]+]], [[NULL_BB:bb[0-9]+]]
// CHECK: [[NULL_BB]]:
// CHECK-NEXT: strong_release [[X_BOX]] : $@box X
// CHECK-NEXT: br [[EPILOG_BB:bb[0-9]+]]
// CHECK: [[NONNULL_BB]]:
// CHECK: [[OTHER_REF:%[0-9]+]] = function_ref @_TF11objc_thunks5otherFT_T_ : $@convention(thin) () -> ()
// CHECK-NEXT: apply [[OTHER_REF]]() : $@convention(thin) () -> ()
// CHECK-NEXT: strong_release [[X_BOX]] : $@box X
// CHECK-NEXT: br [[EPILOG_BB]]
// CHECK: [[EPILOG_BB]]:
// CHECK-NOT: super_method
// CHECK: return
self.init(int:Int(d))
other()
}
func foof() {}
// CHECK-LABEL: sil hidden [thunk] @_TToFC11objc_thunks6Hoozit4foof{{.*}} : $@convention(objc_method) (Hoozit) -> () {
var extensionProperty: Int { return 0 }
// CHECK-LABEL: sil hidden @_TFC11objc_thunks6Hoozitg17extensionPropertySi : $@convention(method) (@guaranteed Hoozit) -> Int
}
// Calling objc methods of subclass should go through native entry points
func useHoozit(h: Hoozit) {
// sil @_TF11objc_thunks9useHoozitFT1hC11objc_thunks6Hoozit_T_
// In the class decl, gets dynamically dispatched
h.fork()
// CHECK: class_method {{%.*}} : {{.*}}, #Hoozit.fork!1 :
// In an extension, 'dynamic' was inferred.
h.foof()
// CHECK: class_method [volatile] {{%.*}} : {{.*}}, #Hoozit.foof!1.foreign
}
func useWotsit(w: Wotsit<String>) {
// sil @_TF11objc_thunks9useWotsitFT1wGCSo6WotsitSS__T_
w.plain()
// CHECK: class_method {{%.*}} : {{.*}}, #Wotsit.plain!1 :
w.generic(2)
// CHECK: class_method {{%.*}} : {{.*}}, #Wotsit.generic!1 :
// Inherited methods only have objc entry points
w.clone()
// CHECK: class_method [volatile] {{%.*}} : {{.*}}, #Gizmo.clone!1.foreign
}
func other() { }
class X { }
// CHECK-LABEL: sil hidden @_TF11objc_thunks8property
func property(g: Gizmo) -> Int {
// CHECK: class_method [volatile] %0 : $Gizmo, #Gizmo.count!getter.1.foreign
return g.count
}
// CHECK-LABEL: sil hidden @_TF11objc_thunks13blockProperty
func blockProperty(g: Gizmo) {
// CHECK: class_method [volatile] %0 : $Gizmo, #Gizmo.block!setter.1.foreign
g.block = { }
// CHECK: class_method [volatile] %0 : $Gizmo, #Gizmo.block!getter.1.foreign
g.block()
}
class DesignatedStubs : Gizmo {
var i: Int
override init() { i = 5 }
// CHECK-LABEL: sil hidden @_TFC11objc_thunks15DesignatedStubsc{{.*}}
// CHECK: function_ref @_TFs26_unimplemented_initializer
// CHECK: string_literal utf8 "objc_thunks.DesignatedStubs"
// CHECK: string_literal utf8 "init(bellsOn:)"
// CHECK: string_literal utf8 "{{.*}}objc_thunks.swift"
// CHECK: return
// CHECK-NOT: sil hidden @_TFCSo15DesignatedStubsc{{.*}}
}
class DesignatedOverrides : Gizmo {
var i: Int = 5
// CHECK-LABEL: sil hidden @_TFC11objc_thunks19DesignatedOverridesc{{.*}}
// CHECK-NOT: return
// CHECK: function_ref @_TFSiC{{.*}}
// CHECK: super_method [volatile] [[SELF:%[0-9]+]] : $DesignatedOverrides, #Gizmo.init!initializer.1.foreign : Gizmo.Type -> () -> Gizmo! , $@convention(objc_method) (@owned Gizmo) -> @owned ImplicitlyUnwrappedOptional<Gizmo>
// CHECK: return
// CHECK-LABEL: sil hidden @_TFC11objc_thunks19DesignatedOverridesc{{.*}}
// CHECK: function_ref @_TFSiC{{.*}}
// CHECK: super_method [volatile] [[SELF:%[0-9]+]] : $DesignatedOverrides, #Gizmo.init!initializer.1.foreign : Gizmo.Type -> (bellsOn: Int) -> Gizmo! , $@convention(objc_method) (Int, @owned Gizmo) -> @owned ImplicitlyUnwrappedOptional<Gizmo>
// CHECK: return
}
// Make sure we copy blocks passed in as IUOs - <rdar://problem/22471309>
func registerAnsible() {
// CHECK: function_ref @_TFF11objc_thunks15registerAnsibleFT_T_U_FGSQFT_T__T_
// CHECK: function_ref @_TTRXFo_oGSQFT_T___dT__XFdCb_dGSQbT_T___dT__
Ansible.anseAsync({ completion in completion() })
}
// FIXME: would be nice if we didn't need to re-abstract as much here.
// CHECK-LABEL: sil shared [transparent] [reabstraction_thunk] @_TTRXFo_oGSQFT_T___dT__XFdCb_dGSQbT_T___dT__ : $@convention(c) (@inout_aliasable @block_storage @callee_owned (@owned ImplicitlyUnwrappedOptional<() -> ()>) -> (), ImplicitlyUnwrappedOptional<@convention(block) () -> ()>) -> ()
// CHECK: [[HEAP_BLOCK_IUO:%.*]] = copy_block %1
// CHECK: select_enum [[HEAP_BLOCK_IUO]]
// CHECK: bb1:
// CHECK: [[HEAP_BLOCK:%.*]] = unchecked_enum_data [[HEAP_BLOCK_IUO]]
// CHECK: [[BLOCK_THUNK:%.*]] = function_ref @_TTRXFdCb__dT__XFo__dT__
// CHECK: [[BRIDGED_BLOCK:%.*]] = partial_apply [[BLOCK_THUNK]]([[HEAP_BLOCK]])
// CHECK: [[REABS_THUNK:%.*]] = function_ref @_TTRXFo__dT__XFo_iT__iT__
// CHECK: [[REABS_BLOCK:%.*]] = partial_apply [[REABS_THUNK]]([[BRIDGED_BLOCK]])
// CHECK: [[REABS_BLOCK_IUO:%.*]] = enum $ImplicitlyUnwrappedOptional<() -> ()>, {{.*}} [[REABS_BLOCK]]
| apache-2.0 | 78fd08b5d06bd4d6ab1a99d57925c859 | 48.231884 | 291 | 0.618978 | 3.341311 | false | false | false | false |
LYM-mg/MGOFO | MGOFO/Pods/SwiftySound/Classes/Sound.swift | 1 | 6200 | //
// Sound.swift
// SwiftySound
//
// Created by Adam Cichy on 21/02/17.
//
// Copyright (c) 2017 Adam Cichy
//
// 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 AVFoundation
/// Sound is a class that allows you to easily play sounds in Swift. It uses AVFoundation framework under the hood.
open class Sound {
/// Number of AVAudioPlayer instances created for every sound. SwiftySound creates 5 players for every sound to make sure that it will be able to play the same sound more than once. If your app doesn't need this functionality, you can reduce the number of players to 1 and reduce memory usage.
public static var playersPerSound: Int = 5 {
didSet {
Sound.stopAll()
Sound.sounds.removeAll()
}
}
private static var sounds = [URL: Sound]()
private static let defaultsKey = "com.moonlightapps.SwiftySound.enabled"
/// Globally enable or disable sound. This setting value is stored in UserDefaults and will be loaded on app launch.
public static var enabled: Bool = {
return !UserDefaults.standard.bool(forKey: defaultsKey)
}() { didSet {
let value = !enabled
UserDefaults.standard.set(value, forKey: defaultsKey)
if value {
stopAll()
}
}
}
private let players: [AVAudioPlayer]
private var counter = 0
// MARK: - Initialization
public init?(url: URL) {
var myPlayers: [AVAudioPlayer] = []
for _ in 0..<Sound.playersPerSound {
if let player = try? AVAudioPlayer(contentsOf: url) {
myPlayers.append(player)
}
}
if myPlayers.count == 0 {
return nil
}
players = myPlayers
Sound.sounds[url] = self
}
// MARK: - Main play method
/// Play the sound
///
/// - Parameter numberOfLoops: Number of loops. Specify a negative number for an infinite loop. Default value of 0 means that the sound will be played once.
/// - Returns: If the sound was played successfully the return value will be true. It will be false if sounds are disabled or if system could not play the sound.
@discardableResult public func play(numberOfLoops: Int = 0) -> Bool {
if !Sound.enabled {
return false
}
let player = players[counter]
counter = (counter + 1) % players.count
player.numberOfLoops = numberOfLoops
return player.play()
}
// MARK: - Stop playing
/// Stop playing the sound
public func stop() {
for player in players {
player.stop()
}
}
// MARK: - Convenience static methods
/// Play sound from a sound file
///
/// - Parameters:
/// - file: Sound file name
/// - fileExtension: Sound file extension
/// - numberOfLoops: Number of loops. Specify a negative number for an infinite loop. Default value of 0 means that the sound will be played once.
/// - Returns: If the sound was played successfully the return value will be true. It will be false if sounds are disabled or if system could not play the sound.
@discardableResult public static func play(file: String, fileExtension: String? = nil, numberOfLoops: Int = 0) -> Bool {
if let url = url(for: file, fileExtension: fileExtension) {
return play(url: url, numberOfLoops: numberOfLoops)
}
return false
}
/// Play a sound from URL
///
/// - Parameters:
/// - url: Sound file URL
/// - numberOfLoops: Number of loops. Specify a negative number for an infinite loop. Default value of 0 means that the sound will be played once.
/// - Returns: If the sound was played successfully the return value will be true. It will be false if sounds are disabled or if system could not play the sound.
@discardableResult public static func play(url: URL, numberOfLoops: Int = 0) -> Bool {
if !Sound.enabled {
return false
}
var sound = sounds[url]
if sound == nil {
sound = Sound(url: url)
}
return sound?.play(numberOfLoops: numberOfLoops) ?? false
}
/// Stop playing sound for given URL
///
/// - Parameter url: Sound file URL
public static func stop(for url: URL) {
let sound = sounds[url]
sound?.stop()
}
/// Stop playing sound for given sound file
///
/// - Parameters:
/// - file: Sound file name
/// - fileExtension: Sound file extension
public static func stop(file: String, fileExtension: String? = nil) {
if let url = url(for: file, fileExtension: fileExtension) {
let sound = sounds[url]
sound?.stop()
}
}
/// Stop playing all sounds
public static func stopAll() {
for sound in sounds.values {
sound.stop()
}
}
// MARK: - Private helper method
private static func url(for file: String, fileExtension: String? = nil) -> URL? {
return Bundle.main.url(forResource: file, withExtension: fileExtension)
}
}
| mit | 3023303d55261a90e0c7d1c9fb7d9fa8 | 36.349398 | 297 | 0.642097 | 4.545455 | false | false | false | false |
noppoMan/aws-sdk-swift | Sources/Soto/Services/SageMaker/SageMaker_Error.swift | 1 | 2369 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Soto for AWS open source project
//
// Copyright (c) 2017-2020 the Soto project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of Soto project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
// THIS FILE IS AUTOMATICALLY GENERATED by https://github.com/soto-project/soto/tree/main/CodeGenerator. DO NOT EDIT.
import SotoCore
/// Error enum for SageMaker
public struct SageMakerErrorType: AWSErrorType {
enum Code: String {
case conflictException = "ConflictException"
case resourceInUse = "ResourceInUse"
case resourceLimitExceeded = "ResourceLimitExceeded"
case resourceNotFound = "ResourceNotFound"
}
private let error: Code
public let context: AWSErrorContext?
/// initialize SageMaker
public init?(errorCode: String, context: AWSErrorContext) {
guard let error = Code(rawValue: errorCode) else { return nil }
self.error = error
self.context = context
}
internal init(_ error: Code) {
self.error = error
self.context = nil
}
/// return error code string
public var errorCode: String { self.error.rawValue }
/// There was a conflict when you attempted to modify an experiment, trial, or trial component.
public static var conflictException: Self { .init(.conflictException) }
/// Resource being accessed is in use.
public static var resourceInUse: Self { .init(.resourceInUse) }
/// You have exceeded an Amazon SageMaker resource limit. For example, you might have too many training jobs created.
public static var resourceLimitExceeded: Self { .init(.resourceLimitExceeded) }
/// Resource being access is not found.
public static var resourceNotFound: Self { .init(.resourceNotFound) }
}
extension SageMakerErrorType: Equatable {
public static func == (lhs: SageMakerErrorType, rhs: SageMakerErrorType) -> Bool {
lhs.error == rhs.error
}
}
extension SageMakerErrorType: CustomStringConvertible {
public var description: String {
return "\(self.error.rawValue): \(self.message ?? "")"
}
}
| apache-2.0 | 339bc1c0e0189fe635718f5536d3f56b | 34.893939 | 122 | 0.652174 | 4.904762 | false | false | false | false |
TeletronicsDotAe/FloatingActionButton | Pod/Classes/FloatingActionButton.swift | 1 | 13730 | //
// FloatingActionButton.swift
// Pods
//
// Adapted by Martin Jacon Rehder on 2016/04/17
//
// Original by
// Created by Takuma Yoshida on 2015/08/25.
//
//
import Foundation
import QuartzCore
// FloatingButton DataSource methods
@objc public protocol FloatingActionButtonDataSource {
func numberOfCells(floatingActionButton: FloatingActionButton) -> Int
func cellForIndex(index: Int) -> FloatingCell
}
@objc public protocol FloatingActionButtonDelegate {
// selected method
optional func floatingActionButton(floatingActionButton: FloatingActionButton, didSelectItemAtIndex index: Int)
}
public enum FloatingActionButtonAnimateStyle: Int {
case Up
case Right
case Left
case Down
}
@IBDesignable
public class FloatingActionButton: UIView {
private let internalRadiusRatio: CGFloat = 20.0 / 56.0
public var cellRadiusRatio: CGFloat = 0.38
public var animateStyle: FloatingActionButtonAnimateStyle = .Up {
didSet {
baseView.animateStyle = animateStyle
}
}
public var enableShadow = true {
didSet {
setNeedsDisplay()
}
}
public var delegate: FloatingActionButtonDelegate?
public var dataSource: FloatingActionButtonDataSource?
public var responsible = true
public var isOpening: Bool {
get {
return !baseView.openingCells.isEmpty
}
}
public private(set) var isClosed: Bool = true
@IBInspectable public var color: UIColor = UIColor(red: 82 / 255.0, green: 112 / 255.0, blue: 235 / 255.0, alpha: 1.0) {
didSet {
if self.childControlsColor == baseView.color {
self.childControlsColor = color
}
baseView.color = color
}
}
@IBInspectable public var childControlsColor: UIKit.UIColor = UIColor(red: 82 / 255.0, green: 112 / 255.0, blue: 235 / 255.0, alpha: 1.0)
@IBInspectable public var childControlsTintColor: UIKit.UIColor = UIKit.UIColor.clearColor();
@IBInspectable public var image: UIImage? {
didSet {
if image != nil {
plusLayer.contents = image!.CGImage
plusLayer.path = nil
}
}
}
@IBInspectable public var rotationDegrees: CGFloat = 45.0
private var plusLayer = CAShapeLayer()
private let circleLayer = CAShapeLayer()
private var touching = false
private var baseView = CircleBaseView()
private let actionButtonView = UIView()
public override init(frame: CGRect) {
super.init(frame: frame)
setup()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup()
}
private func insertCell(cell: FloatingCell) {
cell.color = self.childControlsColor;
cell.imageView.tintColor = self.childControlsTintColor;
cell.radius = self.frame.width * cellRadiusRatio
cell.center = self.center.minus(self.frame.origin)
cell.actionButton = self
insertSubview(cell, aboveSubview: baseView)
}
private func cellArray() -> [FloatingCell] {
var result: [FloatingCell] = []
if let source = dataSource {
for i in 0 ..< source.numberOfCells(self) {
result.append(source.cellForIndex(i))
}
}
return result
}
// open all cells
public func open() {
// rotate plus icon
CATransaction.setAnimationDuration(0.8)
self.plusLayer.transform = CATransform3DMakeRotation((CGFloat(M_PI) * rotationDegrees) / 180, 0, 0, 1)
let cells = cellArray()
for cell in cells {
insertCell(cell)
}
self.baseView.open(cells)
self.isClosed = false
}
// close all cells
public func close() {
// rotate plus icon
CATransaction.setAnimationDuration(0.8)
self.plusLayer.transform = CATransform3DMakeRotation(0, 0, 0, 1)
self.baseView.close(cellArray())
self.isClosed = true
}
// MARK: draw icon
public override func drawRect(rect: CGRect) {
drawCircle()
drawShadow()
}
/// create, configure & draw the plus layer (override and create your own shape in subclass!)
public func createPlusLayer(frame: CGRect) -> CAShapeLayer {
// draw plus shape
let plusLayer = CAShapeLayer()
plusLayer.lineCap = kCALineCapRound
plusLayer.strokeColor = UIColor.whiteColor().CGColor
plusLayer.lineWidth = 3.0
let path = UIBezierPath()
path.moveToPoint(CGPoint(x: frame.width * internalRadiusRatio, y: frame.height * 0.5))
path.addLineToPoint(CGPoint(x: frame.width * (1 - internalRadiusRatio), y: frame.height * 0.5))
path.moveToPoint(CGPoint(x: frame.width * 0.5, y: frame.height * internalRadiusRatio))
path.addLineToPoint(CGPoint(x: frame.width * 0.5, y: frame.height * (1 - internalRadiusRatio)))
plusLayer.path = path.CGPath
return plusLayer
}
private func drawCircle() {
self.circleLayer.cornerRadius = self.frame.width * 0.5
self.circleLayer.masksToBounds = true
if touching && responsible {
self.circleLayer.backgroundColor = self.color.white(0.5).CGColor
} else {
self.circleLayer.backgroundColor = self.color.CGColor
}
}
private func drawShadow() {
if enableShadow {
circleLayer.appendShadow()
}
}
// MARK: Events
public override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
self.touching = true
setNeedsDisplay()
}
public override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
self.touching = false
setNeedsDisplay()
didTapped()
}
public override func touchesCancelled(touches: Set<UITouch>?, withEvent event: UIEvent?) {
self.touching = false
setNeedsDisplay()
}
public override func hitTest(point: CGPoint, withEvent event: UIEvent?) -> UIView? {
for cell in cellArray() {
let pointForTargetView = cell.convertPoint(point, fromView: self)
if (CGRectContainsPoint(cell.bounds, pointForTargetView)) {
if cell.userInteractionEnabled {
return cell.hitTest(pointForTargetView, withEvent: event)
}
}
}
return super.hitTest(point, withEvent: event)
}
// MARK: private methods
private func setup() {
self.backgroundColor = UIColor.clearColor()
self.clipsToBounds = false
baseView.setup(self)
self.baseView.baseLiquid?.removeFromSuperview()
addSubview(baseView)
actionButtonView.frame = baseView.frame
actionButtonView.userInteractionEnabled = false
addSubview(actionButtonView)
actionButtonView.layer.addSublayer(circleLayer)
circleLayer.frame = actionButtonView.layer.bounds
plusLayer = createPlusLayer(circleLayer.bounds)
circleLayer.addSublayer(plusLayer)
plusLayer.frame = circleLayer.bounds
}
private func didTapped() {
if isClosed {
open()
} else {
close()
}
}
public func didTappedCell(target: FloatingCell) {
if let _ = dataSource {
let cells = cellArray()
for i in 0 ..< cells.count {
let cell = cells[i]
if target === cell {
delegate?.floatingActionButton?(self, didSelectItemAtIndex: i)
}
}
}
}
}
class ActionBarBaseView: UIView {
var opening = false
func setup(actionButton: FloatingActionButton) {
}
func translateY(layer: CALayer, duration: CFTimeInterval, f: (CABasicAnimation) -> ()) {
let translate = CABasicAnimation(keyPath: "transform.translation.y")
f(translate)
translate.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
translate.removedOnCompletion = false
translate.fillMode = kCAFillModeForwards
translate.duration = duration
layer.addAnimation(translate, forKey: "transYAnim")
}
}
class CircleBaseView: ActionBarBaseView {
let openDuration: CGFloat = 0.4
let closeDuration: CGFloat = 0.15
let viscosity: CGFloat = 0.65
var animateStyle: FloatingActionButtonAnimateStyle = .Up
var color: UIColor = UIColor(red: 82 / 255.0, green: 112 / 255.0, blue: 235 / 255.0, alpha: 1.0)
var baseLiquid: FloatingCircle?
var enableShadow = true
private var openingCells: [FloatingCell] = []
private var keyDuration: CGFloat = 0
private var displayLink: CADisplayLink?
override func setup(actionButton: FloatingActionButton) {
self.frame = actionButton.frame
self.center = actionButton.center.minus(actionButton.frame.origin)
self.animateStyle = actionButton.animateStyle
let radius = min(self.frame.width, self.frame.height) * 0.5
baseLiquid = FloatingCircle(center: self.center.minus(self.frame.origin), radius: radius, color: actionButton.color)
baseLiquid?.clipsToBounds = false
baseLiquid?.layer.masksToBounds = false
clipsToBounds = false
layer.masksToBounds = false
addSubview(baseLiquid!)
}
func open(cells: [FloatingCell]) {
stop()
displayLink = CADisplayLink(target: self, selector: #selector(CircleBaseView.didDisplayRefresh(_:)))
displayLink?.addToRunLoop(NSRunLoop.currentRunLoop(), forMode: NSRunLoopCommonModes)
opening = true
for cell in cells {
cell.layer.removeAllAnimations()
cell.layer.appendShadow()
openingCells.append(cell)
}
}
func close(cells: [FloatingCell]) {
stop()
opening = false
displayLink = CADisplayLink(target: self, selector: #selector(CircleBaseView.didDisplayRefresh(_:)))
displayLink?.addToRunLoop(NSRunLoop.currentRunLoop(), forMode: NSRunLoopCommonModes)
for cell in cells {
cell.layer.removeAllAnimations()
openingCells.append(cell)
cell.userInteractionEnabled = false
}
}
func didFinishUpdate() {
if opening {
for cell in openingCells {
cell.userInteractionEnabled = true
}
} else {
for cell in openingCells {
cell.removeFromSuperview()
}
}
}
func update(delay: CGFloat, duration: CGFloat, opening: Bool, f: (FloatingCell, Int, CGFloat) -> ()) {
if openingCells.isEmpty {
return
}
let maxDuration = duration + CGFloat(delay)
let t = keyDuration
let allRatio = easeInEaseOut(t / maxDuration)
if allRatio >= 1.0 {
didFinishUpdate()
stop()
return
}
let easeInOutRate = allRatio * allRatio * allRatio
let alphaColor = opening ? easeInOutRate : 1 - easeInOutRate
if opening {
for i in 0 ..< openingCells.count {
let liquidCell = openingCells[i]
let cellDelay = CGFloat(delay)
let ratio = easeInEaseOut((t - cellDelay) / duration)
f(liquidCell, i, ratio)
}
if let firstCell = openingCells.first {
firstCell.alpha = alphaColor
}
for i in 1 ..< openingCells.count {
let prev = openingCells[i - 1]
let cell = openingCells[i]
cell.alpha = alphaColor
}
} else {
for i in 0 ..< openingCells.count {
let cell = openingCells[i]
cell.alpha = alphaColor
}
}
}
func updateOpen() {
update(0.1, duration: openDuration, opening: true) {
cell, i, ratio in
let posRatio = 0.5 + (ratio / 3.333333333)
let distance = (cell.frame.height * 0.5 + CGFloat(i + 1) * cell.frame.height * 1.5) * posRatio
cell.center = self.center.plus(self.differencePoint(distance))
cell.update(ratio, open: true)
}
}
func updateClose() {
update(0, duration: closeDuration, opening: false) {
cell, i, ratio in
let posRatio = 0.5 + (ratio / 3.333333333)
let distance = (cell.frame.height * 0.5 + CGFloat(i + 1) * cell.frame.height * 1.5) * posRatio
cell.center = self.center.plus(self.differencePoint(distance))
cell.update(ratio, open: false)
}
}
func differencePoint(distance: CGFloat) -> CGPoint {
switch animateStyle {
case .Up:
return CGPoint(x: 0, y: -distance)
case .Right:
return CGPoint(x: distance, y: 0)
case .Left:
return CGPoint(x: -distance, y: 0)
case .Down:
return CGPoint(x: 0, y: distance)
}
}
func stop() {
openingCells = []
keyDuration = 0
displayLink?.invalidate()
}
func easeInEaseOut(t: CGFloat) -> CGFloat {
if t >= 1.0 {
return 1.0
}
if t < 0 {
return 0
}
return -1 * t * (t - 2)
}
func didDisplayRefresh(displayLink: CADisplayLink) {
if opening {
keyDuration += CGFloat(displayLink.duration)
updateOpen()
} else {
keyDuration += CGFloat(displayLink.duration)
updateClose()
}
}
}
| mit | c0bc57e0335d11b41d8e210b3facf83e | 29.511111 | 141 | 0.604151 | 4.750865 | false | false | false | false |
cly/swiftris | swiftris/GameViewController.swift | 1 | 5270 | //
// GameViewController.swift
// swiftris
//
// Created by Charlie Liang Yuan on 9/27/14.
// Copyright (c) 2014 Bloc. All rights reserved.
//
import UIKit
import SpriteKit
class GameViewController: UIViewController, SwiftrisDelegate, UIGestureRecognizerDelegate {
var scene: GameScene!
var swiftris:Swiftris!
var panPointReference:CGPoint?
@IBOutlet var scoreLabel: UILabel!
@IBOutlet var levelLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Configure the view.
let skView = view as SKView
skView.multipleTouchEnabled = false
// Create and configure the scene.
scene = GameScene(size: skView.bounds.size)
scene.scaleMode = .AspectFill
scene.tick = didTick
swiftris = Swiftris()
swiftris.delegate = self
swiftris.beginGame()
// Present the scene.
skView.presentScene(scene)
}
override func prefersStatusBarHidden() -> Bool {
return true
}
@IBAction func didTap(sender: UITapGestureRecognizer) {
swiftris.rotateShape()
}
@IBAction func didPan(sender: UIPanGestureRecognizer) {
let currentPoint = sender.translationInView(self.view)
if let originalPoint = panPointReference {
if abs(currentPoint.x - originalPoint.x) > (BlockSize * 0.9) {
if sender.velocityInView(self.view).x > CGFloat(0) {
swiftris.moveShapeRight()
panPointReference = currentPoint
} else {
swiftris.moveShapeLeft()
panPointReference = currentPoint
}
}
} else if sender.state == .Began {
panPointReference = currentPoint
}
}
@IBAction func didSwipe(sender: UISwipeGestureRecognizer) {
swiftris.dropShape()
}
func gestureRecognizer(gestureRecognizer: UIGestureRecognizer!, shouldRecognizeSimultaneouslyWithGestureRecognizer otherGestureRecognizer: UIGestureRecognizer!) -> Bool {
return true
}
func gestureRecognizer(gestureRecognizer: UIGestureRecognizer!, shouldBeRequiredToFailByGestureRecognizer otherGestureRecognizer: UIGestureRecognizer!) -> Bool {
if let swipeRec = gestureRecognizer as? UISwipeGestureRecognizer {
if let panRec = otherGestureRecognizer as? UIPanGestureRecognizer {
return true
}
} else if let panRec = gestureRecognizer as? UIPanGestureRecognizer {
if let tapRec = otherGestureRecognizer as? UITapGestureRecognizer {
return true
}
}
return false
}
func didTick() {
swiftris.letShapeFall()
}
func nextShape() {
let newShapes = swiftris.newShape()
if let fallingShape = newShapes.fallingShape {
self.scene.addPreviewShapeToScene(newShapes.nextShape!) {}
self.scene.movePreviewShape(fallingShape) {
self.view.userInteractionEnabled = true
self.scene.startTicking()
}
}
}
func gameDidBegin(swiftris: Swiftris) {
levelLabel.text = "\(swiftris.level)"
scoreLabel.text = "\(swiftris.score)"
scene.tickLengthMillis = TickLengthLevelOne
// The following is false when restarting a new game
if swiftris.nextShape != nil && swiftris.nextShape!.blocks[0].sprite == nil {
scene.addPreviewShapeToScene(swiftris.nextShape!) {
self.nextShape()
}
} else {
nextShape()
}
}
func gameDidEnd(swiftris: Swiftris) {
view.userInteractionEnabled = false
scene.stopTicking()
scene.playSound("gameover.mp3")
scene.animateCollapsingLines(swiftris.removeAllBlocks(), fallenBlocks: Array<Array<Block>>()) {
swiftris.beginGame()
}
}
func gameDidLevelUp(swiftris: Swiftris) {
levelLabel.text = "\(swiftris.level)"
if scene.tickLengthMillis >= 100 {
scene.tickLengthMillis -= 100
} else if scene.tickLengthMillis > 50 {
scene.tickLengthMillis -= 50
}
scene.playSound("levelup.mp3")
}
func gameShapeDidDrop(swiftris: Swiftris) {
scene.stopTicking()
scene.redrawShape(swiftris.fallingShape!) {
swiftris.letShapeFall()
}
scene.playSound("drop.mp3")
}
func gameShapeDidLand(swiftris: Swiftris) {
scene.stopTicking()
self.view.userInteractionEnabled = false
let removedLines = swiftris.removeCompletedLines()
if removedLines.linesRemoved.count > 0 {
self.scoreLabel.text = "\(swiftris.score)"
scene.animateCollapsingLines(removedLines.linesRemoved, fallenBlocks:removedLines.fallenBlocks) {
self.gameShapeDidLand(swiftris)
}
scene.playSound("bomb.mp3")
} else {
nextShape()
}
}
func gameShapeDidMove(swiftris: Swiftris) {
scene.redrawShape(swiftris.fallingShape!) {}
}
} | mit | 249fd3e3ca2277e209452b5b09c44f3b | 31.337423 | 174 | 0.606831 | 5.047893 | false | false | false | false |
wenghengcong/Coderpursue | BeeFun/BeeFun/View/Stars/ViewCell/JSSegmentControl.swift | 1 | 3274 | //
// JSSegmentControl.swift
// BeeFun
//
// Created by WengHengcong on 2017/5/11.
// Copyright © 2017年 JungleSong. All rights reserved.
//
import UIKit
protocol JSSegmentControlProtocol: class {
func selectedSegmentContrlol(segment: JSSegmentControl, index: Int)
}
/// 导航栏横滑的segment control
class JSSegmentControl: UIView {
/// 初始化的时候,不调用didSet
var titles: [String] {
didSet {
didSetSegmentTitles()
}
}
var selIndex: Int = 0
var backgroundImage: UIImageView = UIImageView(image: UIImage(named: "nav_seg_nor"))
var segButtons: [UIButton]?
weak var delegate: JSSegmentControlProtocol?
override init(frame: CGRect) {
self.titles = []
super.init(frame: frame)
segmentViewInit()
}
convenience init(titles: [String]) {
self.init(titles: titles, frame: CGRect.zero)
}
convenience init(titles: [String], frame: CGRect) {
self.init(frame: frame)
// 注意:初始化的时候,不调用didSet
self.titles = titles
didSetSegmentTitles()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func segmentViewInit() {
self.addSubview(backgroundImage)
backgroundImage.frame = self.frame
}
func didSetSegmentTitles() {
assert(!self.titles.isEmpty, "titles can't empty")
segButtons = []
for (index, title) in titles.enumerated() {
let segBtn = UIButton()
segBtn.tag = index
segBtn.setTitle(title, for: .normal)
segBtn.setTitle(title, for: .highlighted)
segBtn.setTitleColor(UIColor.white, for: .normal)
segBtn.setTitleColor(UIColor.bfRedColor, for: .selected)
segBtn.titleLabel?.font = UIFont.bfSystemFont(ofSize: 15.0)
segBtn.titleLabel?.adjustFontSizeToFitWidth(minScale: 0.5)
segBtn.setBackgroundImage(UIImage(named: "nav_seg_sel"), for: .selected)
segBtn.setBackgroundImage(UIImage(named: "nav_seg_sel"), for: .highlighted)
segBtn.addTarget(self, action: #selector(didSelectedSegment(sender:)), for: .touchUpInside)
segButtons?.append(segBtn)
self.addSubview(segBtn)
}
self.segButtons?.first?.isSelected = true
setNeedsDisplay()
}
override func layoutSubviews() {
if !self.titles.isEmpty && self.segButtons != nil && !(self.segButtons?.isEmpty)! {
let btnW = self.width/CGFloat(self.titles.count)
for index in titles.indices {
let segBtn = self.segButtons![index]
segBtn.frame = CGRect(x: CGFloat(index) * btnW, y: 0, w: btnW, h: self.height)
}
}
}
@objc func didSelectedSegment(sender: UIButton) {
if sender.isKind(of: UIButton.self) {
let tag = sender.tag
for segBtn: UIButton in self.segButtons! {
segBtn.isSelected = (segBtn.tag == tag) ? true : false
}
selIndex = tag
self.delegate?.selectedSegmentContrlol(segment: self, index: selIndex)
}
}
}
| mit | 8563a87482d8672cec1cd20914bc2f14 | 32.123711 | 103 | 0.602552 | 4.25 | false | false | false | false |
flow-ai/flowai-swift | FlowCore/Classes/LocationTemplate.swift | 1 | 1241 | import Foundation
/**
Location response template
*/
public class LocationTemplate : Template {
/// Title of the location
private(set) public var title:String?
/// Latitude
private(set) public var lat:Double!
/// Longitude
private(set) public var long:Double!
/// Optional action
private(set) public var action:Action? = nil
override init(_ data: [String: Any]) throws {
try super.init(data)
guard let title = data["title"] as? String else {
throw Exception.Serialzation("location template has no title")
}
self.title = title
guard let lat = data["lat"] as? String else {
throw Exception.Serialzation("location template has no latitude")
}
self.lat = Double(lat)
guard let long = data["long"] as? String else {
throw Exception.Serialzation("location template has no longitude")
}
self.long = Double(long)
if let action = data["action"] as? [String:Any] {
self.action = try Action(action)
}
}
public required init() {
super.init()
}
}
| mit | 7297265445a4f93281b0397e37d37c53 | 23.82 | 78 | 0.550363 | 4.828794 | false | false | false | false |
jacobwhite/firefox-ios | Client/Frontend/Widgets/PhotonActionSheet.swift | 1 | 27418 | /* 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 Storage
import SnapKit
import Shared
private struct PhotonActionSheetUX {
static let MaxWidth: CGFloat = 414
static let Padding: CGFloat = 10
static let HeaderFooterHeight: CGFloat = 20
static let RowHeight: CGFloat = 50
static let BorderWidth: CGFloat = 0.5
static let BorderColor = UIColor(white: 0, alpha: 0.1)
static let CornerRadius: CGFloat = 10
static let SiteImageViewSize = 52
static let IconSize = CGSize(width: 24, height: 24)
static let SiteHeaderName = "PhotonActionSheetSiteHeaderView"
static let TitleHeaderName = "PhotonActionSheetTitleHeaderView"
static let CellName = "PhotonActionSheetCell"
static let CloseButtonHeight: CGFloat = 56
static let TablePadding: CGFloat = 6
}
public struct PhotonActionSheetItem {
public fileprivate(set) var title: String
public fileprivate(set) var text: String?
public fileprivate(set) var iconString: String?
public fileprivate(set) var iconURL: URL?
public var isEnabled: Bool // Used by toggles like nightmode to switch tint color
public fileprivate(set) var accessory: PhotonActionSheetCellAccessoryType
public fileprivate(set) var accessoryText: String?
public fileprivate(set) var bold: Bool = false
public fileprivate(set) var handler: ((PhotonActionSheetItem) -> Void)?
init(title: String, text: String? = nil, iconString: String? = nil, iconURL: URL? = nil, isEnabled: Bool = false, accessory: PhotonActionSheetCellAccessoryType = .None, accessoryText: String? = nil, bold: Bool? = false, handler: ((PhotonActionSheetItem) -> Void)? = nil) {
self.title = title
self.iconString = iconString
self.iconURL = iconURL
self.isEnabled = isEnabled
self.accessory = accessory
self.handler = handler
self.text = text
self.accessoryText = accessoryText
self.bold = bold ?? false
}
}
private enum PresentationStyle {
case centered // used in the home panels
case bottom // used to display the menu on phone sized devices
case popover // when displayed on the iPad
}
class PhotonActionSheet: UIViewController, UITableViewDelegate, UITableViewDataSource, UIGestureRecognizerDelegate {
fileprivate(set) var actions: [[PhotonActionSheetItem]]
private var site: Site?
private let style: PresentationStyle
private var tintColor = UIColor.Photon.Grey80
private var heightConstraint: Constraint?
var tableView = UITableView(frame: .zero, style: .grouped)
lazy var tapRecognizer: UITapGestureRecognizer = {
let tapRecognizer = UITapGestureRecognizer()
tapRecognizer.addTarget(self, action: #selector(dismiss))
tapRecognizer.numberOfTapsRequired = 1
tapRecognizer.cancelsTouchesInView = false
tapRecognizer.delegate = self
return tapRecognizer
}()
lazy var closeButton: UIButton = {
let button = UIButton()
button.setTitle(Strings.CloseButtonTitle, for: .normal)
button.backgroundColor = UIConstants.AppBackgroundColor
button.setTitleColor(UIConstants.SystemBlueColor, for: .normal)
button.layer.cornerRadius = PhotonActionSheetUX.CornerRadius
button.titleLabel?.font = DynamicFontHelper.defaultHelper.DeviceFontExtraLargeBold
button.addTarget(self, action: #selector(dismiss), for: .touchUpInside)
button.accessibilityIdentifier = "PhotonMenu.close"
return button
}()
var photonTransitionDelegate: UIViewControllerTransitioningDelegate? {
didSet {
self.transitioningDelegate = photonTransitionDelegate
}
}
init(site: Site, actions: [PhotonActionSheetItem]) {
self.site = site
self.actions = [actions]
self.style = .centered
super.init(nibName: nil, bundle: nil)
}
init(title: String? = nil, actions: [[PhotonActionSheetItem]], style presentationStyle: UIModalPresentationStyle) {
self.actions = actions
self.style = presentationStyle == .popover ? .popover : .bottom
super.init(nibName: nil, bundle: nil)
self.title = title
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
if style == .centered {
applyBackgroundBlur()
self.tintColor = UIConstants.SystemBlueColor
}
view.addGestureRecognizer(tapRecognizer)
view.addSubview(tableView)
view.accessibilityIdentifier = "Action Sheet"
// In a popover the popover provides the blur background
// Not using a background color allows the view to style correctly with the popover arrow
if self.popoverPresentationController == nil {
tableView.backgroundColor = UIConstants.AppBackgroundColor.withAlphaComponent(0.7)
let blurEffect = UIBlurEffect(style: .light)
let blurEffectView = UIVisualEffectView(effect: blurEffect)
tableView.backgroundView = blurEffectView
} else {
tableView.backgroundColor = .clear
}
let width = min(self.view.frame.size.width, PhotonActionSheetUX.MaxWidth) - (PhotonActionSheetUX.Padding * 2)
if style == .bottom {
self.view.addSubview(closeButton)
closeButton.snp.makeConstraints { make in
make.centerX.equalTo(self.view.snp.centerX)
make.width.equalTo(width)
make.height.equalTo(PhotonActionSheetUX.CloseButtonHeight)
make.bottom.equalTo(self.view.safeArea.bottom).inset(PhotonActionSheetUX.Padding)
}
}
if style == .popover {
self.actions = actions.map({ $0.reversed() }).reversed()
tableView.snp.makeConstraints { make in
make.edges.equalTo(self.view)
}
} else {
tableView.snp.makeConstraints { make in
make.centerX.equalTo(self.view.snp.centerX)
switch style {
case .bottom, .popover:
make.bottom.equalTo(closeButton.snp.top).offset(-PhotonActionSheetUX.Padding)
case .centered:
make.centerY.equalTo(self.view.snp.centerY)
}
make.width.equalTo(width)
}
}
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
tableView.bounces = false
tableView.delegate = self
tableView.dataSource = self
tableView.keyboardDismissMode = .onDrag
tableView.register(PhotonActionSheetCell.self, forCellReuseIdentifier: PhotonActionSheetUX.CellName)
tableView.register(PhotonActionSheetSiteHeaderView.self, forHeaderFooterViewReuseIdentifier: PhotonActionSheetUX.SiteHeaderName)
tableView.register(PhotonActionSheetTitleHeaderView.self, forHeaderFooterViewReuseIdentifier: PhotonActionSheetUX.TitleHeaderName)
tableView.register(PhotonActionSheetSeparator.self, forHeaderFooterViewReuseIdentifier: "SeparatorSectionHeader")
tableView.register(UITableViewHeaderFooterView.self, forHeaderFooterViewReuseIdentifier: "EmptyHeader")
tableView.estimatedRowHeight = PhotonActionSheetUX.RowHeight
tableView.estimatedSectionFooterHeight = PhotonActionSheetUX.HeaderFooterHeight
// When the menu style is centered the header is much bigger than default. Set a larger estimated height to make sure autolayout sizes the view correctly
tableView.estimatedSectionHeaderHeight = (style == .centered) ? PhotonActionSheetUX.RowHeight : PhotonActionSheetUX.HeaderFooterHeight
tableView.isScrollEnabled = true
tableView.showsVerticalScrollIndicator = false
tableView.layer.cornerRadius = PhotonActionSheetUX.CornerRadius
tableView.separatorStyle = .none
tableView.cellLayoutMarginsFollowReadableWidth = false
tableView.accessibilityIdentifier = "Context Menu"
let footer = UIView(frame: CGRect(width: tableView.frame.width, height: PhotonActionSheetUX.Padding))
tableView.tableHeaderView = footer
tableView.tableFooterView = footer.clone()
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
let maxHeight = self.view.frame.height - (style == .bottom ? PhotonActionSheetUX.CloseButtonHeight : 0)
tableView.snp.makeConstraints { make in
heightConstraint?.deactivate()
// The height of the menu should be no more than 80 percent of the screen
heightConstraint = make.height.equalTo(min(self.tableView.contentSize.height, maxHeight * 0.8)).constraint
}
if style == .popover {
self.preferredContentSize = self.tableView.contentSize
}
}
private func applyBackgroundBlur() {
let appDelegate = UIApplication.shared.delegate as! AppDelegate
if let screenshot = appDelegate.window?.screenshot() {
let blurredImage = screenshot.applyBlur(withRadius: 5,
blurType: BOXFILTER,
tintColor: UIColor.black.withAlphaComponent(0.2),
saturationDeltaFactor: 1.8,
maskImage: nil)
let imageView = UIImageView(image: blurredImage)
view.addSubview(imageView)
}
}
@objc func dismiss(_ gestureRecognizer: UIGestureRecognizer?) {
self.dismiss(animated: true, completion: nil)
}
deinit {
tableView.dataSource = nil
tableView.delegate = nil
}
override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
super.traitCollectionDidChange(previousTraitCollection)
if self.traitCollection.verticalSizeClass != previousTraitCollection?.verticalSizeClass
|| self.traitCollection.horizontalSizeClass != previousTraitCollection?.horizontalSizeClass {
updateViewConstraints()
}
}
func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool {
if tableView.frame.contains(touch.location(in: self.view)) {
return false
}
return true
}
func numberOfSections(in tableView: UITableView) -> Int {
return actions.count
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return actions[section].count
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
var action = actions[indexPath.section][indexPath.row]
guard let handler = action.handler else {
self.dismiss(nil)
return
}
// Switches can be toggled on/off without dismissing the menu
if action.accessory == .Switch {
let generator = UIImpactFeedbackGenerator(style: .medium)
generator.impactOccurred()
action.isEnabled = !action.isEnabled
actions[indexPath.section][indexPath.row] = action
self.tableView.deselectRow(at: indexPath, animated: true)
self.tableView.reloadData()
} else {
self.dismiss(nil)
}
return handler(action)
}
func tableView(_ tableView: UITableView, hasFullWidthSeparatorForRowAtIndexPath indexPath: IndexPath) -> Bool {
return false
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: PhotonActionSheetUX.CellName, for: indexPath) as! PhotonActionSheetCell
let action = actions[indexPath.section][indexPath.row]
cell.tintColor = self.tintColor
cell.configure(with: action)
return cell
}
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
// If we have multiple sections show a separator for each one except the first.
if section > 0 {
return tableView.dequeueReusableHeaderFooterView(withIdentifier: "SeparatorSectionHeader")
}
if let site = site {
let header = tableView.dequeueReusableHeaderFooterView(withIdentifier: PhotonActionSheetUX.SiteHeaderName) as! PhotonActionSheetSiteHeaderView
header.tintColor = self.tintColor
header.configure(with: site)
return header
} else if let title = title {
let header = tableView.dequeueReusableHeaderFooterView(withIdentifier: PhotonActionSheetUX.TitleHeaderName) as! PhotonActionSheetTitleHeaderView
header.tintColor = self.tintColor
header.configure(with: title)
return header
}
// A header height of at least 1 is required to make sure the default header size isnt used when laying out with AutoLayout
let view = tableView.dequeueReusableHeaderFooterView(withIdentifier: "EmptyHeader")
view?.snp.makeConstraints { make in
make.height.equalTo(1)
}
return view
}
// A footer height of at least 1 is required to make sure the default footer size isnt used when laying out with AutoLayout
func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
let view = tableView.dequeueReusableHeaderFooterView(withIdentifier: "EmptyHeader")
view?.snp.makeConstraints { make in
make.height.equalTo(1)
}
return view
}
}
private class PhotonActionSheetTitleHeaderView: UITableViewHeaderFooterView {
static let Padding: CGFloat = 12
lazy var titleLabel: UILabel = {
let titleLabel = UILabel()
titleLabel.font = DynamicFontHelper.defaultHelper.SmallSizeRegularWeightAS
titleLabel.numberOfLines = 1
titleLabel.textColor = UIAccessibilityDarkerSystemColorsEnabled() ? UIColor.black : UIColor.gray
return titleLabel
}()
lazy var separatorView: UIView = {
let separatorLine = UIView()
separatorLine.backgroundColor = UIColor.lightGray
return separatorLine
}()
override init(reuseIdentifier: String?) {
super.init(reuseIdentifier: reuseIdentifier)
self.backgroundView = UIView()
self.backgroundView?.backgroundColor = .clear
contentView.addSubview(titleLabel)
titleLabel.snp.makeConstraints { make in
make.leading.equalTo(contentView).offset(PhotonActionSheetTitleHeaderView.Padding)
make.trailing.equalTo(contentView)
make.top.equalTo(contentView).offset(PhotonActionSheetUX.TablePadding)
}
contentView.addSubview(separatorView)
separatorView.snp.makeConstraints { make in
make.leading.trailing.equalTo(self)
make.top.equalTo(titleLabel.snp.bottom).offset(PhotonActionSheetUX.TablePadding)
make.bottom.equalTo(contentView).inset(PhotonActionSheetUX.TablePadding)
make.height.equalTo(0.5)
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func configure(with title: String) {
self.titleLabel.text = title
}
override func prepareForReuse() {
self.titleLabel.text = nil
}
}
private class PhotonActionSheetSiteHeaderView: UITableViewHeaderFooterView {
static let Padding: CGFloat = 12
static let VerticalPadding: CGFloat = 2
lazy var titleLabel: UILabel = {
let titleLabel = UILabel()
titleLabel.font = DynamicFontHelper.defaultHelper.MediumSizeBoldFontAS
titleLabel.textAlignment = .left
titleLabel.numberOfLines = 2
return titleLabel
}()
lazy var descriptionLabel: UILabel = {
let titleLabel = UILabel()
titleLabel.font = DynamicFontHelper.defaultHelper.MediumSizeRegularWeightAS
titleLabel.textAlignment = .left
titleLabel.numberOfLines = 1
return titleLabel
}()
lazy var siteImageView: UIImageView = {
let siteImageView = UIImageView()
siteImageView.contentMode = .center
siteImageView.clipsToBounds = true
siteImageView.layer.cornerRadius = PhotonActionSheetUX.CornerRadius
siteImageView.layer.borderColor = PhotonActionSheetUX.BorderColor.cgColor
siteImageView.layer.borderWidth = PhotonActionSheetUX.BorderWidth
return siteImageView
}()
override init(reuseIdentifier: String?) {
super.init(reuseIdentifier: reuseIdentifier)
self.backgroundView = UIView()
self.backgroundView?.backgroundColor = .clear
contentView.addSubview(siteImageView)
siteImageView.snp.remakeConstraints { make in
make.top.equalTo(contentView).offset(PhotonActionSheetSiteHeaderView.Padding)
make.centerY.equalTo(contentView)
make.leading.equalTo(contentView).offset(PhotonActionSheetSiteHeaderView.Padding)
make.size.equalTo(PhotonActionSheetUX.SiteImageViewSize)
}
let stackView = UIStackView(arrangedSubviews: [titleLabel, descriptionLabel])
stackView.spacing = PhotonActionSheetSiteHeaderView.VerticalPadding
stackView.alignment = .leading
stackView.axis = .vertical
contentView.addSubview(stackView)
stackView.snp.makeConstraints { make in
make.leading.equalTo(siteImageView.snp.trailing).offset(PhotonActionSheetSiteHeaderView.Padding)
make.trailing.equalTo(contentView).inset(PhotonActionSheetSiteHeaderView.Padding)
make.centerY.equalTo(siteImageView.snp.centerY)
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func prepareForReuse() {
self.siteImageView.image = nil
self.siteImageView.backgroundColor = UIColor.clear
}
func configure(with site: Site) {
self.siteImageView.setFavicon(forSite: site) { (color, url) in
self.siteImageView.backgroundColor = color
self.siteImageView.image = self.siteImageView.image?.createScaled(PhotonActionSheetUX.IconSize)
}
self.titleLabel.text = site.title.isEmpty ? site.url : site.title
self.descriptionLabel.text = site.tileURL.baseDomain
}
}
private struct PhotonActionSheetCellUX {
static let LabelColor = UIConstants.SystemBlueColor
static let BorderWidth: CGFloat = CGFloat(0.5)
static let CellSideOffset = 20
static let TitleLabelOffset = 10
static let CellTopBottomOffset = 12
static let StatusIconSize = 24
static let SelectedOverlayColor = UIColor(white: 0.0, alpha: 0.25)
static let CornerRadius: CGFloat = 3
}
private class PhotonActionSheetSeparator: UITableViewHeaderFooterView {
let separatorLineView = UIView()
override init(reuseIdentifier: String?) {
super.init(reuseIdentifier: reuseIdentifier)
self.backgroundView = UIView()
self.backgroundView?.backgroundColor = .clear
separatorLineView.backgroundColor = UIColor.lightGray
self.contentView.addSubview(separatorLineView)
separatorLineView.snp.makeConstraints { make in
make.leading.trailing.equalTo(self)
make.centerY.equalTo(self)
make.height.equalTo(0.5)
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
public enum PhotonActionSheetCellAccessoryType {
case Disclosure
case Switch
case Text
case None
}
private class PhotonActionSheetCell: UITableViewCell {
static let Padding: CGFloat = 16
static let HorizontalPadding: CGFloat = 10
static let VerticalPadding: CGFloat = 2
static let IconSize = 16
lazy var titleLabel: UILabel = {
let titleLabel = UILabel()
titleLabel.font = DynamicFontHelper.defaultHelper.LargeSizeRegularWeightAS
titleLabel.minimumScaleFactor = 0.8 // Scale the font if we run out of space
titleLabel.textColor = PhotonActionSheetCellUX.LabelColor
titleLabel.setContentHuggingPriority(.defaultHigh, for: .vertical)
titleLabel.numberOfLines = 4
titleLabel.adjustsFontSizeToFitWidth = true
return titleLabel
}()
lazy var subtitleLabel: UILabel = {
let textLabel = UILabel()
textLabel.font = DynamicFontHelper.defaultHelper.SmallSizeRegularWeightAS
textLabel.setContentHuggingPriority(.defaultHigh, for: .vertical)
textLabel.minimumScaleFactor = 0.75 // Scale the font if we run out of space
textLabel.textColor = PhotonActionSheetCellUX.LabelColor
textLabel.numberOfLines = 3
textLabel.adjustsFontSizeToFitWidth = true
return textLabel
}()
lazy var statusIcon: UIImageView = {
let statusIcon = UIImageView()
statusIcon.contentMode = .scaleAspectFit
statusIcon.clipsToBounds = true
statusIcon.layer.cornerRadius = PhotonActionSheetCellUX.CornerRadius
statusIcon.setContentHuggingPriority(.required, for: .horizontal)
return statusIcon
}()
lazy var disclosureLabel: UILabel = {
let label = UILabel()
return label
}()
lazy var toggleSwitch: UIImageView = {
let toggle = UIImageView(image: UIImage(named: "menu-Toggle-Off"))
toggle.contentMode = .scaleAspectFit
return toggle
}()
lazy var selectedOverlay: UIView = {
let selectedOverlay = UIView()
selectedOverlay.backgroundColor = PhotonActionSheetCellUX.SelectedOverlayColor
selectedOverlay.isHidden = true
return selectedOverlay
}()
lazy var disclosureIndicator: UIImageView = {
let disclosureIndicator = UIImageView(image: UIImage(named: "menu-Disclosure"))
disclosureIndicator.contentMode = .scaleAspectFit
disclosureIndicator.layer.cornerRadius = PhotonActionSheetCellUX.CornerRadius
disclosureIndicator.setContentHuggingPriority(.required, for: .horizontal)
return disclosureIndicator
}()
lazy var stackView: UIStackView = {
let stackView = UIStackView()
stackView.spacing = PhotonActionSheetCell.Padding
stackView.alignment = .center
stackView.axis = .horizontal
return stackView
}()
override var isSelected: Bool {
didSet {
self.selectedOverlay.isHidden = !isSelected
}
}
override func prepareForReuse() {
self.statusIcon.image = nil
disclosureIndicator.removeFromSuperview()
disclosureLabel.removeFromSuperview()
toggleSwitch.removeFromSuperview()
}
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
isAccessibilityElement = true
contentView.addSubview(selectedOverlay)
backgroundColor = .clear
selectedOverlay.snp.makeConstraints { make in
make.edges.equalTo(contentView)
}
// Setup our StackViews
let textStackView = UIStackView(arrangedSubviews: [titleLabel, subtitleLabel])
textStackView.spacing = PhotonActionSheetCell.VerticalPadding
textStackView.setContentHuggingPriority(.defaultLow, for: .horizontal)
textStackView.alignment = .leading
textStackView.axis = .vertical
stackView.addArrangedSubview(statusIcon)
stackView.addArrangedSubview(textStackView)
contentView.addSubview(stackView)
let padding = PhotonActionSheetCell.Padding
let topPadding = PhotonActionSheetCell.HorizontalPadding
stackView.snp.makeConstraints { make in
make.edges.equalTo(contentView).inset(UIEdgeInsets(top: topPadding, left: padding, bottom: topPadding, right: padding))
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func configure(with action: PhotonActionSheetItem) {
titleLabel.text = action.title
titleLabel.textColor = self.tintColor
titleLabel.textColor = action.accessory == .Text ? titleLabel.textColor.withAlphaComponent(0.6) : titleLabel.textColor
subtitleLabel.text = action.text
subtitleLabel.textColor = self.tintColor
subtitleLabel.isHidden = action.text == nil
titleLabel.font = action.bold ? DynamicFontHelper.defaultHelper.DeviceFontLargeBold : DynamicFontHelper.defaultHelper.LargeSizeRegularWeightAS
accessibilityIdentifier = action.iconString
accessibilityLabel = action.title
selectionStyle = action.handler != nil ? .default : .none
if let iconName = action.iconString, let image = UIImage(named: iconName)?.withRenderingMode(.alwaysTemplate) {
statusIcon.sd_setImage(with: action.iconURL, placeholderImage: image, options: []) { (img, err, _, _) in
if let img = img {
self.statusIcon.image = img.createScaled(CGSize(width: 30, height: 30))
}
}
// When the iconURL is not nil we are most likely showing a profile picture.
// In that case we do not need a tint color. And make sure the image is sized correctly
// This is for the sync profile button in the menu
if action.iconURL == nil {
statusIcon.tintColor = self.tintColor
} else {
self.statusIcon.image = self.statusIcon.image?.createScaled(CGSize(width: 30, height: 30))
}
if statusIcon.superview == nil {
stackView.insertArrangedSubview(statusIcon, at: 0)
}
} else {
statusIcon.removeFromSuperview()
}
switch action.accessory {
case .Text:
disclosureLabel.font = action.bold ? DynamicFontHelper.defaultHelper.DeviceFontLargeBold : DynamicFontHelper.defaultHelper.LargeSizeRegularWeightAS
disclosureLabel.text = action.accessoryText
disclosureLabel.textColor = titleLabel.textColor
stackView.addArrangedSubview(disclosureLabel)
case .Disclosure:
stackView.addArrangedSubview(disclosureIndicator)
case .Switch:
let image = action.isEnabled ? UIImage(named: "menu-Toggle-On") : UIImage(named: "menu-Toggle-Off")
toggleSwitch.isAccessibilityElement = true
toggleSwitch.accessibilityIdentifier = action.isEnabled ? "enabled" : "disabled"
toggleSwitch.image = image
stackView.addArrangedSubview(toggleSwitch)
default:
break // Do nothing. The rest are not supported yet.
}
}
}
| mpl-2.0 | b999fe88da461d573137441a8d6a96d2 | 40.542424 | 276 | 0.675542 | 5.473747 | false | false | false | false |
SSU-CS-Department/ssumobile-ios | SSUMobile/Modules/Directory/Model/Classes/SSUDepartment.swift | 1 | 2050 | //
// SSUDepartment.swift
// SSUMobile
//
// Created by Eric Amorde on 7/8/18.
// Copyright © 2018 Sonoma State University Department of Computer Science. All rights reserved.
//
//
import Foundation
import CoreData
import SwiftyJSON
@objc(SSUDepartment)
public final class SSUDepartment: SSUDirectoryObject, SSUCoreDataEntity, SSUJSONInitializable {
struct Keys {
static let name = "name"
static let displayName = "display_name"
static let phone = "phone"
static let email = "email"
static let site = "site"
static let chairID = "chair"
static let acID = "ac"
static let buildingID = "building"
static let office = "office"
static let schoolID = "school"
}
// MARK: SSUCoreDataEntity
public typealias IdentifierType = String
public static var identifierKeyPath: KeyPath<SSUDepartment, IdentifierType> {
return \SSUDepartment.id
}
// MARK: -
var acID: SSUPerson.IdentifierType?
var buildingID: SSUBuilding.IdentifierType?
var chairID: SSUPerson.IdentifierType?
var schoolID: SSUSchool.IdentifierType?
@objc
func updateSectionName() {
let charactersToStrip = CharacterSet.alphanumerics.inverted
if let sectionRaw = displayName?.trimmingCharacters(in: charactersToStrip), sectionRaw.count > 0 {
sectionName = String(sectionRaw.prefix(1))
} else {
sectionName = nil
}
}
func initializeWith(json: JSON) throws {
name = json[Keys.name].stringValue
displayName = json[Keys.displayName].string ?? name
term = displayName
email = json[Keys.email].string
phone = json[Keys.phone].string
site = json[Keys.site].string
office = json[Keys.office].string
buildingID = json[Keys.buildingID].int
chairID = json[Keys.chairID].int
acID = json[Keys.acID].int
schoolID = json[Keys.schoolID].int
}
}
| apache-2.0 | 4b28f1f1aff6574fc75ee446caabbc1f | 27.859155 | 106 | 0.634456 | 4.277662 | false | false | false | false |
kickstarter/ios-oss | Kickstarter-iOS/Features/Dashboard/Views/DashboardReferrerRowStackView.swift | 1 | 1395 | import KsApi
import Library
import Prelude
import UIKit
internal final class DashboardReferrerRowStackView: UIStackView {
fileprivate let viewModel: DashboardReferrerRowStackViewViewModelType
= DashboardReferrerRowStackViewViewModel()
fileprivate let backersLabel: UILabel = UILabel()
fileprivate let pledgedLabel: UILabel = UILabel()
fileprivate let sourceLabel: UILabel = UILabel()
internal init(
frame: CGRect,
country: Project.Country,
referrer: ProjectStatsEnvelope.ReferrerStats
) {
super.init(frame: frame)
_ = self |> dashboardStatsRowStackViewStyle
_ = self.backersLabel |> dashboardColumnTextLabelStyle
_ = self.pledgedLabel |> dashboardColumnTextLabelStyle
_ = self.sourceLabel |> dashboardReferrersSourceLabelStyle
self.addArrangedSubview(self.sourceLabel)
self.addArrangedSubview(self.pledgedLabel)
self.addArrangedSubview(self.backersLabel)
self.backersLabel.rac.text = self.viewModel.outputs.backersText
self.pledgedLabel.rac.text = self.viewModel.outputs.pledgedText
self.sourceLabel.rac.text = self.viewModel.outputs.sourceText
self.sourceLabel.rac.textColor = self.viewModel.outputs.textColor
self.viewModel.inputs.configureWith(country: country, referrer: referrer)
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:\(aDecoder)) has not been implemented")
}
}
| apache-2.0 | d5e2b1d20e5478279f83eb3cbf10cfd8 | 31.44186 | 77 | 0.772043 | 4.588816 | false | false | false | false |
zom/Zom-iOS | Zom/Zom/Classes/ZomBuddy.swift | 1 | 1465 | //
// ZomBuddy.swift
// Zom
//
// Created by N-Pex on 2016-06-17.
//
//
import UIKit
import ChatSecureCore
extension OTRBuddy {
@objc public static func swizzle() {
ZomUtil.swizzle(self, originalSelector: #selector(getter: OTRUserInfoProfile.displayName), swizzledSelector:#selector(OTRBuddy.zom_getDisplayName))
}
@objc func zom_getDisplayName() -> String? {
let originalDisplayName = self.zom_getDisplayName()
let account = self.username
if (originalDisplayName == nil || account.compare(originalDisplayName!) == ComparisonResult.orderedSame) {
let split = account.components(separatedBy: "@")
if (split.count > 0) {
var displayName = split[0]
// Strip hex digits at end?
let regex = try! NSRegularExpression(pattern: "\\.[a-fA-F0-9]{4,8}$", options: [])
displayName = regex.stringByReplacingMatches(in: displayName, options: [], range: NSMakeRange(0, displayName.characters.count), withTemplate: "")
self.displayName = displayName
return displayName
}
}
return originalDisplayName
}
public func isYou(transaction:YapDatabaseReadTransaction) -> Bool {
if let account = self.account(with: transaction), account.username == self.username {
return true
}
return false
}
}
| mpl-2.0 | 83a68cead8441d63dfe94b44539d5e5f | 33.069767 | 161 | 0.604096 | 4.7411 | false | false | false | false |
odnoletkov/OptJSON | OptJSONTests/OptJSONTests.swift | 1 | 3255 | //
// OptJSONTests.swift
// OptJSONTests
//
// Created by max on 26.06.14.
//
//
import XCTest
import OptJSON
let nativeJSON = [
"name": "John Smith",
"isAlive": true,
"age": 25,
"height_cm": 167.64,
"pet": NSNull(),
"address": [
"city": "New York",
],
"phoneNumbers": [
[
"type": "home",
"number": "212 555-1234"
],
[
"type": "office",
"number": "646 555-4567",
]
],
]
class OptJSONTests: XCTestCase {
let nsJSON : AnyObject! = {
let data = NSJSONSerialization.dataWithJSONObject(nativeJSON, options: NSJSONWritingOptions(0), error: nil)
return NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions(0), error: nil)
}()
func testBaseTypes() {
XCTAssert(JSON(nativeJSON)?[key:"pet"] as? NSNull == NSNull())
XCTAssert(JSON(nativeJSON)?[key:"isAlive"] as? NSNumber == true)
XCTAssert(JSON(nativeJSON)?[key:"age"] as? NSNumber == 25)
XCTAssert(JSON(nativeJSON)?[key:"height_cm"] as? NSNumber == 167.64)
XCTAssert(JSON(nativeJSON)?[key:"name"] as? NSString == "John Smith")
XCTAssert(JSON(nativeJSON)?[key:"phoneNumbers"] as? NSArray != nil)
XCTAssert(JSON(nativeJSON)?[key:"address"] as? NSDictionary != nil)
}
func testOptionalChaining() {
XCTAssert(JSON(nativeJSON)?[key:"address"]?[key:"city"] as? NSString == "New York")
XCTAssert(JSON(nativeJSON)?[key:"phoneNumbers"]?[index:0]?[key:"type"] as? NSString == "home")
XCTAssert(JSON(nativeJSON)?[key:"missing"]?[index:0]?[key:"missing"] as? NSNumber == nil)
}
func testSafeArrayBounds() {
XCTAssert(JSON(nativeJSON)?[key:"phoneNumbers"]?[index:2] as? NSDictionary == nil)
}
func testNSJSONSerialization() {
XCTAssert(JSON(nsJSON)?[key:"pet"] as? NSNull == NSNull())
XCTAssert(JSON(nsJSON)?[key:"isAlive"] as? NSNumber == true)
XCTAssert(JSON(nsJSON)?[key:"age"] as? NSNumber == 25)
XCTAssert(JSON(nsJSON)?[key:"height_cm"] as? NSNumber == 167.64)
XCTAssert(JSON(nsJSON)?[key:"name"] as? NSString == "John Smith")
XCTAssert(JSON(nsJSON)?[key:"phoneNumbers"] as? NSArray != nil)
XCTAssert(JSON(nsJSON)?[key:"address"] as? NSDictionary != nil)
}
func testCompareSyntax() {
if let person = nsJSON as? NSDictionary {
if let phones = person["phoneNumbers"] as? NSArray {
if let phone = phones[1] as? NSDictionary {
if let number = phone["number"] as? String {
XCTAssert(number == "646 555-4567");
}
}
}
}
XCTAssert((((nsJSON as? NSDictionary)?.objectForKey("phoneNumbers") as? NSArray)?.objectAtIndex(1) as? NSDictionary)?.objectForKey("number") as? NSString == "646 555-4567");
XCTAssert((((nsJSON as? NSDictionary)?["phoneNumbers"] as? NSArray)?[1] as? NSDictionary)?["number"] as? NSString == "646 555-4567");
XCTAssert(JSON(nsJSON)?[key:"phoneNumbers"]?[index:1]?[key:"number"] as? NSString == "646 555-4567")
}
}
| mit | 668ee824669781da3df477a43e8db711 | 35.573034 | 181 | 0.573272 | 4.109848 | false | true | false | false |
Boerworz/Gagat | GagatObjectiveC/Gagat.swift | 1 | 5183 | //
// GagatObjectiveC.swift
// Gagat
//
// Created by Tim Andersson on 2017-06-12.
// Copyright © 2017 Cocoabeans Software. All rights reserved.
//
//
// +---------------------------------------------------------------------------------+
// | This file contains an Objective-C bridge for Gagat. It is the only component of |
// | the GagatObjectiveC target and has a dependency on the original Gagat target. |
// +---------------------------------------------------------------------------------+
//
import Foundation
import Gagat
/// A type that knows how to toggle between two alternative visual styles.
@objc public protocol GGTStyleable {
/// Activates the alternative style that is currently not active.
///
/// This method is called by Gagat at the start of a transition
/// and at the end of a _cancelled_ transition (to revert to the
/// previous style).
@objc func toggleActiveStyle()
/// Called when the style transition is about to begin. `toggleActiveStyle()` will be called just after this.
@objc optional func styleTransitionWillBegin()
/// Called when the style transition ended.
@objc optional func styleTransitionDidEnd()
}
/// The `GGTConfiguration` class allows clients to configure certain
/// aspects of the transition.
///
/// Initialize an empty instance of the class to use the defaults.
public class GGTConfiguration: NSObject {
/// Controls how much the border between the new and
/// previous style is deformed when panning. The larger the
/// factor is, the more the border is deformed.
/// Specify a factor of 0 to entirely disable the deformation.
///
/// Defaults to 1.0.
@objc public let jellyFactor: Double
@objc public init(jellyFactor: Double = 1.0) {
self.jellyFactor = jellyFactor
}
fileprivate var toSwiftRepresentation: Gagat.Configuration {
return Gagat.Configuration(jellyFactor: jellyFactor)
}
}
/// Represents a configured transition and allows clients to
/// access properties that can be modified after configuration.
public class GGTTransitionHandle: NSObject {
private let wrappedHandle: Gagat.TransitionHandle
fileprivate init(byWrapping handle: Gagat.TransitionHandle) {
wrappedHandle = handle
}
/// The pan gesture recognizer that Gagat uses to trigger and drive the
/// transition.
///
/// You may use this property to configure the minimum or maximum number
/// of required touches if you don't want to use the default two-finger
/// pan. You may also use it to setup dependencies between this gesture
/// recognizer and any other gesture recognizers in your application.
///
/// - important: You *must not* change the gesture recognizer's delegate
/// or remove targets not added by the client.
@objc public var panGestureRecognizer: UIPanGestureRecognizer {
return wrappedHandle.panGestureRecognizer
}
}
public class GGTManager: NSObject {
/// Configures everything that's needed by Gagat to begin handling the transition
/// in the specified window.
///
/// - important: You *must* keep a reference to the `GGTTransitionHandle`
/// returned by this method even if you don't intend to access
/// any of its properties.
/// All Gagat-related objects will be torn down when the
/// handle is deallocated, and the client will need to call
/// `-[GGTManager configureForWindow:withStyleableObject:usingConfiguration:]`
/// again to re-enable the Gagat transition.
///
/// - note: This method shouldn't be called multiple times for the same window
/// unless the returned handle has been deallocated.
///
/// - parameter window: The window that the user will pan in to trigger the
/// transition.
/// - parameter styleableObject: An object that conforms to `GGTStyleable` and
/// which is responsible for toggling to the alternative style when
/// the transition is triggered or cancelled.
/// - parameter configuration: The configuration to use for the transition.
///
/// - returns: A new instance of `GGTTransitionHandle`.
@objc public class func configure(forWindow window: UIWindow, withStyleableObject styleableObject: GGTStyleable, usingConfiguration configuration: GGTConfiguration = GGTConfiguration()) -> GGTTransitionHandle {
let styleableObjectProxy = GagatStyleableSwiftToObjCProxy(target: styleableObject)
let handle = Gagat.configure(for: window, with: styleableObjectProxy, using: configuration.toSwiftRepresentation)
return GGTTransitionHandle(byWrapping: handle)
}
}
/// `GagatStyleableSwiftToObjCProxy` is used internally to bridge the Swift-only
/// `GagatStyleable` type to the `GGTStyleable` type.
private struct GagatStyleableSwiftToObjCProxy: GagatStyleable {
private let target: GGTStyleable
init(target: GGTStyleable) {
self.target = target
}
func toggleActiveStyle() {
target.toggleActiveStyle()
}
func styleTransitionWillBegin() {
if let targetImplementation = target.styleTransitionWillBegin {
targetImplementation()
}
}
func styleTransitionDidEnd() {
if let targetImplementation = target.styleTransitionDidEnd {
targetImplementation()
}
}
}
| mit | 183bd41f5abcb93d95eb123988256e64 | 36.824818 | 211 | 0.709379 | 4.303987 | false | true | false | false |
zyhndesign/SDX_DG | sdxdg/sdxdg/HotMatchCell.swift | 1 | 2496 | //
// HotMatchCell.swift
// sdxdg
//
// Created by lotusprize on 17/1/10.
// Copyright © 2017年 geekTeam. All rights reserved.
//
import UIKit
class HotMatchCell : UICollectionViewCell {
let width = UIScreen.main.bounds.size.width//获取屏幕宽
let height = UIScreen.main.bounds.size.height
var imgView:UIImageView?
var redHeartIcon:UIImageView?
var heartCount:UITextView?
var fitBtn:UIButton?
override init(frame: CGRect) {
super.init(frame: frame)
imgView = UIImageView.init(frame: CGRect.init(x: 10, y: 10, width: (width-80)/2, height: (height - 30)/2))
imgView?.contentMode = UIViewContentMode.scaleAspectFit
self.addSubview(imgView!)
redHeartIcon = UIImageView.init(frame: CGRect.init(x: ((width-40)/2 - 35), y: 25, width: 10, height: 10))
redHeartIcon?.image = UIImage.init(named: "like")
self.addSubview(redHeartIcon!)
heartCount = UITextView.init(frame: CGRect.init(x: ((width-40)/2 - 25), y: 15, width: 30, height: 20))
heartCount?.font = UIFont.systemFont(ofSize: 10)
heartCount?.textColor = UIColor.darkGray
self.addSubview(heartCount!)
fitBtn = UIButton.init(frame: CGRect.init(x: 0, y: (height - 30)/2 + 5, width: (width-30)/2, height: 36))
fitBtn?.backgroundColor = UIColor.init(red: 253/255.0, green: 220/255.0, blue: 56/255.0, alpha: 1.0)
let btnIconLayer:CALayer = CALayer()
btnIconLayer.contents = UIImage.init(named: "fitIcon")?.cgImage
btnIconLayer.frame = CGRect.init(x: ((width-30)/2 - 30)/2 - 25, y: 8, width: 20, height: 18)
fitBtn?.layer.addSublayer(btnIconLayer)
let btnTextLayer:CATextLayer = CATextLayer.init()
btnTextLayer.string = "试穿"
btnTextLayer.fontSize = 15
btnTextLayer.foregroundColor = UIColor.darkGray.cgColor
btnTextLayer.frame = CGRect.init(x: ((width-30)/2 - 30)/2 + 5, y: 8, width: 30, height: 17)
fitBtn?.layer.addSublayer(btnTextLayer)
self.addSubview(fitBtn!)
self.backgroundColor = UIColor.white
}
func initImageView(imgView:String, heartCount:Int){
self.imgView?.af_setImage(withURL: URL.init(string: imgView)!)
self.heartCount?.text = String(stringInterpolationSegment:heartCount)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| apache-2.0 | 3c04ef28d65827c8f5b3ef486f5eb38b | 38.349206 | 114 | 0.639774 | 3.773212 | false | false | false | false |
abarisain/skugga | Apple/iOS/Skugga/RemoteFileDatabaseHelper.swift | 1 | 3711 | //
// RemoteFileDatabaseHelper.swift
// Skugga
//
// Created by arnaud on 14/02/2015.
// Copyright (c) 2015 NamelessDev. All rights reserved.
//
import Foundation
import CoreData
import UpdAPI
/*!
Notification that this helper will emit once the files have changed
*/
let RemoteFilesChangedNotification = "RemoteFilesChanged"
let RemoteFilesRefreshFailureNotification = "RemoteFilesFailedToRefresh"
struct RemoteFileDatabaseHelper
{
static func refreshFromServer()
{
FileListClient(configuration: Configuration.updApiConfiguration).getFileList(saveFilesToDB, failure: { (error: NSError) -> () in
NSLog("Error while refreshing files from server \(error), cause : \(error.userInfo)")
NotificationCenter.default.post(name: Notification.Name(rawValue: RemoteFilesChangedNotification), object: nil)
})
}
static var cachedFiles: [RemoteFile]
{
get
{
let (fetchedResults, error) = readFilesFromDB()
if let results = fetchedResults
{
return results.map({RemoteFile(fromNSManagedObject: $0)}).sorted(by: {$0.uploadDate > $1.uploadDate})
}
else
{
NSLog("Could not get cached files \(error), cause : \(error!.userInfo)")
return [RemoteFile]()
}
}
}
fileprivate static func readFilesFromDB() -> ([NSManagedObject]?, NSError?)
{
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let managedContext = appDelegate.managedObjectContext!
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName:"RemoteFile")
do {
let fetchedResults = try managedContext.fetch(fetchRequest) as? [NSManagedObject]
return (fetchedResults, nil)
} catch let error as NSError {
return (nil, error)
}
}
fileprivate static func truncateFilesDB()
{
let (fetchedResults, error) = readFilesFromDB()
if let results = fetchedResults
{
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let managedContext = appDelegate.managedObjectContext!
for result in results
{
managedContext.delete(result)
}
do {
try managedContext.save()
} catch let saveError as NSError {
NSLog("Could not truncate cached files \(saveError), cause : \(saveError.userInfo)")
}
}
else
{
NSLog("Could not truncate cached files \(error), cause : \(error!.userInfo)")
}
}
fileprivate static func saveFilesToDB(_ files: [RemoteFile])
{
DispatchQueue.main.async {
truncateFilesDB()
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let managedContext = appDelegate.managedObjectContext!
let entity = NSEntityDescription.entity(forEntityName: "RemoteFile", in: managedContext)
for file in files
{
let _ = file.toNSManagedObject(managedContext, entity: entity!)
}
do {
try managedContext.save()
} catch let error as NSError {
NSLog("Could not save remote files \(error), cause : \(error.userInfo)")
}
NotificationCenter.default.post(name: Notification.Name(rawValue: RemoteFilesChangedNotification), object: nil)
}
}
}
| apache-2.0 | 5efeda87e5cf04b9adb4b5090000b6c1 | 31.552632 | 136 | 0.585018 | 5.378261 | false | false | false | false |
xremix/SwiftGS1Barcode | SwiftGS1Barcode/GS1ApplicationIdentifier.swift | 1 | 5647 | //
// GS1ApplicationIdentifier.swift
// SwiftGS1Barcode
//
// Created by Toni Hoffmann on 26.06.17.
// Copyright © 2017 Toni Hoffmann. All rights reserved.
//
import Foundation
public enum GS1ApplicationIdentifierType: String{
case AlphaNumeric
case Numeric
case NumericDouble
case Date
var description: String{
return self.rawValue
}
}
public class GS1ApplicationIdentifier: NSObject{
/** Barcode Parser will search for this identifier and will */
public var identifier: String
/** Maximum length. The value can be smaller if there are not enough characters available or if dynamic length is active (and a GS character is available) */
public var maxLength: Int
/** Seperates by the next GS-character */
public var dynamicLength: Bool = false
public var type: GS1ApplicationIdentifierType?
/** The original data from the AI. This will always been set to the content that was trying to be parsed. If Date / Int parsing failed it will still pout the content in there */
public var rawValue: String?
/** This will be set by the Barcode parser, if type is Date */
public var dateValue: Date?
/** This will be set by the Barcode parser, if type is Numeric */
public var intValue: Int?
/** This will be set by the Barcode parser, if type is NumericDouble */
public var doubleValue: Double?
/** This will be set by the Barcode parser, if type is AlphaNumeric */
public var stringValue: String?
public var decimalPlaces: Int?
/** Initiates a GS1 AI with a maximum length */
public init(_ identifier: String, length: Int){
self.identifier = identifier
self.maxLength = length
}
/** Initiates a GS1 AI with a maximum length and a type */
public convenience init(_ identifier: String, length: Int, type: GS1ApplicationIdentifierType){
self.init(identifier, length: length)
self.type = type
}
/** Initiates a GS1 AI with a maximum length and dynamic length and a type. The dynamic length is always stronger than the maximum length */
public convenience init(_ identifier: String, length: Int, type: GS1ApplicationIdentifierType, dynamicLength: Bool){
self.init(identifier, length: length, type: type)
self.dynamicLength = dynamicLength
}
/** Initiates a GS1 AI of type date */
public convenience init(dateIdentifier identifier: String){
// Defaults the max length to 6 and sets default type to Date
self.init(identifier, length: 6, type: .Date)
}
public var readableValue: String{
get{
if self.type == GS1ApplicationIdentifierType.AlphaNumeric{
return self.stringValue ?? ""
}
if self.type == GS1ApplicationIdentifierType.NumericDouble{
if self.doubleValue == nil {
return ""
}
return String(self.doubleValue!)
}
if self.type == GS1ApplicationIdentifierType.Numeric{
if self.intValue == nil {
return ""
}
return String(self.intValue!)
}
if self.type == GS1ApplicationIdentifierType.Date{
if self.dateValue == nil {
return ""
}
let formatter = DateFormatter()
formatter.dateStyle = .short
return formatter.string(for: self.dateValue!)!
}
return self.rawValue ?? ""
}
}
// Think about moving this logic to GS1 Barcode
/** Get a readable english string to display in the user interface */
public var readableIdentifier: String{
get{
if identifier == "00" { return "Serial Shipping Container Code" }
else if identifier == "01" { return "GTIN" }
else if identifier == "02" { return "GTIN of contained Trade Items" }
else if identifier == "10" { return "Lot Number" }
else if identifier == "11" { return "Production Date" }
else if identifier == "12" { return "Due Date" }
else if identifier == "13" { return "Packaging Date" }
else if identifier == "15" { return "Best Before Date" }
else if identifier == "17" { return "Expiration Date" }
else if identifier == "20" { return "Product Variant" }
else if identifier == "21" { return "Serial Number" }
else if identifier == "22" { return "Secondary Data Fields" }
else if identifier == "30" { return "Count of Items" }
else if identifier == "37" { return "Number of Units Contained" }
else if identifier == "310" { return "Product Weight in KG" }
else if identifier == "23n" { return "Lot Number of N" }
else if identifier == "240" { return "Additional Product Identification" }
else if identifier == "241" { return "Customer Part Number" }
else if identifier == "242" { return "Made to Order Variation Number" }
else if identifier == "250" { return "Secondary Serial Number" }
else if identifier == "251" { return "Reference to Source Entity" }
else if identifier == "392" { return "Price - Single Monetary Area" }
else if identifier == "393" { return "Price and ISO" }
else if identifier == "395" { return "Price per UOM" }
else if identifier == "422" { return "Country of Origin" }
else { return identifier }
}
}
}
| mit | 90283c3384d41ba6e9d84bd3061e7ef1 | 42.767442 | 181 | 0.606624 | 4.732607 | false | false | false | false |
zachgrayio/RxSwiftWebSocketExample | RxSwiftWebSocketExample/ViewController.swift | 1 | 3104 | //
// ViewController.swift
// RxSwiftWebSocketExample
//
// Created by Zachary Gray on 11/16/15.
// Copyright © 2015 Zachary Gray. All rights reserved.
//
import UIKit
import SwiftWebSocket
import RxCocoa
import RxSwift
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let ws = WebSocket()
// subscribe to trace signal and print messages
_ = ws.rx_trace
.takeUntil(self.rx_deallocated)
.subscribeNext { (element:TraceElement) in
print("[TRACE]: \(element.eventName)\(element.message)(\(element.id.UUIDString))")
}
// subscribe to open
let openSubscription = ws.rx_event.open
.takeUntil(self.rx_deallocated)
.subscribeNext { print("[socket example] > OPEN") }
// subscribe to close
let closeSubscription = ws.rx_event.close
.takeUntil(self.rx_deallocated)
.subscribeNext { (closeEvent:SocketCloseEvent) in
print("[socket example] > CLOSE | code:\(closeEvent.code), reason:\(closeEvent.reason)")
}
// subscribe to error
let errorSubscription = ws.rx_event.error
.takeUntil(self.rx_deallocated)
.subscribeNext { error in
print("[socket example] > ERROR | error: \(error)")
}
let endSubscription = ws.rx_event.end
.takeUntil(self.rx_deallocated)
.subscribeNext { endEvent in
print("[socket example] > END | reason: \(endEvent.reason), error: \(endEvent.error)")
}
let messageSubscription = ws.rx_event.message
.takeUntil(self.rx_deallocated)
.subscribeNext { message in
print("[socket example] > MESSAGE: \(message)")
}
// define a message variable, with one element "hello" which will be dispatched to subscribers immediately upon
// subscription
let message = Variable<String>("hello")
// open a bad url:
ws.open("wz://echo.websocket.org")
// open a working url:
delay(3) {
ws.close()
ws.open("ws://echo.websocket.org")
// bind the message variable to the send sink, resulting in an immediate send (and receive from echo server)
// of "hello", followed by "world" after a second
_ = ws.rx_send <- message
delay(1) { message.value = "world" }
}
// then close it:
delay(10) {
ws.close()
}
delay(20) {
openSubscription.dispose()
closeSubscription.dispose()
errorSubscription.dispose()
endSubscription.dispose()
messageSubscription.dispose()
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| mit | 08652944ba5d8a4e9f91c26266d661f8 | 30.663265 | 120 | 0.555269 | 4.917591 | false | false | false | false |
jonathan-stone/slidingmessage | slidingmessageTests/LabelWithAutowrapTests.swift | 1 | 812 | //
// LabelWithAutowrapTests.swift
// slidingmessage
//
// Created by Jonathan Stone on 9/15/17.
// Copyright © 2017 CompassionApps. All rights reserved.
//
import XCTest
@testable import slidingmessage
class LabelWithAutowrapTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
let newLabel = LabelWithAutoWrap()
let testText = "Test label text"
newLabel.text = testText
XCTAssertTrue(newLabel.text == testText)
}
}
| mit | bef5409e35835a3b0365c9a8f7cfd82d | 25.16129 | 111 | 0.654747 | 4.336898 | false | true | false | false |
RxSwiftCommunity/RxSwiftExt | Source/RxSwift/bufferWithTrigger.swift | 2 | 1673 | //
// bufferWithTrigger.swift
// RxSwiftExt
//
// Created by Patrick Maltagliati on 11/12/18.
// Copyright © 2018 RxSwift Community. All rights reserved.
//
import Foundation
import RxSwift
extension ObservableType {
/**
Collects the elements of the source observable, and emits them as an array when the trigger emits.
- parameter trigger: The observable sequence used to signal the emission of the buffered items.
- returns: The buffered observable from elements of the source sequence.
*/
public func bufferWithTrigger<Trigger: ObservableType>(_ trigger: Trigger) -> Observable<[Element]> {
return Observable.create { observer in
var buffer: [Element] = []
let lock = NSRecursiveLock()
let triggerDisposable = trigger.subscribe { event in
lock.lock(); defer { lock.unlock() }
switch event {
case .next:
observer.onNext(buffer)
buffer = []
default:
break
}
}
let disposable = self.subscribe { event in
lock.lock(); defer { lock.unlock() }
switch event {
case .next(let element):
buffer.append(element)
case .completed:
observer.onNext(buffer)
observer.onCompleted()
case .error(let error):
observer.onError(error)
buffer = []
}
}
return Disposables.create([disposable, triggerDisposable])
}
}
}
| mit | 4da3086f0956c8fc453b1535dc47519e | 33.122449 | 105 | 0.540072 | 5.376206 | false | false | false | false |
Pyroh/Fluor | Fluor/Models/AppManager.swift | 1 | 8018 | //
// AppManager.swift
//
// Fluor
//
// MIT License
//
// Copyright (c) 2020 Pierre Tacchi
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
import Cocoa
import DefaultsWrapper
extension UserDefaultsKeyName {
static let userHasAlreadyAnsweredAccessibility: UserDefaultsKeyName = "HasAlreadyRefusedAccessibility"
static let keyboardMode: UserDefaultsKeyName = "DefaultKeyboardMode"
static let appRules: UserDefaultsKeyName = "AppRules"
static let restoreStateOnQuit: UserDefaultsKeyName = "ResetModeOnQuit"
static let restoreStateAsBeforeStartup: UserDefaultsKeyName = "SameStateAsBeforeStartup"
static let onQuitState: UserDefaultsKeyName = "OnQuitState"
static let disabledOnLunch: UserDefaultsKeyName = "OnLaunchDisabled"
static let switchMethod: UserDefaultsKeyName = "DefaultSwitchMethod"
static let useLightIcon: UserDefaultsKeyName = "UseLightIcon"
static let showAllRunningProcesses: UserDefaultsKeyName = "ShowAllProcesses"
static let fnKeyMaximumDelay: UserDefaultsKeyName = "FNKeyReleaseMaximumDelay"
static let lastRunVersion: UserDefaultsKeyName = "LastRunVersion"
static let hideSwitchMethod: UserDefaultsKeyName = "HideSwitchMethod"
static let sendFnKeyNotification: UserDefaultsKeyName = "sendFnKeyNotification"
static let hideNotificationAuthorizationPopup: UserDefaultsKeyName = "hideNotificationAuthorizationPopup"
static let userNotificationEnablement: UserDefaultsKeyName = "userNotificationEnablement"
static let sendLegacyUserNotifications: UserDefaultsKeyName = "sendLegacyUserNotification"
}
/// This class holds all per-application keyboard behaviors.
/// It also takes care of NSUserDefaults reading and synchronizing.
class AppManager: BehaviorDidChangePoster {
/// The defaut behavior manager.
static let `default`: AppManager = AppManager()
@Defaults(key: .keyboardMode, defaultValue: .media)
var defaultFKeyMode: FKeyMode
@Defaults(key: .switchMethod, defaultValue: .window)
var switchMethod: SwitchMethod
@Defaults(key: .hideSwitchMethod, defaultValue: false)
var hideSwitchMethod: Bool
@Defaults(key: .lastRunVersion, defaultValue: "unknown")
var lastRunVersion: String
@Defaults(key: .restoreStateOnQuit, defaultValue: false)
var shouldRestoreStateOnQuit: Bool
@Defaults(key: .restoreStateAsBeforeStartup, defaultValue: false)
var shouldRestorePreviousState: Bool
@Defaults(key: .onQuitState, defaultValue: .media)
var onQuitState: FKeyMode
@Defaults(key: .disabledOnLunch, defaultValue: false)
var isDisabled: Bool
@Defaults(key: .useLightIcon, defaultValue: false)
var useLightIcon: Bool
@Defaults(key: .showAllRunningProcesses, defaultValue: false)
var showAllRunningProcesses: Bool
@Defaults(key: .userHasAlreadyAnsweredAccessibility, defaultValue: false)
var hasAlreadyAnsweredAccessibility: Bool
@Defaults(key: .fnKeyMaximumDelay, defaultValue: 280)
var fnKeyMaximumDelay: TimeInterval
@Defaults(key: .hideNotificationAuthorizationPopup, defaultValue: false)
var hideNotificationAuthorizationPopup: Bool
@Defaults(key: .sendFnKeyNotification, defaultValue: true)
var sendFnKeyNotification: Bool
@Defaults(key: .userNotificationEnablement, defaultValue: .none)
var userNotificationEnablement: UserNotificationEnablement
@Defaults(key: .sendLegacyUserNotifications, defaultValue: false)
var sendLegacyUserNotifications: Bool
private(set) var rules: Set<Rule> = []
private var behaviorDict: [String: AppBehavior] = [:]
private let defaults = UserDefaults.standard
private init() {
self.loadRules()
}
func propagate(behavior: AppBehavior, forApp id: String, at url: URL, from source: NotificationSource) {
guard self.behaviorDict[id] != behavior else { return }
self.setBehaviorForApp(id: id, behavior: behavior, url: url)
self.postBehaviorDidChangeNotification(id: id, url: url, behavior: behavior, source: source)
}
/// Return the behavior for the given application.
///
/// - parameter id: The application's bundle id.
///
/// - returns: The behavior for the application.
func behaviorForApp(id: String) -> AppBehavior {
return behaviorDict[id] ?? .inferred
}
/// Change the application of the given bundle id and bundle url.
///
/// - parameter id: The application's bundle id.
/// - parameter behavior: The new application's behavior.
/// - parameter url: The application's bundle url.
func setBehaviorForApp(id: String, behavior: AppBehavior, url: URL) {
var change = false
if behavior == .inferred {
self.behaviorDict.removeValue(forKey: id)
guard let index = self.rules.firstIndex(where: { $0.url == url }) else { fatalError() }
self.rules.remove(at: index)
change = true
} else if let previousBehavior = self.behaviorDict[id] {
if previousBehavior != behavior {
self.behaviorDict[id] = behavior
guard let rule = self.rules.first(where: { $0.url == url }) else { fatalError() }
rule.behavior = behavior
change = true
}
} else {
behaviorDict[id] = behavior
self.rules.insert(.init(id: id, url: url, behavior: behavior))
change = true
}
if change { synchronizeRules() }
}
/// Get the function key state according to globals preferences.
///
/// - returns: The current keyboard state.
func getCurrentFKeyMode() -> FKeyMode {
FKeyManager.getCurrentFKeyMode().getOrFailWith { (error) -> Never in
AppErrorManager.terminateApp(withReason: error.localizedDescription)
}
}
/// Return the keyboard state for the given behavior based on the actual keyboard state.
///
/// - parameter behavior: The behavior.
///
/// - returns: The keyboard state.
func keyboardStateFor(behavior: AppBehavior) -> FKeyMode {
switch behavior {
case .inferred:
return self.defaultFKeyMode
case .media:
return .media
case .function:
return .function
}
}
/// Load the defaults.
private func loadRules() {
if let rules: Set<Rule> = self.defaults.convertible(forKey: UserDefaultsKeyName.appRules.rawValue) {
self.rules = rules
self.behaviorDict = .init(uniqueKeysWithValues: rules.map { ($0.id, $0.behavior) })
}
}
/// Synchronize and write the defaults from altered data held by this `BehaviorManager` instance.
private func synchronizeRules() {
self.defaults.set(self.rules, forKey: UserDefaultsKeyName.appRules.rawValue)
}
}
| mit | 3c72d07e3d964abeb56ace246ef0279a | 39.494949 | 109 | 0.695311 | 4.634682 | false | false | false | false |
almapp/uc-access-ios | uc-access/AppDelegate.swift | 1 | 7927 | //
// AppDelegate.swift
// uc-access
//
// Created by Patricio Lopez on 08-01-16.
// Copyright © 2016 Almapp. All rights reserved.
//
import UIKit
import DZNWebViewController
import ChameleonFramework
enum UIUserInterfaceIdiom : Int {
case Unspecified
case Phone // iPhone and iPod touch style UI
case Pad // iPad style UI
}
extension AppDelegate: UISplitViewControllerDelegate {
func splitViewController(splitViewController: UISplitViewController, showDetailViewController vc: UIViewController, sender: AnyObject?) -> Bool {
if splitViewController.collapsed {
// Check if is cached
let cached = self.viewCache.filter({ $1 == vc }).count > 0
let title = cached ? "Ocultar" : "Cerrar"
// Present in a navigation controller
let navigation = UINavigationController(rootViewController: vc)
vc.navigationItem.leftBarButtonItem = UIBarButtonItem(title: title, style: .Plain, target: vc, action: Selector("dismiss"))
self.masterController!.presentViewController(navigation, animated: true, completion: nil)
} else {
// Replace content in right navigation controller
let navigation = splitViewController.viewControllers[1] as! UINavigationController
navigation.viewControllers = [vc]
}
// We handled it
return true
}
func targetDisplayModeForActionInSplitViewController(svc: UISplitViewController) -> UISplitViewControllerDisplayMode {
if svc.displayMode == .PrimaryOverlay || svc.displayMode == .PrimaryHidden {
return UISplitViewControllerDisplayMode.AllVisible
} else {
return UISplitViewControllerDisplayMode.PrimaryHidden
}
}
}
extension AppDelegate: WebPagePresenter {
func present(webpage: WebPage, withUser user: User? = nil) {
if let session = user, service = self.service(webpage, user: session) {
if let cached = self.getCachedView(service, user: session) {
self.presentDetail(cached)
} else {
UIApplication.sharedApplication().networkActivityIndicatorVisible = true
service.login()
.then { cookies -> Void in
let view = DetailViewController.init(service: service, configuration: BrowserHelper.setup(service))
self.setCachedView(service, user: session, view: view)
self.presentDetail(view)
}.error { error in
// This is not working
print(error)
}
}
} else {
// Normal webpage
self.presentDetail(DetailViewController.init(webpage: webpage))
}
}
func presentDetail(controller: UIViewController) {
controller.navigationItem.leftBarButtonItem = self.splitViewController!.displayModeButtonItem()
self.splitViewController!.showDetailViewController(controller, sender: self)
}
}
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
var splitViewController: UISplitViewController?
var masterController: UITabBarController?
var detailController: UINavigationController?
var users: [User] = []
var viewCache: [String: DetailViewController] = [:]
func setCachedView(service: Service, user: User?, view: DetailViewController) {
let key = self.hash(service, user: user)
self.viewCache[key] = view
}
func getCachedView(service: Service, user: User?) -> DetailViewController? {
let key = self.hash(service, user: user)
return self.viewCache[key]
}
func hash(service: Service, user: User?) -> String {
return "\(service.name)-\(user?.username)"
}
// Sugar getters
static var instance: AppDelegate {
get {
return UIApplication.sharedApplication().delegate as! AppDelegate
}
}
func service(webpage: WebPage, user: User) -> Service? {
if let id = webpage.id {
switch id {
case Siding.ID: return Siding(user: user.username, password: user.password)
case Labmat.ID: return Labmat(user: user.username, password: user.password)
case WebCursos.ID: return WebCursos(user: user.username, password: user.password)
case PortalUC.ID: return PortalUC(user: user.username, password: user.password)
default: return nil
}
}
return nil
}
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Setup data
self.users = User.loadAll()
// Setup views
let storyboard = UIStoryboard(name: "Main", bundle: nil)
self.window = UIWindow(frame: UIScreen.mainScreen().bounds) // Not root controller yet
// This is shared by both devices
self.masterController = storyboard.instantiateViewControllerWithIdentifier("Master") as? UITabBarController
// Setup SplitView as root view
self.splitViewController = UISplitViewController()
self.splitViewController!.preferredDisplayMode = .AllVisible
// Create the detail view
self.detailController = UINavigationController()
// Add views to split view controller
self.splitViewController?.viewControllers = [self.masterController!, self.detailController!]
// Delegate
self.splitViewController!.delegate = self
self.window?.rootViewController = self.splitViewController
// Present default detail
if self.splitViewController!.collapsed {
let initial = WebPage(id: nil, name: "", description: "", URL: "http://www.uc.cl", imageURL: "")
self.present(initial)
}
// Style
// let colors = ColorSchemeOf(ColorScheme.Analogous, color: FlatBrown(), isFlatScheme: true)
self.window!.tintColor = FlatYellowDark()
// UINavigationBar.appearance().backgroundColor = FlatSand()
// UIBarButtonItem.appearance().tintColor = FlatBrownDark()
// UITabBar.appearance().tintColor = FlatBrownDark()
// UISegmentedControl.appearance().tintColor = FlatBrown()
self.window!.makeKeyAndVisible()
return true
}
func applicationDidReceiveMemoryWarning(application: UIApplication) {
self.viewCache.removeAll()
}
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) {
User.save(self.users)
}
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:.
}
}
| gpl-3.0 | 2d6c3472462562bed9236b302e33c41d | 39.85567 | 285 | 0.661746 | 5.348178 | false | false | false | false |
nathawes/swift | test/decl/class/circular_inheritance.swift | 6 | 3116 | // RUN: rm -rf %t/stats-dir
// RUN: mkdir -p %t/stats-dir
// RUN: %target-typecheck-verify-swift
// RUN: not %target-swift-frontend -typecheck -debug-cycles %s -build-request-dependency-graph -output-request-graphviz %t.dot -stats-output-dir %t/stats-dir 2> %t.cycles
class Left // expected-error {{circular reference}} expected-note {{through reference here}}
: Right.Hand { // expected-note {{through reference here}}
class Hand {}
}
class Right // expected-note 2 {{through reference here}}
: Left.Hand { // expected-note {{through reference here}}
class Hand {}
}
class C : B { } // expected-error{{'C' inherits from itself}}
class B : A { } // expected-note{{class 'B' declared here}}
class A : C { } // expected-note{{class 'A' declared here}}
class TrivialCycle : TrivialCycle {} // expected-error{{'TrivialCycle' inherits from itself}}
protocol P : P {} // expected-error {{protocol 'P' refines itself}}
class Isomorphism : Automorphism { }
class Automorphism : Automorphism { } // expected-error{{'Automorphism' inherits from itself}}
// FIXME: Useless error
let _ = A() // expected-error{{'A' cannot be constructed because it has no accessible initializers}}
class Outer {
class Inner : Outer {}
}
class Outer2 // expected-error {{circular reference}} expected-note {{through reference here}}
: Outer2.Inner { // expected-note {{through reference here}}
class Inner {}
}
class Outer3 // expected-error {{circular reference}} expected-note {{through reference here}}
: Outer3.Inner<Int> { // expected-note {{through reference here}}
class Inner<T> {}
}
// CHECK: ===CYCLE DETECTED===
// CHECK-LABEL: `--{{.*}}HasCircularInheritanceRequest(circular_inheritance.(file).Left@
// CHECK-NEXT: `--{{.*}}SuperclassDeclRequest({{.*Left}}
// CHECK: `--{{.*}}InheritedDeclsReferencedRequest(circular_inheritance.(file).Left@
// CHECK: `--{{.*}}SuperclassDeclRequest
// CHECK: `--{{.*}}InheritedDeclsReferencedRequest(circular_inheritance.(file).Right@
// CHECK: `--{{.*}}SuperclassDeclRequest{{.*(cyclic dependency)}}
// CHECK-DOT: digraph Dependencies
// CHECK-DOT: label="InheritedTypeRequest
protocol Initable {
init()
// expected-note@-1 {{protocol requires initializer 'init()' with type '()'; do you want to add a stub?}}
// expected-note@-2 {{did you mean 'init'?}}
}
protocol Shape : Circle {}
class Circle : Initable & Circle {}
// expected-error@-1 {{'Circle' inherits from itself}}
// expected-error@-2 {{type 'Circle' does not conform to protocol 'Initable'}}
func crash() {
Circle()
// expected-error@-1 {{'Circle' cannot be constructed because it has no accessible initializers}}
}
// FIXME: We shouldn't emit the redundant "circular reference" diagnostics here.
class WithDesignatedInit : WithDesignatedInit {
// expected-error@-1 {{'WithDesignatedInit' inherits from itself}}
// expected-error@-2 {{circular reference}}
// expected-note@-3 {{through reference here}}
// expected-note@-4 2 {{through reference here}}
init(x: Int) {} // expected-error {{circular reference}}
}
| apache-2.0 | be9eb8ac0ce2c0321bd905077d0f7a9e | 37.95 | 170 | 0.678755 | 3.890137 | false | false | false | false |
lachatak/lift | ios/Lift/Device/MultiDeviceSession.swift | 5 | 6479 | import Foundation
///
/// Exposes information about a connected device
///
struct ConnectedDeviceInfo {
var deviceInfo: DeviceInfo
var deviceInfoDetail: DeviceInfo.Detail?
func withDeviceInfo(deviceInfo: DeviceInfo) -> ConnectedDeviceInfo {
return ConnectedDeviceInfo(deviceInfo: deviceInfo, deviceInfoDetail: deviceInfoDetail)
}
func withDeviceInfoDetail(deviceInfoDetail: DeviceInfo.Detail) -> ConnectedDeviceInfo {
return ConnectedDeviceInfo(deviceInfo: deviceInfo, deviceInfoDetail: deviceInfoDetail)
}
}
protocol MultiDeviceSessionDelegate {
func multiDeviceSession(session: MultiDeviceSession, encodingSensorDataGroup group: SensorDataGroup)
func multiDeviceSession(session: MultiDeviceSession, continuousSensorDataEncodedRange range: TimeRange)
}
///
/// Packs togehter multiple devices
///
class MultiDeviceSession : DeviceSession, DeviceSessionDelegate, DeviceDelegate, SensorDataGroupBufferDelegate {
// the stats are combined for all devices
private let combinedStats = DeviceSessionStats<DeviceSessionStatsTypes.KeyWithLocation>()
// our special deviceId is all 0s
private let multiDeviceId = DeviceId(UUIDString: "00000000-0000-0000-0000-000000000000")!
private var deviceInfos: [DeviceId : ConnectedDeviceInfo] = [:]
private var devices: [ConnectedDevice] = []
private var sensorDataGroupBuffer: SensorDataGroupBuffer!
private let deviceSessionDelegate: DeviceSessionDelegate!
private let deviceDelegate: DeviceDelegate!
private let delegate: MultiDeviceSessionDelegate!
required init(delegate: MultiDeviceSessionDelegate, deviceDelegate: DeviceDelegate, deviceSessionDelegate: DeviceSessionDelegate) {
// Multi device's ID is all zeros
self.deviceSessionDelegate = deviceSessionDelegate
self.deviceDelegate = deviceDelegate
self.delegate = delegate
super.init()
self.sensorDataGroupBuffer = SensorDataGroupBuffer(delegate: self, queue: dispatch_get_main_queue(), deviceLocations: { LiftUserDefaults.getLocation(deviceId: $0) })
for device in Devices.devices {
device.connect(self, deviceSessionDelegate: self, onDone: { d in self.devices += [d] })
}
}
///
/// Start all connected devices
///
func start() -> Void {
for d in devices { d.start() }
}
///
/// Get all device infos
///
func getDeviceInfo(index: Int) -> ConnectedDeviceInfo {
return deviceInfos.values.array[index]
}
///
/// Get all device infos
///
func getDeviceInfos() -> [ConnectedDeviceInfo] {
return deviceInfos.values.array
}
///
/// Get the session stats at the given index
///
func getSessionStats(index: Int) -> (DeviceSessionStatsTypes.KeyWithLocation, DeviceSessionStatsTypes.Entry) {
return combinedStats[index]
}
///
/// Gets all combined stats
///
func getSessionStats() -> [(DeviceSessionStatsTypes.KeyWithLocation, DeviceSessionStatsTypes.Entry)] {
return combinedStats.toList()
}
///
/// The connected device count
///
var deviceInfoCount: Int {
get {
return deviceInfos.count
}
}
///
/// The session stats count
///
var sessionStatsCount: Int {
get {
return combinedStats.count
}
}
///
/// Returns the currently held sensorDataGroup
///
var sensorDataGroup: SensorDataGroup {
get {
return sensorDataGroupBuffer.sensorDataGroup
}
}
override func stop() {
for d in devices { d.stop() }
sensorDataGroupBuffer.stop()
}
// MARK: DeviceDelegate implementation
func deviceAppLaunched(deviceId: DeviceId) {
deviceDelegate.deviceAppLaunched(deviceId)
}
func deviceAppLaunchFailed(deviceId: DeviceId, error: NSError) {
deviceDelegate.deviceAppLaunchFailed(deviceId, error: error)
}
func deviceDidNotConnect(error: NSError) {
deviceDelegate.deviceDidNotConnect(error)
}
func deviceDisconnected(deviceId: DeviceId) {
deviceDelegate.deviceDisconnected(deviceId)
}
func deviceGotDeviceInfo(deviceId: DeviceId, deviceInfo: DeviceInfo) {
deviceInfos.updated(deviceId, notFound: ConnectedDeviceInfo(deviceInfo: deviceInfo, deviceInfoDetail: nil)) {
$0.withDeviceInfo(deviceInfo)
}
deviceDelegate.deviceGotDeviceInfo(deviceId, deviceInfo: deviceInfo)
}
func deviceGotDeviceInfoDetail(deviceId: DeviceId, detail: DeviceInfo.Detail) {
deviceInfos.updated(deviceId) { $0.withDeviceInfoDetail(detail) }
deviceDelegate.deviceGotDeviceInfoDetail(deviceId, detail: detail)
}
// MARK: DeviceSessionDelegate implementation
func deviceSession(session: DeviceSession, sensorDataReceivedFrom deviceId: DeviceId, atDeviceTime time: CFAbsoluteTime, data: NSData) {
sensorDataGroupBuffer.decodeAndAdd(data, fromDeviceId: deviceId, maximumGap: 0.3, gapValue: 0)
combinedStats.merge(session.getStats()) { k in
let location = k.deviceId == ThisDevice.Info.id ? DeviceInfo.Location.Waist : DeviceInfo.Location.Wrist
return DeviceSessionStatsTypes.KeyWithLocation(sensorKind: k.sensorKind, deviceId: k.deviceId, location: location)
}
}
func deviceSession(deviceSession: DeviceSession, endedFrom deviceId: DeviceId) {
deviceInfos.removeValueForKey(deviceId)
deviceSessionDelegate.deviceSession(self, endedFrom: deviceId)
}
func deviceSession(deviceSession: DeviceSession, sensorDataNotReceivedFrom deviceId: DeviceId) {
// ???
}
// MARK: SensorDataGroupBufferDelegate implementation
func sensorDataGroupBuffer(buffer: SensorDataGroupBuffer, continuousSensorDataEncodedRange range: TimeRange, data: NSData) {
deviceSessionDelegate.deviceSession(self, sensorDataReceivedFrom: multiDeviceId, atDeviceTime: CFAbsoluteTimeGetCurrent(), data: data)
delegate.multiDeviceSession(self, continuousSensorDataEncodedRange: range)
}
func sensorDataGroupBuffer(buffer: SensorDataGroupBuffer, encodingSensorDataGroup group: SensorDataGroup) {
delegate.multiDeviceSession(self, encodingSensorDataGroup: group)
}
}
| apache-2.0 | 3842700f03c3be36a4688d113c581e83 | 34.021622 | 173 | 0.695015 | 4.953364 | false | false | false | false |
blockchain/My-Wallet-V3-iOS | Modules/Platform/Sources/PlatformUIKit/Components/AmountComponent/AmountLabelView/AmountLabelViewPresenter.swift | 1 | 5638 | // Copyright © Blockchain Luxembourg S.A. All rights reserved.
import PlatformKit
import RxCocoa
import RxRelay
import RxSwift
import ToolKit
/// A view model for `AmountLabelView` which is able to display a money amount with
/// an `valid` / `invalid` indication.
public final class AmountLabelViewPresenter {
// MARK: - Types
public enum CurrencyCodeSide {
case leading
case trailing
}
public struct Output {
fileprivate static var empty: Output {
Output(
amountLabelContent: .empty,
currencyCodeSide: .leading
)
}
public var string: NSAttributedString {
let string = NSMutableAttributedString()
switch currencyCodeSide {
case .leading:
string.append(NSAttributedString(amountLabelContent.currencyCode))
string.append(.space())
string.append(amountLabelContent.string)
return string
case .trailing:
string.append(amountLabelContent.string)
string.append(.space())
string.append(NSAttributedString(amountLabelContent.currencyCode))
return string
}
}
public var accessibility: Accessibility {
amountLabelContent.accessibility
}
let amountLabelContent: AmountLabelContent
let currencyCodeSide: CurrencyCodeSide
}
// MARK: - Properties
/// Streams the amount label content
var output: Driver<Output> {
outputRelay.asDriver()
}
public let outputRelay = BehaviorRelay<Output>(value: .empty)
/// The state of the component
public let inputRelay = BehaviorRelay<MoneyValueInputScanner.Input>(value: .empty)
public let focusRelay = BehaviorRelay<Bool>(value: false)
// MARK: - Injected
private let currencyCodeSide: CurrencyCodeSide
private let interactor: AmountLabelViewInteractor
private let disposeBag = DisposeBag()
public init(interactor: AmountLabelViewInteractor, currencyCodeSide: CurrencyCodeSide, isFocused: Bool = false) {
focusRelay.accept(isFocused)
self.interactor = interactor
self.currencyCodeSide = currencyCodeSide
Observable
.combineLatest(
interactor.currency,
inputRelay,
focusRelay
)
.map { currency, input, hasFocus in
AmountLabelContent(
input: input,
currencyCode: currency.displayCode,
currencySymbol: currency.displaySymbol,
hasFocus: hasFocus
)
}
.map { labelContent in
Output(
amountLabelContent: labelContent,
currencyCodeSide: currencyCodeSide
)
}
.bindAndCatch(to: outputRelay)
.disposed(by: disposeBag)
}
}
// MARK: - AmountLabelContent
extension AmountLabelViewPresenter {
// MARK: - Types
private typealias AccessibilityId = Accessibility.Identifier.AmountLabelView
struct AmountLabelContent {
// MARK: - Properties
fileprivate static var empty: AmountLabelContent {
.init(input: .empty, currencyCode: "", currencySymbol: "", hasFocus: false)
}
/// Returns the attributed string
var string: NSAttributedString {
let string = NSMutableAttributedString()
string.append(.init(amount))
if let placeholder = placeholder {
string.append(.init(placeholder))
}
return string
}
let accessibility: Accessibility
let amount: LabelContent
let currencyCode: LabelContent
let placeholder: LabelContent?
// MARK: - Setup
init(
input: MoneyValueInputScanner.Input,
currencyCode: String,
currencySymbol: String,
hasFocus: Bool
) {
var amount = ""
let formatter = NumberFormatter(
locale: Locale.current,
currencyCode: currencyCode,
maxFractionDigits: 0
)
let decimalSeparator = MoneyValueInputScanner.Constant.decimalSeparator
let amountComponents = input.amount.components(separatedBy: decimalSeparator)
if let firstComponent = amountComponents.first, let decimal = Decimal(string: firstComponent) {
amount += formatter.format(major: decimal, includeSymbol: false)
}
if amountComponents.count == 2 {
amount += "\(decimalSeparator)\(amountComponents[1])"
}
let font: UIFont = hasFocus ? .main(.medium, 48) : .main(.semibold, 14)
self.currencyCode = LabelContent(
text: currencySymbol,
font: font,
color: .titleText
)
self.amount = LabelContent(
text: amount,
font: font,
color: .titleText
)
accessibility = .init(
id: AccessibilityId.amountLabel,
label: amount
)
guard let padding = input.padding else {
placeholder = nil
return
}
placeholder = LabelContent(
text: padding,
font: font,
color: .mutedText
)
}
}
}
| lgpl-3.0 | a767161fe7a083e56e7a2a610a9574ef | 28.056701 | 117 | 0.568033 | 5.84751 | false | false | false | false |
huonw/swift | test/PrintAsObjC/enums.swift | 2 | 5256 | // RUN: %empty-directory(%t)
// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -enable-source-import -emit-module -emit-module-doc -o %t %s -import-objc-header %S/Inputs/enums.h -disable-objc-attr-requires-foundation-module
// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -parse-as-library %t/enums.swiftmodule -typecheck -emit-objc-header-path %t/enums.h -import-objc-header %S/Inputs/enums.h -disable-objc-attr-requires-foundation-module
// RUN: %FileCheck %s < %t/enums.h
// RUN: %FileCheck -check-prefix=NEGATIVE %s < %t/enums.h
// RUN: %check-in-clang %t/enums.h
// RUN: %check-in-clang -fno-modules -Qunused-arguments %t/enums.h -include Foundation.h -include ctypes.h -include CoreFoundation.h
// REQUIRES: objc_interop
import Foundation
// NEGATIVE-NOT: NSMalformedEnumMissingTypedef :
// NEGATIVE-NOT: enum EnumNamed
// CHECK-LABEL: enum FooComments : NSInteger;
// CHECK-LABEL: enum NegativeValues : int16_t;
// CHECK-LABEL: enum ObjcEnumNamed : NSInteger;
// CHECK-LABEL: @interface AnEnumMethod
// CHECK-NEXT: - (enum NegativeValues)takeAndReturnEnum:(enum FooComments)foo SWIFT_WARN_UNUSED_RESULT;
// CHECK-NEXT: - (void)acceptPlainEnum:(enum NSMalformedEnumMissingTypedef)_;
// CHECK-NEXT: - (enum ObjcEnumNamed)takeAndReturnRenamedEnum:(enum ObjcEnumNamed)foo SWIFT_WARN_UNUSED_RESULT;
// CHECK-NEXT: - (void)acceptTopLevelImportedWithA:(enum TopLevelRaw)a b:(TopLevelEnum)b c:(TopLevelOptions)c d:(TopLevelTypedef)d e:(TopLevelAnon)e;
// CHECK-NEXT: - (void)acceptMemberImportedWithA:(enum MemberRaw)a b:(enum MemberEnum)b c:(MemberOptions)c d:(enum MemberTypedef)d e:(MemberAnon)e ee:(MemberAnon2)ee;
// CHECK: @end
@objc class AnEnumMethod {
@objc func takeAndReturnEnum(_ foo: FooComments) -> NegativeValues {
return .Zung
}
@objc func acceptPlainEnum(_: NSMalformedEnumMissingTypedef) {}
@objc func takeAndReturnRenamedEnum(_ foo: EnumNamed) -> EnumNamed {
return .A
}
@objc func acceptTopLevelImported(a: TopLevelRaw, b: TopLevelEnum, c: TopLevelOptions, d: TopLevelTypedef, e: TopLevelAnon) {}
@objc func acceptMemberImported(a: Wrapper.Raw, b: Wrapper.Enum, c: Wrapper.Options, d: Wrapper.Typedef, e: Wrapper.Anon, ee: Wrapper.Anon2) {}
}
// CHECK-LABEL: typedef SWIFT_ENUM_NAMED(NSInteger, ObjcEnumNamed, "EnumNamed", closed) {
// CHECK-NEXT: ObjcEnumNamedA = 0,
// CHECK-NEXT: ObjcEnumNamedB = 1,
// CHECK-NEXT: ObjcEnumNamedC = 2,
// CHECK-NEXT: ObjcEnumNamedD = 3,
// CHECK-NEXT: ObjcEnumNamedHelloDolly = 4,
// CHECK-NEXT: };
@objc(ObjcEnumNamed) enum EnumNamed: Int {
case A, B, C, d, helloDolly
}
// CHECK-LABEL: typedef SWIFT_ENUM(NSInteger, EnumWithNamedConstants, closed) {
// CHECK-NEXT: kEnumA SWIFT_COMPILE_NAME("A") = 0,
// CHECK-NEXT: kEnumB SWIFT_COMPILE_NAME("B") = 1,
// CHECK-NEXT: kEnumC SWIFT_COMPILE_NAME("C") = 2,
// CHECK-NEXT: };
@objc enum EnumWithNamedConstants: Int {
@objc(kEnumA) case A
@objc(kEnumB) case B
@objc(kEnumC) case C
}
// CHECK-LABEL: typedef SWIFT_ENUM(unsigned int, ExplicitValues, closed) {
// CHECK-NEXT: ExplicitValuesZim = 0,
// CHECK-NEXT: ExplicitValuesZang = 219,
// CHECK-NEXT: ExplicitValuesZung = 220,
// CHECK-NEXT: };
// NEGATIVE-NOT: ExplicitValuesDomain
@objc enum ExplicitValues: CUnsignedInt {
case Zim, Zang = 219, Zung
func methodNotExportedToObjC() {}
}
// CHECK: /// Foo: A feer, a female feer.
// CHECK-NEXT: typedef SWIFT_ENUM(NSInteger, FooComments, closed) {
// CHECK: /// Zim: A zeer, a female zeer.
// CHECK-NEXT: FooCommentsZim = 0,
// CHECK-NEXT: FooCommentsZang = 1,
// CHECK-NEXT: FooCommentsZung = 2,
// CHECK-NEXT: };
/// Foo: A feer, a female feer.
@objc public enum FooComments: Int {
/// Zim: A zeer, a female zeer.
case Zim
case Zang, Zung
}
// CHECK-LABEL: typedef SWIFT_ENUM(int16_t, NegativeValues, closed) {
// CHECK-NEXT: Zang = -219,
// CHECK-NEXT: Zung = -218,
// CHECK-NEXT: };
@objc enum NegativeValues: Int16 {
case Zang = -219, Zung
func methodNotExportedToObjC() {}
}
// CHECK-LABEL: typedef SWIFT_ENUM(NSInteger, SomeError, closed) {
// CHECK-NEXT: SomeErrorBadness = 9001,
// CHECK-NEXT: SomeErrorWorseness = 9002,
// CHECK-NEXT: };
// CHECK-NEXT: static NSString * _Nonnull const SomeErrorDomain = @"enums.SomeError";
@objc enum SomeError: Int, Error {
case Badness = 9001
case Worseness
}
// CHECK-LABEL: typedef SWIFT_ENUM(NSInteger, SomeOtherError, closed) {
// CHECK-NEXT: SomeOtherErrorDomain = 0,
// CHECK-NEXT: };
// NEGATIVE-NOT: NSString * _Nonnull const SomeOtherErrorDomain
@objc enum SomeOtherError: Int, Error {
case Domain // collision!
}
// CHECK-LABEL: typedef SWIFT_ENUM_NAMED(NSInteger, ObjcErrorType, "SomeRenamedErrorType", closed) {
// CHECK-NEXT: ObjcErrorTypeBadStuff = 0,
// CHECK-NEXT: };
// CHECK-NEXT: static NSString * _Nonnull const ObjcErrorTypeDomain = @"enums.SomeRenamedErrorType";
@objc(ObjcErrorType) enum SomeRenamedErrorType: Int, Error {
case BadStuff
}
// CHECK-NOT: enum {{[A-Z]+}}
// CHECK-LABEL: @interface ZEnumMethod
// CHECK-NEXT: - (enum NegativeValues)takeAndReturnEnum:(enum FooComments)foo SWIFT_WARN_UNUSED_RESULT;
// CHECK: @end
@objc class ZEnumMethod {
@objc func takeAndReturnEnum(_ foo: FooComments) -> NegativeValues {
return .Zung
}
}
| apache-2.0 | 1933fe25aa133baaa6c124eb655b9fb0 | 37.933333 | 229 | 0.716895 | 3.232472 | false | false | false | false |
xivol/Swift-CS333 | playgrounds/swift/SwiftBasics.playground/Pages/Arrays.xcplaygroundpage/Contents.swift | 2 | 1877 | /*:
## Arrays
[Table of Contents](TableOfContents) · [Previous](@previous) · [Next](@next)
****
*/
var fibonachi: [Int] = [1,2,3,5,8]
while fibonachi.count < 20 {
fibonachi.append(fibonachi.last! + fibonachi[fibonachi.count-2])
}
fibonachi
fibonachi.insert(1, at: 0)
fibonachi.remove(at: 1)
//: ### Slicing Arrays
fibonachi[10...14]
fibonachi.prefix(upTo: 10)
fibonachi.suffix(from: 10)
//: ### Searching Arrays
fibonachi.index(of: 377)
fibonachi.index(where: {
elem in
return elem > 99 && elem < 1000
})
//: ### Spliting Arrays
fibonachi.split(separator: 89)
fibonachi.split(whereSeparator: {
$0 % 2 == 0
})
/*:
### Processing Arrays
Sequences and collections implement methods such as `map(_:)`, `filter(_:)`, and `reduce(_:_:)` to consume and transform their contents. You can compose these methods together to efficiently implement complex algorithms.
A collection's `filter(_:)` method returns an array containing only the elements that pass the provided test.
*/
fibonachi.filter({
elem in
elem % 2 == 0
})
var fibStrings = fibonachi.map({
"\( $0 )"
})
fibStrings.insert("?", at: 0)
//: The `map(_:)` method returns a new array by applying a `transform` to each element in a collection.
fibStrings.map({
Int($0)
})
//: The `flatMap(_:)` method works similar to `map(_:)` but the result contains only non-nil values.
fibStrings.flatMap({
Int($0)
})
//: `reduce(_:,_:)`
fibonachi[0...5].reduce(0, {
sum, elem in
sum + elem
})
fibonachi.reduce(0) {
$0 + $1
}
//: - Experiment: Every divider of first 20 fibonachi numbers.
var dividers: [Int:[Int]] = [:]
fibonachi.forEach {
fib in
if fib > 2 {
dividers[fib] = (2..<fib).filter {fib % $0 == 0}
} else {
dividers[fib] = []
}
}
dividers
//: ****
//: [Table of Contents](TableOfContents) · [Previous](@previous) · [Next](@next)
| mit | 8ecbbbe51d3c8ee747f5fcf7a44123af | 23.012821 | 221 | 0.636412 | 3.22931 | false | false | false | false |
Jnosh/swift | test/Migrator/tuple-arguments.swift | 2 | 1456 | // RUN: %target-swift-frontend -typecheck %s -swift-version 3
// RUN: %target-swift-frontend -typecheck -update-code -primary-file %s -emit-migrated-file-path %t.result -disable-migrator-fixits -swift-version 3
// RUN: diff -u %s.expected %t.result
// RUN: %target-swift-frontend -typecheck %s.expected -swift-version 4
func test1(_: ()) {}
test1(())
test1()
func test2() {}
test2()
enum Result<T> {
case success(T)
}
func test3(_: Result<()>) {}
test3(.success())
func test4(_: (Int, Int) -> ()) {}
test4({ (x,y) in })
func test5(_: (Int, Int, Int) -> ()) {}
test5({ (x,y,z) in })
func test6(_: ((Int, Int)) -> ()) {}
test6({ (x,y) in })
func test7(_: ((Int, Int, Int)) -> ()) {}
test7({ (x,y,z) in })
test6({ (_ x, _ y) in })
test6({ (_, _) in })
test6({ (x:Int, y:Int) in })
test6({ (_, _) ->() in })
func toString(indexes: Int?...) -> String {
let _ = indexes.enumerated().flatMap({ (i: Int, index: Int?) -> String? in
let _: Int = i
if index != nil {}
return ""
})
let _ = indexes.reduce(0) { print($0); return $0.0 + ($0.1 ?? 0)}
let _ = indexes.reduce(0) { (true ? $0 : (1, 2)).0 + ($0.1 ?? 0) }
let _ = [(1, 2)].contains { $0 != $1 }
_ = ["Hello", "Foo"].sorted { print($0); return $0.0.characters.count > ($0).1.characters.count }
_ = ["Hello" : 2].map { ($0, ($1)) }
}
extension Dictionary {
public mutating func merge(with dictionary: Dictionary) {
dictionary.forEach { updateValue($1, forKey: $0) }
}
}
| apache-2.0 | 12c59627ffa99862ade7bb6c9162f9e2 | 28.714286 | 148 | 0.555632 | 2.757576 | false | true | false | false |
shjborage/iOS-Guide | Swift/SwiftPlayground.playground/Pages/Have a try.xcplaygroundpage/Contents.swift | 1 | 2173 | //: [Previous](@previous)
import Foundation
var str = "Hello, playground"
//: [Next](@next)
do {
// var content = try String(contentsOfFile:"asdf")
var content = try String(contentsOfFile:"asdf", encoding:.utf8)
} catch {
print(error)
}
struct RegexHelper {
let regex: NSRegularExpression;
init(_ pattern: String) throws {
regex = try NSRegularExpression(pattern: pattern, options: .caseInsensitive)
}
func match(input: String) -> [NSTextCheckingResult] {
let matches = regex.matches(in: input, options: [], range: NSMakeRange(0, input.characters.count))
return matches
}
}
extension String {
func index(from: Int) -> Index {
return self.index(startIndex, offsetBy: from)
}
func substring(from: Int) -> String {
let fromIndex = index(from: from)
return substring(from: fromIndex)
}
func substring(to: Int) -> String {
let toIndex = index(from: to)
return substring(to: toIndex)
}
func substring(with r: Range<Int>) -> String {
let startIndex = index(from: r.lowerBound)
let endIndex = index(from: r.upperBound)
return substring(with: startIndex..<endIndex)
}
func trim() -> String {
return self.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
}
}
do {
let input = "<image>http://asdfsdf.baidu.com<image/>"
let regex = try NSRegularExpression(pattern: "<image>(http|ftp|https):\\/\\/[\\w\\-_]+(\\.[\\w\\-_]+)+([\\w\\-\\.,@?^=%&:/~\\+#]*[\\w\\-\\@?^=%&/~\\+#])?<image/>", options: .caseInsensitive)
let result = regex.matches(in: input, options: NSRegularExpression.MatchingOptions(rawValue: 0), range: NSMakeRange(0, input.characters.count))
if result.count > 0 {
for checkingRes in result {
print("Location:\(checkingRes.range.location), length:\(checkingRes.range.length)")
print(input.substring(with: checkingRes.range.location..<checkingRes.range.location+checkingRes.range.length))
}
}else{
print("未查找到")
}
} catch {
print(error)
}
" asdf \n\r ".trim() | mit | 32a3736df4605c607469c8e0540e1c1c | 28.671233 | 202 | 0.613857 | 3.900901 | false | false | false | false |
neekon/ios | Neekon/Neekon/EventCell.swift | 1 | 1510 | //
// EventCell.swift
// Neekon
//
// Created by Mohsen Azimi on 5/2/15.
// Copyright (c) 2015 Iranican Inc. All rights reserved.
//
import UIKit
import SnapKit
class EventCell: UITableViewCell {
var event: EventObject?
@IBOutlet weak var eventImage: UIImageView!
@IBOutlet weak var title: UILabel!
@IBOutlet weak var timeAndLocation: UILabel!
let startTimeFormatter = NSDateFormatter()
override func awakeFromNib() {
super.awakeFromNib()
backgroundColor = UIColor.clearColor()
startTimeFormatter.dateStyle = .NoStyle
startTimeFormatter.timeStyle = .ShortStyle
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
func updateEvent(event event_: EventObject) {
self.event = event_
println(event!)
title.text = event!.title!
// TODO guard against invalid URLs
eventImage.contentMode = .ScaleAspectFill
eventImage.clipsToBounds = true
eventImage.image = UIImage(data: NSData(contentsOfURL: NSURL(string: event!.image!)!)!)
let durationInHours = Int(event!.duration!) / 60;
let formattedStartTime = startTimeFormatter.stringFromDate(event!.startTime!)
timeAndLocation.text = "Starts at \(formattedStartTime) (\(durationInHours) hours)"
}
}
| mit | 8a127cf67a0d8638ad4e3c1c54dd66b2 | 25.964286 | 95 | 0.640397 | 4.870968 | false | false | false | false |
Turistforeningen/SjekkUT | ios/SjekkUt/views/controls/ShareButton.swift | 1 | 1361 | //
// ShareButton.swift
// SjekkUt
//
// Created by Henrik Hartz on 09/09/16.
// Copyright © 2016 Den Norske Turistforening. All rights reserved.
//
import Foundation
class ShareButton: DntTrackButton {
var checkin: Checkin? = nil
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override init(frame: CGRect) {
super.init(frame: frame)
}
convenience init(checkin aCheckin: Checkin) {
self.init(frame: CGRect(x: 0, y: 0, width: 44, height: 33))
checkin = aCheckin
addTarget(self, action: #selector(shareClicked), for: .touchUpInside)
trackingIdentifier = "Bruker trykket på del"
trackingParameters = ["checkinid": "\(aCheckin.identifier!)"]
}
@objc func shareClicked(_ sender: AnyObject) {
if checkin!.canShare, let currentController = DntNavigationController.current {
let activityView: UIActivityViewController = UIActivityViewController(activityItems: [(checkin?.url?.URL())!], applicationActivities: nil)
activityView.completionWithItemsHandler = { activity, success, items, error in
currentController.dismiss(animated: true, completion:nil)
}
currentController.present(activityView, animated: true, completion: nil)
}
}
}
| mit | 731a14dcb4aa9fab8381d415a0a8c5f8 | 30.604651 | 150 | 0.662252 | 4.412338 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.