repo_name
stringlengths 6
91
| ref
stringlengths 12
59
| path
stringlengths 7
936
| license
stringclasses 15
values | copies
stringlengths 1
3
| content
stringlengths 61
714k
| hash
stringlengths 32
32
| line_mean
float64 4.88
60.8
| line_max
int64 12
421
| alpha_frac
float64 0.1
0.92
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
theMatys/myWatch | refs/heads/master | myWatch/Source/Core/Device/MWDevice.swift | gpl-3.0 | 1 | //
// MWDevice.swift
// myWatch
//
// Created by Máté on 2017. 04. 12..
// Copyright © 2017. theMatys. All rights reserved.
//
import CoreBluetooth
/// Represents the myWatch device that the application uses.
///
/// Step/sleep data are held in this object as well as the given name, device ID and the peripheral repsresenting this device.
///
/// Encoded to a file when the app is about to terminate to presist data for the device.
@objc class MWDevice: NSObject, NSCoding
{
//MARK: Instance variables
/// The name of the device given by the user.
var name: String
/// The device's ID which is used to identify the device after first launch.
var identifier: String
/// The Bluetooth peripheral representing this device.
var peripheral: CBPeripheral?
//MARK: - Inherited initializers from: NSCoding
required convenience init?(coder aDecoder: NSCoder)
{
let name: String = aDecoder.decodeObject(forKey: PropertyKey.name) as? String ?? ""
let identifier: String = aDecoder.decodeObject(forKey: PropertyKey.identifier) as? String ?? ""
self.init(name: name, identifier: identifier)
}
//MARK: Initializers
/// Makes an `MWDevice` object.
///
/// Can be called programatically by any class or by `init(coder:)` to initialize.
///
/// - Parameters:
/// - name: The name of this device given by the user.
/// - identifier: The ID used to identify this device for later use.
/// - peripheral: The Bluetooth peripheral representing this device object.
///
/// - Returns: An `MWDevice` object.
init(name: String = "", identifier: String = "", peripheral: CBPeripheral? = nil)
{
self.name = name
self.identifier = identifier
self.peripheral = peripheral
}
//MARK: Inherited functions from: NSCoding
func encode(with aCoder: NSCoder)
{
aCoder.encode(name, forKey: PropertyKey.name)
aCoder.encode(identifier, forKey: PropertyKey.identifier)
}
//MARK: -
/// The structure which holds the property names used in the files to identify the properties of this object.
private struct PropertyKey
{
//MARK: Prefixes
/// The prefix of the property keys.
private static let prefix: String = "MWDevice"
//MARK: Property keys
static let name: String = prefix + "Name"
static let identifier: String = prefix + "Identifier"
}
}
| 20dffefcf80ade92a7dce61248ebd1fd | 31.487179 | 126 | 0.641673 | false | false | false | false |
guojiubo/PlainReader | refs/heads/master | PlainReader/StarredArticlesViewController.swift | mit | 1 | //
// PRStarredArticlesViewController.swift
// PlainReader
//
// Created by guo on 11/12/14.
// Copyright (c) 2014 guojiubo. All rights reserved.
//
import UIKit
class StarredArticlesViewController: PRPullToRefreshViewController, UITableViewDataSource, UITableViewDelegate {
@IBOutlet var tableView: UITableView!
var articles = PRDatabase.shared().starredArticles() as! [PRArticle]
override func viewDidLoad() {
super.viewDidLoad()
self.refreshHeader.title = "收藏"
let menuView = UIView(frame: CGRect(x: 0, y: 0, width: 60, height: 44))
let menuButton = PRAutoHamburgerButton(frame: CGRect(x: 0, y: 0, width: 30, height: 30))
menuButton.addTarget(self, action: #selector(StarredArticlesViewController.menuAction(_:)), for: .touchUpInside)
menuButton.center = menuView.center
menuView.addSubview(menuButton)
self.refreshHeader.leftView = menuView
let nc = NotificationCenter.default
nc.addObserver(self, selector: #selector(StarredArticlesViewController.handleStarActionNotification(_:)), name: NSNotification.Name.ArticleViewControllerStarred, object: nil)
}
func handleStarActionNotification(_ n: Notification) {
self.tableView.reloadData()
}
func menuAction(_ sender: PRAutoHamburgerButton) {
self.sideMenuViewController.presentLeftMenuViewController()
}
override func scrollView() -> UIScrollView! {
return self.tableView
}
override func useRefreshHeader() -> Bool {
return true
}
override func useLoadMoreFooter() -> Bool {
return false
}
override func refreshTriggered() {
super.refreshTriggered()
articles = PRDatabase.shared().starredArticles() as! [PRArticle]
self.tableView.reloadSections(IndexSet(integer: 0), with: .automatic)
DispatchQueue.main.async(execute: { [weak self] () -> Void in
if let weakSelf = self {
weakSelf.refreshCompleted()
}
})
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.articles.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cellIdentifier = "ArticleCell"
var cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier) as? PRArticleCell
if cell == nil {
cell = Bundle.main.loadNibNamed("PRArticleCell", owner: self, options: nil)?.first as? PRArticleCell
}
cell!.article = self.articles[(indexPath as NSIndexPath).row]
return cell!
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
let article = self.articles[(indexPath as NSIndexPath).row]
let vc = PRArticleViewController.cw_loadFromNibUsingClassName()
vc?.articleId = article.articleId;
self.stackController.pushViewController(vc, animated: true)
}
}
| d06c32b480606c2d97caa865411bb102 | 35.418605 | 182 | 0.666986 | false | false | false | false |
ivlevAstef/DITranquillity | refs/heads/master | Sources/Core/Internal/FrameworksDependenciesContainer.swift | mit | 1 | //
// FrameworksDependenciesContainer.swift
// DITranquillity
//
// Created by Alexander Ivlev on 06/06/2017.
// Copyright © 2017 Alexander Ivlev. All rights reserved.
//
final class FrameworksDependenciesContainer {
private var imports = [FrameworkWrapper: Set<FrameworkWrapper>]()
private var mutex = PThreadMutex(normal: ())
final func dependency(framework: DIFramework.Type, import importFramework: DIFramework.Type) {
let frameworkWrapper = FrameworkWrapper(framework: framework)
let importFrameworkWrapper = FrameworkWrapper(framework: importFramework)
mutex.sync {
if nil == imports[frameworkWrapper]?.insert(importFrameworkWrapper) {
imports[frameworkWrapper] = [importFrameworkWrapper]
}
}
}
func filterByChilds(for framework: DIFramework.Type, components: Components) -> Components {
let frameworkWrapper = FrameworkWrapper(framework: framework)
let childs = mutex.sync {
return imports[frameworkWrapper] ?? []
}
return components.filter { $0.framework.map { childs.contains(FrameworkWrapper(framework: $0)) } ?? false }
}
}
private class FrameworkWrapper: Hashable {
let framework: DIFramework.Type
private let identifier: ObjectIdentifier
init(framework: DIFramework.Type) {
self.framework = framework
self.identifier = ObjectIdentifier(framework)
}
#if swift(>=5.0)
func hash(into hasher: inout Hasher) {
hasher.combine(identifier)
}
#else
var hashValue: Int {
return identifier.hashValue
}
#endif
static func ==(lhs: FrameworkWrapper, rhs: FrameworkWrapper) -> Bool {
return lhs.identifier == rhs.identifier
}
}
| 05d3924985796792ea49a772659b2b0d | 29.109091 | 111 | 0.722826 | false | false | false | false |
ontouchstart/swift3-playground | refs/heads/playgroundbook | Learn to Code 1.playgroundbook/Contents/Chapters/Document8.playgroundchapter/Pages/Exercise4.playgroundpage/Sources/Assessments.swift | mit | 1 | //
// Assessments.swift
//
// Copyright (c) 2016 Apple Inc. All Rights Reserved.
//
let solution = "```swift\nwhile !isOnGem {\n while !isOnClosedSwitch && !isOnGem {\n moveForward()\n }\n if isOnClosedSwitch && isBlocked {\n toggleSwitch()\n turnLeft()\n } else if isOnClosedSwitch {\n toggleSwitch()\n turnRight()\n }\n}\ncollectGem()\n"
import PlaygroundSupport
public func assessmentPoint() -> AssessmentResults {
pageIdentifier = "Which_Way_To_Turn?"
let success = "### Brilliant! \nNow you're creating your own algorithms from scratch. How cool is that? \n\n[**Next Page**](@next)"
var hints = [
"Each time Byte reaches a switch, you need to decide whether to turn left or right.",
"Be sure to run your algorithm until Byte reaches the gem at the end of the puzzle.",
"Remember to use the && operator to check multiple conditions with a single `if` statement."
]
switch currentPageRunCount {
case 2..<4:
hints[0] = "You can use nested `while` loops in this puzzle. Make the *outer* loop run while Byte isn’t on a gem. Make the *inner* loop move Byte forward until reaching the next switch."
case 4..<6:
hints[0] = "Your algorithm should turn Byte to the left if on a switch and blocked, and to the right if just on a switch but not blocked."
case 5..<9:
hints[0] = "Trying a lot of different approaches is the best way to find one that works. Sometimes the people who fail the most in the beginning are those who end up succeeding in the end."
default:
break
}
return updateAssessment(successMessage: success, failureHints: hints, solution: solution)
}
| bbc053f9e3527ccae35b750e1f6fad52 | 45.605263 | 305 | 0.648786 | false | false | false | false |
Instamojo/ios-sdk | refs/heads/master | Instamojo/PaymentOptionsView.swift | lgpl-3.0 | 1 | //
// PaymentOptionsView.swift
// Instamojo
//
// Created by Sukanya Raj on 06/02/17.
// Edited by Vaibhav Bhasin on 4/10/19
// Copyright © 2017 Sukanya Raj. All rights reserved.
//
import UIKit
class PaymentOptionsView: UIViewController, UITableViewDataSource, UITableViewDelegate {
@IBOutlet weak var paymentOptionsTableView: UITableView!
var order: Order!
var paymentOptions: NSMutableArray = [Constants.DebitCardOption, Constants.NetBankingOption, Constants.CreditCardOption, Constants.WalletsOption, Constants.EmiOption, Constants.UpiOption]
var paymentCompleted : Bool = false;
var mainStoryboard: UIStoryboard = UIStoryboard()
var isBackButtonNeeded: Bool = true
override func viewDidLoad() {
super.viewDidLoad()
paymentOptionsTableView.tableFooterView = UIView()
mainStoryboard = Constants.getStoryboardInstance()
self.reloadDataBasedOnOrder()
NotificationCenter.default.addObserver(self, selector: #selector(self.backToViewController), name: NSNotification.Name("INSTAMOJO"), object: nil)
if(isBackButtonNeeded == false){
let menu_button_ = UIBarButtonItem.init(title: "Exit", style: .plain, target: self, action:#selector(self.exitViewController))
self.navigationItem.rightBarButtonItem = menu_button_
}
}
@objc func exitViewController(){
self.dismiss(animated: true, completion: nil)
}
@objc func backToViewController(){
Logger.logDebug(tag: "Payment Done", message: "In Observer")
paymentCompleted = true
}
//Set payment options based on the order
func reloadDataBasedOnOrder() {
if order.netBankingOptions == nil {
paymentOptions.remove(Constants.NetBankingOption)
}
if order.cardOptions == nil {
paymentOptions.remove(Constants.CreditCardOption)
paymentOptions.remove(Constants.DebitCardOption)
}
if order.emiOptions == nil {
paymentOptions.remove(Constants.EmiOption)
}
if order.walletOptions == nil {
paymentOptions.remove(Constants.WalletsOption)
}
if order.upiOptions == nil {
paymentOptions.remove(Constants.UpiOption)
}
paymentOptionsTableView.reloadData()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return paymentOptions.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: Constants.PaymentOptionsCell, for: indexPath)
cell.textLabel?.text = paymentOptions.object(at: indexPath.row) as? String
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let rowSelected = indexPath.row
let options = paymentOptions.object(at: rowSelected) as? String
switch options {
case Constants.NetBankingOption? :
DispatchQueue.main.async {
self.onNetBankingSelected(options: options!)
}
break
case Constants.CreditCardOption? :
onCreditCardSelected()
break
case Constants.DebitCardOption? :
onDebitCardSelected()
break
case Constants.EmiOption? :
onEmiSelected(options : options!)
break
case Constants.WalletsOption? :
DispatchQueue.main.async {
self.onWalletSelected(options: options!)
}
break
case Constants.UpiOption? :
onUPISelected()
break
default:
onCreditCardSelected()
break
}
}
func onNetBankingSelected(options: String) {
if let viewController = mainStoryboard.instantiateViewController(withIdentifier: Constants.PaymentOptionsListviewController) as? ListOptionsView {
viewController.paymentOption = options
viewController.order = order
self.navigationController?.pushViewController(viewController, animated: true)
}
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
if UserDefaults.standard.value(forKey: "USER-CANCELLED-ON-VERIFY") != nil {
DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
_ = self.navigationController?.popViewController(animated: true)
NotificationCenter.default.post(name: NSNotification.Name(rawValue: "INSTAMOJO"), object: nil)
}
}
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
if paymentCompleted {
Logger.logDebug(tag: "Payment Done", message: "GO BACK")
paymentCompleted = false
_ = self.navigationController?.popViewController(animated: true)
}
}
func onCreditCardSelected() {
if let viewController = mainStoryboard.instantiateViewController(withIdentifier: Constants.PaymentOptionsCardViewController) as? CardFormView {
viewController.cardType = Constants.CreditCard
viewController.order = self.order
self.navigationController?.pushViewController(viewController, animated: true)
}
}
func onDebitCardSelected() {
if let viewController = mainStoryboard.instantiateViewController(withIdentifier: Constants.PaymentOptionsCardViewController) as? CardFormView {
viewController.cardType = Constants.DebitCard
viewController.order = self.order
self.navigationController?.pushViewController(viewController, animated: true)
}
}
func onEmiSelected(options: String) {
if let viewController = mainStoryboard.instantiateViewController(withIdentifier: Constants.PaymentOptionsListviewController) as? ListOptionsView {
viewController.paymentOption = options
viewController.order = order
self.navigationController?.pushViewController(viewController, animated: true)
}
}
func onWalletSelected(options: String) {
if let viewController = mainStoryboard.instantiateViewController(withIdentifier: Constants.PaymentOptionsListviewController) as? ListOptionsView {
viewController.paymentOption = options
viewController.order = order
self.navigationController?.pushViewController(viewController, animated: true)
}
}
func onUPISelected() {
if let viewController = mainStoryboard.instantiateViewController(withIdentifier: Constants.PaymentOptionsUpiViewController) as? UPIPaymentView {
viewController.order = order
self.navigationController?.pushViewController(viewController, animated: true)
}
}
}
| 4d2bc676b3d198043f9ac0901b9a8d44 | 38.649718 | 191 | 0.671701 | false | false | false | false |
amberstar/Component | refs/heads/master | ComponentKit/operators/Time.swift | mit | 2 | //
// Component: Time.swift
// Copyright © 2016 SIMPLETOUCH LLC, All rights reserved.
//
import Foundation
public struct Runtime : OperatorProtocol {
private typealias TimeProcess = (TimeInterval, CFAbsoluteTime, CFAbsoluteTime) -> (CFAbsoluteTime, TimeInterval)
private final class TimeProcessor {
static var firstProcess: TimeProcess = { time, timestamp, _ in
return (timestamp, time)
}
static var normalProcess: TimeProcess = { time, timestamp, previousTimestamp in
return (timestamp, time + (timestamp - previousTimestamp))
}
lazy var switchingProcess: TimeProcess = { return { time, timestamp, previousTimestamp in
self._process = normalProcess
return TimeProcessor.firstProcess(time, timestamp, previousTimestamp)
}}()
lazy var _process: TimeProcess = { return self.switchingProcess }()
func process(time: TimeInterval, timestamp: CFAbsoluteTime, previousTimestamp: CFAbsoluteTime) -> (CFAbsoluteTime, TimeInterval) {
return _process(time, timestamp, previousTimestamp)
}
}
public private(set) var time: (timestamp: CFAbsoluteTime, time: TimeInterval)
private var processor = TimeProcessor()
public mutating func input(_ timestamp: CFAbsoluteTime) -> TimeInterval? {
time = processor.process(time: time.time, timestamp: timestamp, previousTimestamp: time.timestamp)
return time.time
}
/// Creates an instance with the specified timestamp and uptime in seconds.
public init(timestamp: CFAbsoluteTime? = nil, uptime: TimeInterval = 0 ) {
self.time = (timestamp: timestamp ?? CFAbsoluteTimeGetCurrent(), time: uptime)
}
}
/// An operator that produces the current absolute time in seconds
public struct Timestamp : OperatorProtocol {
public mutating func input(_ : Void) -> CFTimeInterval? {
return CFAbsoluteTimeGetCurrent()
}
public init() {}
}
public struct TimeKeeper {
private var op : Operator<(), Double>
public private(set) var time: TimeInterval = 0
public mutating func start() {
time = op.input()!
}
public mutating func update() -> TimeInterval {
return op.input()!
}
public mutating func reset() {
op = Timestamp().compose(Runtime())
time = 0
}
public init(time: TimeInterval = 0) {
op = Timestamp().compose(Runtime(timestamp: time))
}
}
| 8be76100cdf1220aea20b2000b242470 | 32.324324 | 138 | 0.667883 | false | false | false | false |
JGiola/swift | refs/heads/main | test/Interop/Cxx/namespace/templates-module-interface.swift | apache-2.0 | 5 | // RUN: %target-swift-ide-test -print-module -module-to-print=Templates -I %S/Inputs -source-filename=x -enable-experimental-cxx-interop | %FileCheck %s
// CHECK: enum TemplatesNS1 {
// CHECK-NEXT: enum TemplatesNS2 {
// CHECK-NEXT: static func forwardDeclaredFunctionTemplate<T>(_: T) -> UnsafePointer<CChar>!
// CHECK-NEXT: struct __CxxTemplateInstN12TemplatesNS112TemplatesNS228ForwardDeclaredClassTemplateIcEE {
// CHECK-NEXT: init()
// CHECK-NEXT: mutating func basicMember() -> UnsafePointer<CChar>!
// CHECK-NEXT: }
// CHECK-NEXT: struct ForwardDeclaredClassTemplate<> {
// CHECK-NEXT: }
// CHECK-NEXT: static func forwardDeclaredFunctionTemplateOutOfLine<T>(_: T) -> UnsafePointer<CChar>!
// CHECK-NEXT: struct __CxxTemplateInstN12TemplatesNS112TemplatesNS237ForwardDeclaredClassTemplateOutOfLineIcEE {
// CHECK-NEXT: init()
// CHECK-NEXT: mutating func basicMember() -> UnsafePointer<CChar>!
// CHECK-NEXT: }
// CHECK-NEXT: struct ForwardDeclaredClassTemplateOutOfLine<> {
// CHECK-NEXT: }
// CHECK-NEXT: typealias BasicClassTemplateChar = TemplatesNS1.TemplatesNS3.__CxxTemplateInstN12TemplatesNS112TemplatesNS318BasicClassTemplateIcEE
// CHECK-NEXT: static func takesClassTemplateFromSibling(_: TemplatesNS1.TemplatesNS2.BasicClassTemplateChar) -> UnsafePointer<CChar>!
// CHECK-NEXT: }
// CHECK-NEXT: static func basicFunctionTemplate<T>(_: T) -> UnsafePointer<CChar>!
// CHECK-NEXT: struct __CxxTemplateInstN12TemplatesNS118BasicClassTemplateIcEE {
// CHECK-NEXT: init()
// CHECK-NEXT: mutating func basicMember() -> UnsafePointer<CChar>!
// CHECK-NEXT: }
// CHECK-NEXT: struct BasicClassTemplate<> {
// CHECK-NEXT: }
// CHECK-NEXT: typealias BasicClassTemplateChar = TemplatesNS1.__CxxTemplateInstN12TemplatesNS118BasicClassTemplateIcEE
// CHECK-NEXT: static func basicFunctionTemplateDefinedInDefs<T>(_: T) -> UnsafePointer<CChar>!
// CHECK-NEXT: struct BasicClassTemplateDefinedInDefs<> {
// CHECK-NEXT: }
// CHECK-NEXT: typealias UseTemplate = TemplatesNS4.__CxxTemplateInstN12TemplatesNS417HasSpecializationIcEE
// CHECK-NEXT: typealias UseSpecialized = TemplatesNS4.__CxxTemplateInstN12TemplatesNS417HasSpecializationIiEE
// CHECK-NEXT: enum TemplatesNS3 {
// CHECK-NEXT: struct __CxxTemplateInstN12TemplatesNS112TemplatesNS318BasicClassTemplateIcEE {
// CHECK-NEXT: init()
// CHECK-NEXT: }
// CHECK-NEXT: struct BasicClassTemplate<> {
// CHECK-NEXT: }
// CHECK-NEXT: }
// CHECK-NEXT: struct __CxxTemplateInstN12TemplatesNS112TemplatesNS228ForwardDeclaredClassTemplateIcEE {
// CHECK-NEXT: init()
// CHECK-NEXT: mutating func basicMember() -> UnsafePointer<CChar>!
// CHECK-NEXT: }
// CHECK-NEXT: typealias ForwardDeclaredClassTemplateChar = TemplatesNS1.TemplatesNS2.__CxxTemplateInstN12TemplatesNS112TemplatesNS228ForwardDeclaredClassTemplateIcEE
// CHECK-NEXT: }
// CHECK-NEXT: typealias ForwardDeclaredClassTemplateOutOfLineChar = TemplatesNS1.TemplatesNS2.__CxxTemplateInstN12TemplatesNS112TemplatesNS237ForwardDeclaredClassTemplateOutOfLineIcEE
// CHECK-NEXT: enum TemplatesNS4 {
// CHECK-NEXT: struct __CxxTemplateInstN12TemplatesNS417HasSpecializationIcEE {
// CHECK-NEXT: init()
// CHECK-NEXT: }
// CHECK-NEXT: struct __CxxTemplateInstN12TemplatesNS417HasSpecializationIiEE {
// CHECK-NEXT: init()
// CHECK-NEXT: }
// CHECK-NEXT: struct HasSpecialization<> {
// CHECK-NEXT: }
// CHECK-NEXT: }
| c6034ff40d2a4a56ebe9f904d858751f | 59.206897 | 184 | 0.748855 | false | false | false | false |
harlanhaskins/HaroldWorkaround | refs/heads/master | App/Pods/BRYXBanner/Pod/Classes/Banner.swift | mit | 1 | //
// Banner.swift
//
// Created by Harlan Haskins on 7/27/15.
// Copyright (c) 2015 Bryx. All rights reserved.
//
import UIKit
private enum BannerState {
case Showing, Hidden, Gone
}
/// A level of 'springiness' for Banners.
///
/// - None: The banner will slide in and not bounce.
/// - Slight: The banner will bounce a little.
/// - Heavy: The banner will bounce a lot.
public enum BannerSpringiness {
case None, Slight, Heavy
private var springValues: (damping: CGFloat, velocity: CGFloat) {
switch self {
case .None: return (damping: 1.0, velocity: 1.0)
case .Slight: return (damping: 0.7, velocity: 1.5)
case .Heavy: return (damping: 0.6, velocity: 2.0)
}
}
}
/// Banner is a dropdown notification view that presents above the main view controller, but below the status bar.
public class Banner: UIView {
private class func topWindow() -> UIWindow? {
for window in UIApplication.sharedApplication().windows.reverse() {
if window.windowLevel == UIWindowLevelNormal && !window.hidden { return window }
}
return nil
}
private let contentView = UIView()
private let labelView = UIView()
private let backgroundView = UIView()
/// How long the slide down animation should last.
public var animationDuration: NSTimeInterval = 0.4
/// The preferred style of the status bar during display of the banner. Defaults to `.LightContent`.
///
/// If the banner's `adjustsStatusBarStyle` is false, this property does nothing.
public var preferredStatusBarStyle = UIStatusBarStyle.LightContent
/// Whether or not this banner should adjust the status bar style during its presentation. Defaults to `false`.
public var adjustsStatusBarStyle = false
/// How 'springy' the banner should display. Defaults to `.Slight`
public var springiness = BannerSpringiness.Slight
/// The color of the text as well as the image tint color if `shouldTintImage` is `true`.
public var textColor = UIColor.whiteColor() {
didSet {
resetTintColor()
}
}
/// Whether or not the banner should show a shadow when presented.
public var hasShadows = true {
didSet {
resetShadows()
}
}
/// The color of the background view. Defaults to `nil`.
override public var backgroundColor: UIColor? {
get { return backgroundView.backgroundColor }
set { backgroundView.backgroundColor = newValue }
}
/// The opacity of the background view. Defaults to 0.95.
override public var alpha: CGFloat {
get { return backgroundView.alpha }
set { backgroundView.alpha = newValue }
}
/// A block to call when the uer taps on the banner.
public var didTapBlock: (() -> ())?
/// A block to call after the banner has finished dismissing and is off screen.
public var didDismissBlock: (() -> ())?
/// Whether or not the banner should dismiss itself when the user taps. Defaults to `true`.
public var dismissesOnTap = true
/// Whether or not the banner should dismiss itself when the user swipes up. Defaults to `true`.
public var dismissesOnSwipe = true
/// Whether or not the banner should tint the associated image to the provided `textColor`. Defaults to `true`.
public var shouldTintImage = true {
didSet {
resetTintColor()
}
}
/// The label that displays the banner's title.
public let titleLabel: UILabel = {
let label = UILabel()
label.font = UIFont.preferredFontForTextStyle(UIFontTextStyleHeadline)
label.numberOfLines = 0
label.translatesAutoresizingMaskIntoConstraints = false
return label
}()
/// The label that displays the banner's subtitle.
public let detailLabel: UILabel = {
let label = UILabel()
label.font = UIFont.preferredFontForTextStyle(UIFontTextStyleSubheadline)
label.numberOfLines = 0
label.translatesAutoresizingMaskIntoConstraints = false
return label
}()
/// The image on the left of the banner.
let image: UIImage?
/// The image view that displays the `image`.
public let imageView: UIImageView = {
let imageView = UIImageView()
imageView.translatesAutoresizingMaskIntoConstraints = false
imageView.contentMode = .ScaleAspectFit
return imageView
}()
private var bannerState = BannerState.Hidden {
didSet {
if bannerState != oldValue {
forceUpdates()
}
}
}
/// A Banner with the provided `title`, `subtitle`, and optional `image`, ready to be presented with `show()`.
///
/// - parameter title: The title of the banner. Optional. Defaults to nil.
/// - parameter subtitle: The subtitle of the banner. Optional. Defaults to nil.
/// - parameter image: The image on the left of the banner. Optional. Defaults to nil.
/// - parameter backgroundColor: The color of the banner's background view. Defaults to `UIColor.blackColor()`.
/// - parameter didTapBlock: An action to be called when the user taps on the banner. Optional. Defaults to `nil`.
public required init(title: String? = nil, subtitle: String? = nil, image: UIImage? = nil, backgroundColor: UIColor = UIColor.blackColor(), didTapBlock: (() -> ())? = nil) {
self.didTapBlock = didTapBlock
self.image = image
super.init(frame: CGRectZero)
resetShadows()
addGestureRecognizers()
initializeSubviews()
resetTintColor()
titleLabel.text = title
detailLabel.text = subtitle
backgroundView.backgroundColor = backgroundColor
backgroundView.alpha = 0.95
}
private func forceUpdates() {
guard let superview = superview, showingConstraint = showingConstraint, hiddenConstraint = hiddenConstraint else { return }
switch bannerState {
case .Hidden:
superview.removeConstraint(showingConstraint)
superview.addConstraint(hiddenConstraint)
case .Showing:
superview.removeConstraint(hiddenConstraint)
superview.addConstraint(showingConstraint)
case .Gone:
superview.removeConstraint(hiddenConstraint)
superview.removeConstraint(showingConstraint)
superview.removeConstraints(commonConstraints)
}
setNeedsLayout()
setNeedsUpdateConstraints()
layoutIfNeeded()
updateConstraintsIfNeeded()
}
internal func didTap(recognizer: UITapGestureRecognizer) {
if dismissesOnTap {
dismiss()
}
didTapBlock?()
}
internal func didSwipe(recognizer: UISwipeGestureRecognizer) {
if dismissesOnSwipe {
dismiss()
}
}
private func addGestureRecognizers() {
addGestureRecognizer(UITapGestureRecognizer(target: self, action: "didTap:"))
let swipe = UISwipeGestureRecognizer(target: self, action: "didSwipe:")
swipe.direction = .Up
addGestureRecognizer(swipe)
}
private func resetTintColor() {
titleLabel.textColor = textColor
detailLabel.textColor = textColor
imageView.image = shouldTintImage ? image?.imageWithRenderingMode(.AlwaysTemplate) : image
imageView.tintColor = shouldTintImage ? textColor : nil
}
private func resetShadows() {
layer.shadowColor = UIColor.blackColor().CGColor
layer.shadowOpacity = self.hasShadows ? 0.5 : 0.0
layer.shadowOffset = CGSize(width: 0, height: 0)
layer.shadowRadius = 4
}
private func initializeSubviews() {
let views = [
"backgroundView": backgroundView,
"contentView": contentView,
"imageView": imageView,
"labelView": labelView,
"titleLabel": titleLabel,
"detailLabel": detailLabel
]
translatesAutoresizingMaskIntoConstraints = false
addSubview(backgroundView)
backgroundView.translatesAutoresizingMaskIntoConstraints = false
addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|[backgroundView]|", options: .DirectionLeadingToTrailing, metrics: nil, views: views))
addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[backgroundView(>=80)]|", options: .DirectionLeadingToTrailing, metrics: nil, views: views))
backgroundView.backgroundColor = backgroundColor
contentView.translatesAutoresizingMaskIntoConstraints = false
backgroundView.addSubview(contentView)
labelView.translatesAutoresizingMaskIntoConstraints = false
contentView.addSubview(labelView)
labelView.addSubview(titleLabel)
labelView.addSubview(detailLabel)
let statusBarSize = UIApplication.sharedApplication().statusBarFrame.size
let heightOffset = min(statusBarSize.height, statusBarSize.width) // Arbitrary, but looks nice.
for format in ["H:|[contentView]|", "V:|-(\(heightOffset))-[contentView]|"] {
backgroundView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat(format, options: .DirectionLeadingToTrailing, metrics: nil, views: views))
}
let leftConstraintText: String
if image == nil {
leftConstraintText = "|"
} else {
contentView.addSubview(imageView)
contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-(15)-[imageView]", options: .DirectionLeadingToTrailing, metrics: nil, views: views))
contentView.addConstraint(NSLayoutConstraint(item: imageView, attribute: .CenterY, relatedBy: .Equal, toItem: contentView, attribute: .CenterY, multiplier: 1.0, constant: 0.0))
imageView.addConstraint(NSLayoutConstraint(item: imageView, attribute: .Width, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1.0, constant: 25.0))
imageView.addConstraint(NSLayoutConstraint(item: imageView, attribute: .Height, relatedBy: .Equal, toItem: imageView, attribute: .Width, multiplier: 1.0, constant: 0.0))
leftConstraintText = "[imageView]"
}
let constraintFormat = "H:\(leftConstraintText)-(15)-[labelView]-(8)-|"
contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat(constraintFormat, options: .DirectionLeadingToTrailing, metrics: nil, views: views))
contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-(>=1)-[labelView]-(>=1)-|", options: .DirectionLeadingToTrailing, metrics: nil, views: views))
backgroundView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|[contentView]-(<=1)-[labelView]", options: .AlignAllCenterY, metrics: nil, views: views))
for view in [titleLabel, detailLabel] {
let constraintFormat = "H:|-(15)-[label]-(8)-|"
contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat(constraintFormat, options: .DirectionLeadingToTrailing, metrics: nil, views: ["label": view]))
}
labelView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-(10)-[titleLabel][detailLabel]-(10)-|", options: .DirectionLeadingToTrailing, metrics: nil, views: views))
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private var showingConstraint: NSLayoutConstraint?
private var hiddenConstraint: NSLayoutConstraint?
private var commonConstraints = [NSLayoutConstraint]()
override public func didMoveToSuperview() {
super.didMoveToSuperview()
guard let superview = superview where bannerState != .Gone else { return }
commonConstraints = NSLayoutConstraint.constraintsWithVisualFormat("H:|[banner]|", options: .DirectionLeadingToTrailing, metrics: nil, views: ["banner": self])
superview.addConstraints(commonConstraints)
let yOffset: CGFloat = -7.0 // Offset the bottom constraint to make room for the shadow to animate off screen.
showingConstraint = NSLayoutConstraint(item: self, attribute: .Top, relatedBy: .Equal, toItem: superview, attribute: .Top, multiplier: 1.0, constant: yOffset)
hiddenConstraint = NSLayoutConstraint(item: self, attribute: .Bottom, relatedBy: .Equal, toItem: superview, attribute: .Top, multiplier: 1.0, constant: yOffset)
}
/// Shows the banner. If a view is specified, the banner will be displayed at the top of that view, otherwise at top of the top window. If a `duration` is specified, the banner dismisses itself automatically after that duration elapses.
/// - parameter view: A view the banner will be shown in. Optional. Defaults to 'nil', which in turn means it will be shown in the top window. duration A time interval, after which the banner will dismiss itself. Optional. Defaults to `nil`.
public func show(view view: UIView? = Banner.topWindow(), duration: NSTimeInterval? = nil) {
guard let view = view else {
print("[Banner]: Could not find window. Aborting.")
return
}
view.addSubview(self)
forceUpdates()
let (damping, velocity) = self.springiness.springValues
let oldStatusBarStyle = UIApplication.sharedApplication().statusBarStyle
if adjustsStatusBarStyle {
UIApplication.sharedApplication().setStatusBarStyle(preferredStatusBarStyle, animated: true)
}
UIView.animateWithDuration(animationDuration, delay: 0.0, usingSpringWithDamping: damping, initialSpringVelocity: velocity, options: .AllowUserInteraction, animations: {
self.bannerState = .Showing
}, completion: { finished in
if let duration = duration {
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(duration * NSTimeInterval(NSEC_PER_SEC))), dispatch_get_main_queue()) {
self.dismiss(self.adjustsStatusBarStyle ? oldStatusBarStyle : nil)
}
}
})
}
/// Dismisses the banner.
public func dismiss(oldStatusBarStyle: UIStatusBarStyle? = nil) {
let (damping, velocity) = self.springiness.springValues
UIView.animateWithDuration(animationDuration, delay: 0.0, usingSpringWithDamping: damping, initialSpringVelocity: velocity, options: .AllowUserInteraction, animations: {
self.bannerState = .Hidden
if let oldStatusBarStyle = oldStatusBarStyle {
UIApplication.sharedApplication().setStatusBarStyle(oldStatusBarStyle, animated: true)
}
}, completion: { finished in
self.bannerState = .Gone
self.removeFromSuperview()
self.didDismissBlock?()
})
}
}
| 7fe26e9b97fff77bf0c845ecfea2d1fe | 46.071875 | 245 | 0.669521 | false | false | false | false |
juancruzmdq/NLService | refs/heads/master | NLService/Classes/NLRemoteRequest.swift | mit | 1 | //
// RemoteRequest.swift
//
//Copyright (c) 2016 Juan Cruz Ghigliani <[email protected]> www.juancruzmdq.com.ar
//
//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.
////////////////////////////////////////////////////////////////////////////////
// MARK: Imports
import Foundation
public enum RemoteRequestResult<T> {
case Success(T)
case Error(NSError)
}
/**
* Class that handle a request to a RemoteResource in a RemoteService
*/
public class NLRemoteRequest<T>{
////////////////////////////////////////////////////////////////////////////////
// MARK: Types
public typealias CompleteBlock = (RemoteRequestResult<T>)->Void
////////////////////////////////////////////////////////////////////////////////
// MARK: Public Properties
public var resource:NLRemoteResource<T>
public var manager:NLManagerProtocol
public var params:[String:String]
public var HTTPMethod:NLMethod = .GET
public var service:NLRemoteService
////////////////////////////////////////////////////////////////////////////////
// MARK: Setup & Teardown
internal init(resource:NLRemoteResource<T>, service:NLRemoteService, manager:NLManagerProtocol){
self.service = service
self.resource = resource
self.manager = manager
self.params = [:]
}
////////////////////////////////////////////////////////////////////////////////
// MARK: public Methods
public func addParam(key:String,value:String) -> NLRemoteRequest<T>{
self.params[key] = value
return self
}
public func addParams(values:[String:String]) -> NLRemoteRequest<T>{
for(k,v) in values{
self.params[k] = v
}
return self
}
public func HTTPMethod(method:NLMethod) -> NLRemoteRequest<T> {
self.HTTPMethod = method
return self
}
public func fullURLString() -> String{
return self.fullURL().absoluteString
}
public func fullURL() -> NSURL{
return self.service.baseURL.URLByAppendingPathComponent(self.resource.path)
}
/**
Use manager to build the request to the remote service, and handle response
- parameter onComplete: block to be call after handle response
*/
public func load(onComplete:CompleteBlock){
preconditionFailure("This method must be overridden - HEEEEELPPPPPPPPP I DON'T KNOW WHAT TO DO")
}
func handleError(error:NSError?,onComplete:CompleteBlock){
if let error:NSError = error{
onComplete(.Error(error))
}else{
onComplete(.Error(NSError(domain: "RemoteService", code: 5003, localizedDescription:"Empty Response")))
}
}
} | 57d060f3466fe8d768c9abd0c0c54181 | 35.048077 | 115 | 0.614995 | false | false | false | false |
spweau/Test_DYZB | refs/heads/master | Test_DYZB/Test_DYZB/Classes/Main/View/CollectionBaseCell.swift | mit | 1 | //
// CollectionBaseCell.swift
// Test_DYZB
//
// Created by Spweau on 2017/2/24.
// Copyright © 2017年 sp. All rights reserved.
//
import UIKit
class CollectionBaseCell: UICollectionViewCell {
@IBOutlet weak var iconImageView: UIImageView!
@IBOutlet weak var onlineBtn: UIButton!
@IBOutlet weak var nickNameLabel: UILabel!
// 定义模型属性
var anchor : AnchorModel? {
didSet {
// 0.校验模型是否有值
guard let anchor = anchor else { return }
// 1.取出在线人数显示的文字
var onlineStr : String = ""
if anchor.online >= 10000 {
onlineStr = "\(Int(anchor.online / 10000))万在线"
} else {
onlineStr = "\(anchor.online)在线"
}
onlineBtn.setTitle(onlineStr, for: .normal)
// 2.昵称的显示
nickNameLabel.text = anchor.nickname
// 4. 封面
guard let iconURL = URL(string: anchor.vertical_src) else { return }
iconImageView.kf.setImage(with: iconURL)
}
}
}
| 213e521c6fd3a35b5a46ea1557c6f705 | 23.888889 | 80 | 0.524107 | false | false | false | false |
joerocca/GitHawk | refs/heads/master | Local Pods/SwipeCellKit/Source/SwipeExpansionStyle.swift | mit | 2 | //
// SwipeExpansionStyle.swift
//
// Created by Jeremy Koch
// Copyright © 2017 Jeremy Koch. All rights reserved.
//
import UIKit
/// Describes the expansion style. Expansion is the behavior when the cell is swiped past a defined threshold.
public struct SwipeExpansionStyle {
/// The default action performs a selection-type behavior. The cell bounces back to its unopened state upon selection and the row remains in the table view.
public static var selection: SwipeExpansionStyle { return SwipeExpansionStyle(target: .percentage(0.5),
elasticOverscroll: true,
completionAnimation: .bounce) }
/// The default action performs a destructive behavior. The cell is removed from the table view in an animated fashion.
public static var destructive: SwipeExpansionStyle { return .destructive(automaticallyDelete: true, timing: .with) }
/// The default action performs a destructive behavior after the fill animation completes. The cell is removed from the table view in an animated fashion.
public static var destructiveAfterFill: SwipeExpansionStyle { return .destructive(automaticallyDelete: true, timing: .after) }
/// The default action performs a fill behavior.
///
/// - note: The action handle must call `SwipeAction.fulfill(style:)` to resolve the fill expansion.
public static var fill: SwipeExpansionStyle { return SwipeExpansionStyle(target: .edgeInset(30),
additionalTriggers: [.overscroll(30)],
completionAnimation: .fill(.manual(timing: .after))) }
/**
Returns a `SwipeExpansionStyle` instance for the default action which peforms destructive behavior with the specified options.
- parameter automaticallyDelete: Specifies if row/item deletion should be peformed automatically. If `false`, you must call `SwipeAction.fulfill(with style:)` at some point while/after your action handler is invoked to trigger deletion.
- parameter timing: The timing which specifies when the action handler will be invoked with respect to the fill animation.
- returns: The new `SwipeExpansionStyle` instance.
*/
public static func destructive(automaticallyDelete: Bool, timing: FillOptions.HandlerInvocationTiming = .with) -> SwipeExpansionStyle {
return SwipeExpansionStyle(target: .edgeInset(30),
additionalTriggers: [.touchThreshold(0.8)],
completionAnimation: .fill(automaticallyDelete ? .automatic(.delete, timing: timing) : .manual(timing: timing)))
}
/// The relative target expansion threshold. Expansion will occur at the specified value.
public let target: Target
/// Additional triggers to useful for determining if expansion should occur.
public let additionalTriggers: [Trigger]
/// Specifies if buttons should expand to fully fill overscroll, or expand at a percentage relative to the overscroll.
public let elasticOverscroll: Bool
/// Specifies the expansion animation completion style.
public let completionAnimation: CompletionAnimation
/// Specifies the minimum amount of overscroll required if the configured target is less than the fully exposed action view.
public var minimumTargetOverscroll: CGFloat = 20
/// The amount of elasticity applied when dragging past the expansion target.
///
/// - note: Default value is 0.2. Valid range is from 0.0 for no movement past the expansion target, to 1.0 for unrestricted movement with dragging.
public var targetOverscrollElasticity: CGFloat = 0.2
/**
Contructs a new `SwipeExpansionStyle` instance.
- parameter target: The relative target expansion threshold. Expansion will occur at the specified value.
- parameter additionalTriggers: Additional triggers to useful for determining if expansion should occur.
- parameter elasticOverscroll: Specifies if buttons should expand to fully fill overscroll, or expand at a percentage relative to the overscroll.
- parameter completionAnimation: Specifies the expansion animation completion style.
- returns: The new `SwipeExpansionStyle` instance.
*/
public init(target: Target, additionalTriggers: [Trigger] = [], elasticOverscroll: Bool = false, completionAnimation: CompletionAnimation = .bounce) {
self.target = target
self.additionalTriggers = additionalTriggers
self.elasticOverscroll = elasticOverscroll
self.completionAnimation = completionAnimation
}
func shouldExpand(view: Swipeable, gesture: UIPanGestureRecognizer, in superview: UIView) -> Bool {
guard let actionsView = view.actionsView else { return false }
guard abs(view.frame.minX) >= actionsView.preferredWidth else { return false }
if abs(view.frame.minX) >= target.offset(for: view, in: superview, minimumOverscroll: minimumTargetOverscroll) {
return true
}
for trigger in additionalTriggers {
if trigger.isTriggered(view: view, gesture: gesture, in: superview) {
return true
}
}
return false
}
func targetOffset(for view: Swipeable, in superview: UIView) -> CGFloat {
return target.offset(for: view, in: superview, minimumOverscroll: minimumTargetOverscroll)
}
}
extension SwipeExpansionStyle {
/// Describes the relative target expansion threshold. Expansion will occur at the specified value.
public enum Target {
/// The target is specified by a percentage.
case percentage(CGFloat)
/// The target is specified by a edge inset.
case edgeInset(CGFloat)
func offset(for view: Swipeable, in superview: UIView, minimumOverscroll: CGFloat) -> CGFloat {
guard let actionsView = view.actionsView else { return .greatestFiniteMagnitude }
let offset: CGFloat = {
switch self {
case .percentage(let value):
return superview.bounds.width * value
case .edgeInset(let value):
return superview.bounds.width - value
}
}()
return max(actionsView.preferredWidth + minimumOverscroll, offset)
}
}
/// Describes additional triggers to useful for determining if expansion should occur.
public enum Trigger {
/// The trigger is specified by a touch occuring past the supplied percentage in the superview.
case touchThreshold(CGFloat)
/// The trigger is specified by the distance in points past the fully exposed action view.
case overscroll(CGFloat)
func isTriggered(view: Swipeable, gesture: UIPanGestureRecognizer, in superview: UIView) -> Bool {
guard let actionsView = view.actionsView else { return false }
switch self {
case .touchThreshold(let value):
let location = gesture.location(in: superview).x
let locationRatio = (actionsView.orientation == .left ? location : superview.bounds.width - location) / superview.bounds.width
return locationRatio > value
case .overscroll(let value):
return abs(view.frame.minX) > actionsView.preferredWidth + value
}
}
}
/// Describes the expansion animation completion style.
public enum CompletionAnimation {
/// The expansion will completely fill the item.
case fill(FillOptions)
/// The expansion will bounce back from the trigger point and hide the action view, resetting the item.
case bounce
}
/// Specifies the options for the fill completion animation.
public struct FillOptions {
/// Describes when the action handler will be invoked with respect to the fill animation.
public enum HandlerInvocationTiming {
/// The action handler is invoked with the fill animation.
case with
/// The action handler is invoked after the fill animation completes.
case after
}
/**
Returns a `FillOptions` instance with automatic fulfillemnt.
- parameter style: The fulfillment style describing how expansion should be resolved once the action has been fulfilled.
- parameter timing: The timing which specifies when the action handler will be invoked with respect to the fill animation.
- returns: The new `FillOptions` instance.
*/
public static func automatic(_ style: ExpansionFulfillmentStyle, timing: HandlerInvocationTiming) -> FillOptions {
return FillOptions(autoFulFillmentStyle: style, timing: timing)
}
/**
Returns a `FillOptions` instance with manual fulfillemnt.
- parameter timing: The timing which specifies when the action handler will be invoked with respect to the fill animation.
- returns: The new `FillOptions` instance.
*/
public static func manual(timing: HandlerInvocationTiming) -> FillOptions {
return FillOptions(autoFulFillmentStyle: nil, timing: timing)
}
/// The fulfillment style describing how expansion should be resolved once the action has been fulfilled.
public let autoFulFillmentStyle: ExpansionFulfillmentStyle?
/// The timing which specifies when the action handler will be invoked with respect to the fill animation.
public let timing: HandlerInvocationTiming
}
}
extension SwipeExpansionStyle.Target: Equatable {
/// :nodoc:
public static func ==(lhs: SwipeExpansionStyle.Target, rhs: SwipeExpansionStyle.Target) -> Bool {
switch (lhs, rhs) {
case (.percentage(let lhs), .percentage(let rhs)):
return lhs == rhs
case (.edgeInset(let lhs), .edgeInset(let rhs)):
return lhs == rhs
default:
return false
}
}
}
extension SwipeExpansionStyle.CompletionAnimation: Equatable {
/// :nodoc:
public static func ==(lhs: SwipeExpansionStyle.CompletionAnimation, rhs: SwipeExpansionStyle.CompletionAnimation) -> Bool {
switch (lhs, rhs) {
case (.fill, .fill):
return true
case (.bounce, .bounce):
return true
default:
return false
}
}
}
| 3bcb767dc3646a50cefc14cc4f37cca4 | 45.819742 | 241 | 0.64983 | false | false | false | false |
legendecas/Rocket.Chat.iOS | refs/heads/sdk | Rocket.Chat.Shared/Controllers/Chat/ChatControllerMessageActions.swift | mit | 1 | //
// ChatControllerMessageActions.swift
// Rocket.Chat
//
// Created by Rafael Kellermann Streit on 14/02/17.
// Copyright © 2017 Rocket.Chat. All rights reserved.
//
import UIKit
extension ChatViewController {
func presentActionsFor(_ message: Message, view: UIView) {
let alert = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
let pinMessage = message.pinned ? localized("chat.message.actions.unpin") : localized("chat.message.actions.pin")
alert.addAction(UIAlertAction(title: pinMessage, style: .default, handler: { (_) in
if message.pinned {
self.messageManager.unpin(message, completion: { (_) in
// Do nothing
})
} else {
self.messageManager.pin(message, completion: { (_) in
// Do nothing
})
}
}))
alert.addAction(UIAlertAction(title: localized("chat.message.actions.report"), style: .default, handler: { (_) in
self.report(message: message)
}))
alert.addAction(UIAlertAction(title: localized("chat.message.actions.block"), style: .default, handler: { [weak self] (_) in
guard let user = message.user else { return }
DispatchQueue.main.async {
self?.messageManager.blockMessagesFrom(user, completion: {
self?.updateSubscriptionInfo()
})
}
}))
alert.addAction(UIAlertAction(title: localized("chat.message.actions.copy"), style: .default, handler: { (_) in
UIPasteboard.general.string = message.text
}))
alert.addAction(UIAlertAction(title: localized("global.cancel"), style: .cancel, handler: nil))
if let presenter = alert.popoverPresentationController {
presenter.sourceView = view
presenter.sourceRect = view.bounds
}
present(alert, animated: true, completion: nil)
}
// MARK: Actions
fileprivate func report(message: Message) {
messageManager.report(message) { (_) in
let alert = UIAlertController(
title: localized("chat.message.report.success.title"),
message: localized("chat.message.report.success.message"),
preferredStyle: .alert
)
alert.addAction(UIAlertAction(title: localized("global.ok"), style: .default, handler: nil))
self.present(alert, animated: true, completion: nil)
}
}
}
| c16e9ecb8225c3569a22a58394b264d8 | 34.666667 | 132 | 0.595016 | false | false | false | false |
Kinglioney/DouYuTV | refs/heads/master | DouYuTV/DouYuTV/Classes/Tools/Extension/UIBarButtonItem-Extension.swift | mit | 1 | //
// UIBarButtonItem-Extension.swift
// DouYuTV
//
// Created by apple on 2017/7/17.
// Copyright © 2017年 apple. All rights reserved.
//
import UIKit
extension UIBarButtonItem{
/*
类方法扩展
class func createItem(imageName : String, highImageName : String, size : CGSize) -> UIBarButtonItem {
let btn = UIButton()
btn.setImage(UIImage(named:imageName), for: .normal)
btn.setImage(UIImage(named:highImageName), for: .highlighted)
btn.frame = CGRect(origin: CGPoint(x:0, y:0), size: size)
return UIBarButtonItem(customView: btn)
}
*/
//Swift中推荐使用构造函数
//便利构造函数:1>convenience开头 2>在构造函数中必须明确调用一个设计的构造函数(self)
convenience init(imageName : String, highImageName : String = "", size : CGSize = CGSize.zero){
let btn = UIButton()
btn.setImage(UIImage(named:imageName), for: .normal)
if highImageName != ""{
btn.setImage(UIImage(named:highImageName), for: .highlighted)
}
if size == CGSize.zero{
btn.sizeToFit()
}else{
btn.frame = CGRect(origin: CGPoint.zero, size: size)
}
self.init(customView: btn)
}
}
| 5c40bb73dc463e12bf2ecf483cf94c05 | 27.658537 | 105 | 0.622979 | false | false | false | false |
donnywdavis/Word-Jive | refs/heads/master | WordJive/WordJive/BackEndRequests.swift | cc0-1.0 | 1 | //
// BackEndRequests.swift
// WordJive
//
// Created by Nick Perkins on 5/17/16.
// Copyright © 2016 Donny Davis. All rights reserved.
//
import Foundation
protocol CapabilitiesDelegate: class {
func availableCapabilities(data: [[String: String]])
}
protocol PuzzleDelegate: class {
func puzzleData(data: NSData)
}
enum BackEndURLs : String {
case Capabilities = "https://floating-taiga-20677.herokuapp.com/capabilities"
case Puzzle = "https://floating-taiga-20677.herokuapp.com/puzzle"
}
class BackEndRequests : AnyObject {
weak static var delegate: CapabilitiesDelegate?
weak static var puzzleDelegate: PuzzleDelegate?
class func getCapabilities() {
startSession(BackEndURLs.Capabilities, gameOptions: nil)
}
class func getPuzzle(gameOptions: [String: AnyObject]) {
startSession(BackEndURLs.Puzzle, gameOptions: gameOptions)
}
private class func startSession(urlString: BackEndURLs, gameOptions: [String: AnyObject]?) {
let url = NSURL(string: urlString.rawValue)
let urlRequest = NSMutableURLRequest(URL: url!)
let session = NSURLSession.sharedSession()
if urlString == .Puzzle {
if let gameOptions = gameOptions {
do {
urlRequest.HTTPBody = try NSJSONSerialization.dataWithJSONObject(gameOptions, options: .PrettyPrinted)
} catch {
urlRequest.HTTPBody = NSData()
}
}
urlRequest.HTTPMethod = "POST"
urlRequest.addValue("application/json", forHTTPHeaderField: "Content-Type")
urlRequest.addValue("application/json", forHTTPHeaderField: "Accept")
}
let task = session.dataTaskWithRequest(urlRequest) {
(data, response, error) -> Void in
let httpResponse = response as! NSHTTPURLResponse
let statusCode = httpResponse.statusCode
let urlValue = httpResponse.URL?.absoluteString
if (statusCode == 200) {
parseData(data!, urlString: urlValue!)
} else {
print("We did not get a response back. Not good. Status code: \(statusCode).")
}
}
task.resume()
}
private class func parseData(data: NSData, urlString: String) {
switch urlString {
case BackEndURLs.Capabilities.rawValue:
do {
let parsedData = try NSJSONSerialization.JSONObjectWithData(data, options: .AllowFragments) as? [[String: String]]
delegate?.availableCapabilities(parsedData!)
} catch {
print("Uh oh!")
}
case BackEndURLs.Puzzle.rawValue:
puzzleDelegate?.puzzleData(data)
// do {
//// let parsedData = try NSJSONSerialization.JSONObjectWithData(data, options: .AllowFragments) as? [String: AnyObject]
// puzzleDelegate?.puzzleData(data)
// } catch {
// print("Uh oh!")
// }
default:
break
}
}
}
| ce72728c2807b2407bc59fcb5ad6e3bd | 31.24 | 135 | 0.586538 | false | false | false | false |
wmcginty/Shifty | refs/heads/main | Examples/Shifty-iOSExample/Animators/ContinuityTransitionAnimator.swift | mit | 1 | //
// SimpleShiftAnimator.swift
// Shifty
//
// Created by William McGinty on 7/6/16.
// Copyright © 2016 Will McGinty. All rights reserved.
//
import UIKit
import Shifty
/** An example UIViewControllerAnimatedTransitioning object designed to make movement between similar screens seamless, appearing
as a single screen. This animator functions in many scenarios, but functions best with view controllers with similar backgrounds. */
class ContinuityTransitionAnimator: NSObject, UIViewControllerAnimatedTransitioning {
// MARK: - UIViewControllerAnimatedTransitioning
func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
return 0.3
}
func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
/** Begin by ensuring the transitionContext is configured correctly, and that our source + destination can power the transition.
This being a basic example - exit if this fails, no fallbacks. YMMV with more complicated examples. */
let container = transitionContext.containerView
guard let sourceController = transitionContext.viewController(forKey: .from), let destinationController = transitionContext.viewController(forKey: .to) else { return }
//Next, add and position the destinationView ABOVE the sourceView
container.addSubview(destinationController.view)
destinationController.view.frame = transitionContext.finalFrame(for: destinationController)
/** Next, we will create a source animator, and instruct it to animate. This will gather all the subviews of `source` with associated `actions` and
animate them simultaneously using the options specified to the animator. As soon as the source's actions have completed, the transition can finish. */
let sourceAnimator = ActionAnimator(timingProvider: CubicTimingProvider(duration: transitionDuration(using: transitionContext), curve: .easeIn))
sourceAnimator.animateActions(from: sourceController.view, in: container) { position in
transitionContext.completeTransition(position == .end)
}
let destinationAnimator = sourceAnimator.inverted()
destinationAnimator.animateActions(from: destinationController.view, in: container)
}
}
| da6b646fd2b697059aac80a5d6d927a9 | 54.372093 | 175 | 0.746325 | false | false | false | false |
CodaFi/swift | refs/heads/main | test/SILGen/builtins.swift | apache-2.0 | 12 | // RUN: %target-swift-emit-silgen -parse-stdlib %s -disable-access-control -disable-objc-attr-requires-foundation-module -enable-objc-interop | %FileCheck %s
// RUN: %target-swift-emit-sil -Onone -parse-stdlib %s -disable-access-control -disable-objc-attr-requires-foundation-module -enable-objc-interop | %FileCheck -check-prefix=CANONICAL %s
import Swift
protocol ClassProto : class { }
struct Pointer {
var value: Builtin.RawPointer
}
// CHECK-LABEL: sil hidden [ossa] @$s8builtins3foo{{[_0-9a-zA-Z]*}}F
func foo(_ x: Builtin.Int1, y: Builtin.Int1) -> Builtin.Int1 {
// CHECK: builtin "cmp_eq_Int1"
return Builtin.cmp_eq_Int1(x, y)
}
// CHECK-LABEL: sil hidden [ossa] @$s8builtins8load_pod{{[_0-9a-zA-Z]*}}F
func load_pod(_ x: Builtin.RawPointer) -> Builtin.Int64 {
// CHECK: [[ADDR:%.*]] = pointer_to_address {{%.*}} to [strict] $*Builtin.Int64
// CHECK: [[VAL:%.*]] = load [trivial] [[ADDR]]
// CHECK: return [[VAL]]
return Builtin.load(x)
}
// CHECK-LABEL: sil hidden [ossa] @$s8builtins8load_obj{{[_0-9a-zA-Z]*}}F
func load_obj(_ x: Builtin.RawPointer) -> Builtin.NativeObject {
// CHECK: [[ADDR:%.*]] = pointer_to_address {{%.*}} to [strict] $*Builtin.NativeObject
// CHECK: [[VAL:%.*]] = load [copy] [[ADDR]]
// CHECK: return [[VAL]]
return Builtin.load(x)
}
// CHECK-LABEL: sil hidden [ossa] @$s8builtins12load_raw_pod{{[_0-9a-zA-Z]*}}F
func load_raw_pod(_ x: Builtin.RawPointer) -> Builtin.Int64 {
// CHECK: [[ADDR:%.*]] = pointer_to_address {{%.*}} to $*Builtin.Int64
// CHECK: [[VAL:%.*]] = load [trivial] [[ADDR]]
// CHECK: return [[VAL]]
return Builtin.loadRaw(x)
}
// CHECK-LABEL: sil hidden [ossa] @$s8builtins12load_raw_obj{{[_0-9a-zA-Z]*}}F
func load_raw_obj(_ x: Builtin.RawPointer) -> Builtin.NativeObject {
// CHECK: [[ADDR:%.*]] = pointer_to_address {{%.*}} to $*Builtin.NativeObject
// CHECK: [[VAL:%.*]] = load [copy] [[ADDR]]
// CHECK: return [[VAL]]
return Builtin.loadRaw(x)
}
// CHECK-LABEL: sil hidden [ossa] @$s8builtins18load_invariant_pod{{[_0-9a-zA-Z]*}}F
func load_invariant_pod(_ x: Builtin.RawPointer) -> Builtin.Int64 {
// CHECK: [[ADDR:%.*]] = pointer_to_address {{%.*}} to [invariant] $*Builtin.Int64
// CHECK: [[VAL:%.*]] = load [trivial] [[ADDR]]
// CHECK: return [[VAL]]
return Builtin.loadInvariant(x)
}
// CHECK-LABEL: sil hidden [ossa] @$s8builtins18load_invariant_obj{{[_0-9a-zA-Z]*}}F
func load_invariant_obj(_ x: Builtin.RawPointer) -> Builtin.NativeObject {
// CHECK: [[ADDR:%.*]] = pointer_to_address {{%.*}} to [invariant] $*Builtin.NativeObject
// CHECK: [[VAL:%.*]] = load [copy] [[ADDR]]
// CHECK: return [[VAL]]
return Builtin.loadInvariant(x)
}
// CHECK-LABEL: sil hidden [ossa] @$s8builtins8load_gen{{[_0-9a-zA-Z]*}}F
func load_gen<T>(_ x: Builtin.RawPointer) -> T {
// CHECK: [[ADDR:%.*]] = pointer_to_address {{%.*}} to [strict] $*T
// CHECK: copy_addr [[ADDR]] to [initialization] {{%.*}}
return Builtin.load(x)
}
// CHECK-LABEL: sil hidden [ossa] @$s8builtins8move_pod{{[_0-9a-zA-Z]*}}F
func move_pod(_ x: Builtin.RawPointer) -> Builtin.Int64 {
// CHECK: [[ADDR:%.*]] = pointer_to_address {{%.*}} to [strict] $*Builtin.Int64
// CHECK: [[VAL:%.*]] = load [trivial] [[ADDR]]
// CHECK: return [[VAL]]
return Builtin.take(x)
}
// CHECK-LABEL: sil hidden [ossa] @$s8builtins8move_obj{{[_0-9a-zA-Z]*}}F
func move_obj(_ x: Builtin.RawPointer) -> Builtin.NativeObject {
// CHECK: [[ADDR:%.*]] = pointer_to_address {{%.*}} to [strict] $*Builtin.NativeObject
// CHECK: [[VAL:%.*]] = load [take] [[ADDR]]
// CHECK-NOT: copy_value [[VAL]]
// CHECK: return [[VAL]]
return Builtin.take(x)
}
// CHECK-LABEL: sil hidden [ossa] @$s8builtins8move_gen{{[_0-9a-zA-Z]*}}F
func move_gen<T>(_ x: Builtin.RawPointer) -> T {
// CHECK: [[ADDR:%.*]] = pointer_to_address {{%.*}} to [strict] $*T
// CHECK: copy_addr [take] [[ADDR]] to [initialization] {{%.*}}
return Builtin.take(x)
}
// CHECK-LABEL: sil hidden [ossa] @$s8builtins11destroy_pod{{[_0-9a-zA-Z]*}}F
func destroy_pod(_ x: Builtin.RawPointer) {
var x = x
// CHECK: [[XBOX:%[0-9]+]] = alloc_box
// CHECK-NOT: pointer_to_address
// CHECK-NOT: destroy_addr
// CHECK-NOT: destroy_value
// CHECK: destroy_value [[XBOX]] : ${{.*}}{
// CHECK-NOT: destroy_value
return Builtin.destroy(Builtin.Int64.self, x)
// CHECK: return
}
// CHECK-LABEL: sil hidden [ossa] @$s8builtins11destroy_obj{{[_0-9a-zA-Z]*}}F
func destroy_obj(_ x: Builtin.RawPointer) {
// CHECK: [[ADDR:%.*]] = pointer_to_address {{%.*}} to [strict] $*Builtin.NativeObject
// CHECK: destroy_addr [[ADDR]]
return Builtin.destroy(Builtin.NativeObject.self, x)
}
// CHECK-LABEL: sil hidden [ossa] @$s8builtins11destroy_gen{{[_0-9a-zA-Z]*}}F
func destroy_gen<T>(_ x: Builtin.RawPointer, _: T) {
// CHECK: [[ADDR:%.*]] = pointer_to_address {{%.*}} to [strict] $*T
// CHECK: destroy_addr [[ADDR]]
return Builtin.destroy(T.self, x)
}
// CHECK-LABEL: sil hidden [ossa] @$s8builtins10assign_pod{{[_0-9a-zA-Z]*}}F
func assign_pod(_ x: Builtin.Int64, y: Builtin.RawPointer) {
var x = x
var y = y
// CHECK: alloc_box
// CHECK: alloc_box
// CHECK-NOT: alloc_box
// CHECK: [[ADDR:%.*]] = pointer_to_address {{%.*}} to [strict] $*Builtin.Int64
// CHECK-NOT: load [[ADDR]]
// CHECK: assign {{%.*}} to [[ADDR]]
// CHECK: destroy_value
// CHECK: destroy_value
// CHECK-NOT: destroy_value
Builtin.assign(x, y)
// CHECK: return
}
// CHECK-LABEL: sil hidden [ossa] @$s8builtins10assign_obj{{[_0-9a-zA-Z]*}}F
func assign_obj(_ x: Builtin.NativeObject, y: Builtin.RawPointer) {
// CHECK: [[ADDR:%.*]] = pointer_to_address {{%.*}} to [strict] $*Builtin.NativeObject
// CHECK: assign {{%.*}} to [[ADDR]]
// CHECK-NOT: destroy_value
Builtin.assign(x, y)
}
// CHECK-LABEL: sil hidden [ossa] @$s8builtins12assign_tuple{{[_0-9a-zA-Z]*}}F
func assign_tuple(_ x: (Builtin.Int64, Builtin.NativeObject),
y: Builtin.RawPointer) {
var x = x
var y = y
// CHECK: [[ADDR:%.*]] = pointer_to_address {{%.*}} to [strict] $*(Builtin.Int64, Builtin.NativeObject)
// CHECK: [[T0:%.*]] = tuple_element_addr [[ADDR]]
// CHECK: assign {{%.*}} to [[T0]]
// CHECK: [[T0:%.*]] = tuple_element_addr [[ADDR]]
// CHECK: assign {{%.*}} to [[T0]]
// CHECK: destroy_value
Builtin.assign(x, y)
}
// CHECK-LABEL: sil hidden [ossa] @$s8builtins10assign_gen{{[_0-9a-zA-Z]*}}F
func assign_gen<T>(_ x: T, y: Builtin.RawPointer) {
// CHECK: [[ADDR:%.*]] = pointer_to_address {{%.*}} to [strict] $*T
// CHECK: copy_addr [take] {{%.*}} to [[ADDR]] :
Builtin.assign(x, y)
}
// CHECK-LABEL: sil hidden [ossa] @$s8builtins8init_pod{{[_0-9a-zA-Z]*}}F
func init_pod(_ x: Builtin.Int64, y: Builtin.RawPointer) {
// CHECK: [[ADDR:%.*]] = pointer_to_address {{%.*}} to [strict] $*Builtin.Int64
// CHECK-NOT: load [[ADDR]]
// CHECK: store {{%.*}} to [trivial] [[ADDR]]
// CHECK-NOT: destroy_value [[ADDR]]
Builtin.initialize(x, y)
}
// CHECK-LABEL: sil hidden [ossa] @$s8builtins8init_obj{{[_0-9a-zA-Z]*}}F
func init_obj(_ x: Builtin.NativeObject, y: Builtin.RawPointer) {
// CHECK: [[ADDR:%.*]] = pointer_to_address {{%.*}} to [strict] $*Builtin.NativeObject
// CHECK-NOT: load [[ADDR]]
// CHECK: store [[SRC:%.*]] to [init] [[ADDR]]
// CHECK-NOT: destroy_value [[SRC]]
Builtin.initialize(x, y)
}
// CHECK-LABEL: sil hidden [ossa] @$s8builtins8init_gen{{[_0-9a-zA-Z]*}}F
func init_gen<T>(_ x: T, y: Builtin.RawPointer) {
// CHECK: [[ADDR:%.*]] = pointer_to_address {{%.*}} to [strict] $*T
// CHECK: copy_addr [[OTHER_LOC:%.*]] to [initialization] [[ADDR]]
// CHECK-NOT: destroy_addr [[OTHER_LOC]]
Builtin.initialize(x, y)
}
class C {}
class D {}
// CHECK-LABEL: sil hidden [ossa] @$s8builtins22class_to_native_object{{[_0-9a-zA-Z]*}}F
// CHECK: bb0([[ARG:%.*]] : @guaranteed $C):
// CHECK-NEXT: debug_value
// CHECK-NEXT: [[ARG_COPY:%.*]] = copy_value [[ARG]]
// CHECK-NEXT: [[OBJ:%.*]] = unchecked_ref_cast [[ARG_COPY]] : $C to $Builtin.NativeObject
// CHECK-NEXT: return [[OBJ]]
func class_to_native_object(_ c:C) -> Builtin.NativeObject {
return Builtin.castToNativeObject(c)
}
// CHECK-LABEL: sil hidden [ossa] @$s8builtins32class_archetype_to_native_object{{[_0-9a-zA-Z]*}}F
func class_archetype_to_native_object<T : C>(_ t: T) -> Builtin.NativeObject {
// CHECK: [[COPY:%.*]] = copy_value %0
// CHECK: [[OBJ:%.*]] = unchecked_ref_cast [[COPY]] : $T to $Builtin.NativeObject
// CHECK-NOT: destroy_value [[COPY]]
// CHECK-NOT: destroy_value [[OBJ]]
// CHECK: return [[OBJ]]
return Builtin.castToNativeObject(t)
}
// CHECK-LABEL: sil hidden [ossa] @$s8builtins34class_existential_to_native_object{{[_0-9a-zA-Z]*}}F
// CHECK: bb0([[ARG:%.*]] : @guaranteed $ClassProto):
// CHECK-NEXT: debug_value
// CHECK-NEXT: [[ARG_COPY:%.*]] = copy_value [[ARG]]
// CHECK-NEXT: [[REF:%[0-9]+]] = open_existential_ref [[ARG_COPY]] : $ClassProto
// CHECK-NEXT: [[PTR:%[0-9]+]] = unchecked_ref_cast [[REF]] : $@opened({{.*}}) ClassProto to $Builtin.NativeObject
// CHECK-NEXT: return [[PTR]]
func class_existential_to_native_object(_ t:ClassProto) -> Builtin.NativeObject {
return Builtin.unsafeCastToNativeObject(t)
}
// CHECK-LABEL: sil hidden [ossa] @$s8builtins24class_from_native_object{{[_0-9a-zA-Z]*}}F
func class_from_native_object(_ p: Builtin.NativeObject) -> C {
// CHECK: [[COPY:%.*]] = copy_value %0
// CHECK: [[CAST:%.*]] = unchecked_ref_cast [[COPY]] : $Builtin.NativeObject to $C
// CHECK-NOT: destroy_value [[COPY]]
// CHECK-NOT: destroy_value [[CAST]]
// CHECK: return [[CAST]]
return Builtin.castFromNativeObject(p)
}
// CHECK-LABEL: sil hidden [ossa] @$s8builtins34class_archetype_from_native_object{{[_0-9a-zA-Z]*}}F
func class_archetype_from_native_object<T : C>(_ p: Builtin.NativeObject) -> T {
// CHECK: [[COPY:%.*]] = copy_value %0
// CHECK: [[CAST:%.*]] = unchecked_ref_cast [[COPY]] : $Builtin.NativeObject to $T
// CHECK-NOT: destroy_value [[COPY]]
// CHECK-NOT: destroy_value [[CAST]]
// CHECK: return [[CAST]]
return Builtin.castFromNativeObject(p)
}
// CHECK-LABEL: sil hidden [ossa] @$s8builtins41objc_class_existential_from_native_object{{[_0-9a-zA-Z]*}}F
func objc_class_existential_from_native_object(_ p: Builtin.NativeObject) -> AnyObject {
// CHECK: [[COPY:%.*]] = copy_value %0
// CHECK: [[CAST:%.*]] = unchecked_ref_cast [[COPY]] : $Builtin.NativeObject to $AnyObject
// CHECK-NOT: destroy_value [[COPY]]
// CHECK-NOT: destroy_value [[CAST]]
// CHECK: return [[CAST]]
return Builtin.castFromNativeObject(p)
}
// CHECK-LABEL: sil hidden [ossa] @$s8builtins20class_to_raw_pointer{{[_0-9a-zA-Z]*}}F
func class_to_raw_pointer(_ c: C) -> Builtin.RawPointer {
// CHECK: [[RAW:%.*]] = ref_to_raw_pointer [[C:%.*]] to $Builtin.RawPointer
// CHECK: return [[RAW]]
return Builtin.bridgeToRawPointer(c)
}
func class_archetype_to_raw_pointer<T : C>(_ t: T) -> Builtin.RawPointer {
return Builtin.bridgeToRawPointer(t)
}
protocol CP: class {}
func existential_to_raw_pointer(_ p: CP) -> Builtin.RawPointer {
return Builtin.bridgeToRawPointer(p)
}
// CHECK-LABEL: sil hidden [ossa] @$s8builtins18obj_to_raw_pointer{{[_0-9a-zA-Z]*}}F
func obj_to_raw_pointer(_ c: Builtin.NativeObject) -> Builtin.RawPointer {
// CHECK: [[RAW:%.*]] = ref_to_raw_pointer [[C:%.*]] to $Builtin.RawPointer
// CHECK: return [[RAW]]
return Builtin.bridgeToRawPointer(c)
}
// CHECK-LABEL: sil hidden [ossa] @$s8builtins22class_from_raw_pointer{{[_0-9a-zA-Z]*}}F
func class_from_raw_pointer(_ p: Builtin.RawPointer) -> C {
// CHECK: [[C:%.*]] = raw_pointer_to_ref [[RAW:%.*]] to $C
// CHECK: [[C_COPY:%.*]] = copy_value [[C]]
// CHECK: return [[C_COPY]]
return Builtin.bridgeFromRawPointer(p)
}
func class_archetype_from_raw_pointer<T : C>(_ p: Builtin.RawPointer) -> T {
return Builtin.bridgeFromRawPointer(p)
}
// CHECK-LABEL: sil hidden [ossa] @$s8builtins20obj_from_raw_pointer{{[_0-9a-zA-Z]*}}F
func obj_from_raw_pointer(_ p: Builtin.RawPointer) -> Builtin.NativeObject {
// CHECK: [[C:%.*]] = raw_pointer_to_ref [[RAW:%.*]] to $Builtin.NativeObject
// CHECK: [[C_COPY:%.*]] = copy_value [[C]]
// CHECK: return [[C_COPY]]
return Builtin.bridgeFromRawPointer(p)
}
// CHECK-LABEL: sil hidden [ossa] @$s8builtins28existential_from_raw_pointer{{[_0-9a-zA-Z]*}}F
func existential_from_raw_pointer(_ p: Builtin.RawPointer) -> AnyObject {
// CHECK: [[C:%.*]] = raw_pointer_to_ref [[RAW:%.*]] to $AnyObject
// CHECK: [[C_COPY:%.*]] = copy_value [[C]]
// CHECK: return [[C_COPY]]
return Builtin.bridgeFromRawPointer(p)
}
// CHECK-LABEL: sil hidden [ossa] @$s8builtins9gep_raw64{{[_0-9a-zA-Z]*}}F
func gep_raw64(_ p: Builtin.RawPointer, i: Builtin.Int64) -> Builtin.RawPointer {
// CHECK: [[GEP:%.*]] = index_raw_pointer
// CHECK: return [[GEP]]
return Builtin.gepRaw_Int64(p, i)
}
// CHECK-LABEL: sil hidden [ossa] @$s8builtins9gep_raw32{{[_0-9a-zA-Z]*}}F
func gep_raw32(_ p: Builtin.RawPointer, i: Builtin.Int32) -> Builtin.RawPointer {
// CHECK: [[GEP:%.*]] = index_raw_pointer
// CHECK: return [[GEP]]
return Builtin.gepRaw_Int32(p, i)
}
// CHECK-LABEL: sil hidden [ossa] @$s8builtins3gep{{[_0-9a-zA-Z]*}}F
func gep<Elem>(_ p: Builtin.RawPointer, i: Builtin.Word, e: Elem.Type) -> Builtin.RawPointer {
// CHECK: [[P2A:%.*]] = pointer_to_address %0
// CHECK: [[GEP:%.*]] = index_addr [[P2A]] : $*Elem, %1 : $Builtin.Word
// CHECK: [[A2P:%.*]] = address_to_pointer [[GEP]]
// CHECK: return [[A2P]]
return Builtin.gep_Word(p, i, e)
}
public final class Header { }
// CHECK-LABEL: sil hidden [ossa] @$s8builtins20allocWithTailElems_1{{[_0-9a-zA-Z]*}}F
func allocWithTailElems_1<T>(n: Builtin.Word, ty: T.Type) -> Header {
// CHECK: [[M:%.*]] = metatype $@thick Header.Type
// CHECK: [[A:%.*]] = alloc_ref [tail_elems $T * %0 : $Builtin.Word] $Header
// CHECK: return [[A]]
return Builtin.allocWithTailElems_1(Header.self, n, ty)
}
// CHECK-LABEL: sil hidden [ossa] @$s8builtins20allocWithTailElems_3{{[_0-9a-zA-Z]*}}F
func allocWithTailElems_3<T1, T2, T3>(n1: Builtin.Word, ty1: T1.Type, n2: Builtin.Word, ty2: T2.Type, n3: Builtin.Word, ty3: T3.Type) -> Header {
// CHECK: [[M:%.*]] = metatype $@thick Header.Type
// CHECK: [[A:%.*]] = alloc_ref [tail_elems $T1 * %0 : $Builtin.Word] [tail_elems $T2 * %2 : $Builtin.Word] [tail_elems $T3 * %4 : $Builtin.Word] $Header
// CHECK: return [[A]]
return Builtin.allocWithTailElems_3(Header.self, n1, ty1, n2, ty2, n3, ty3)
}
// CHECK-LABEL: sil hidden [ossa] @$s8builtins16projectTailElems{{[_0-9a-zA-Z]*}}F
func projectTailElems<T>(h: Header, ty: T.Type) -> Builtin.RawPointer {
// CHECK: bb0([[ARG1:%.*]] : @guaranteed $Header
// CHECK: [[TA:%.*]] = ref_tail_addr [[ARG1]] : $Header
// CHECK: [[A2P:%.*]] = address_to_pointer [[TA]]
// CHECK: return [[A2P]]
return Builtin.projectTailElems(h, ty)
}
// CHECK: } // end sil function '$s8builtins16projectTailElems1h2tyBpAA6HeaderC_xmtlF'
// Make sure we borrow if this is owned.
//
// CHECK-LABEL: sil hidden [ossa] @$s8builtins21projectTailElemsOwned{{[_0-9a-zA-Z]*}}F
func projectTailElemsOwned<T>(h: __owned Header, ty: T.Type) -> Builtin.RawPointer {
// CHECK: bb0([[ARG1:%.*]] : @owned $Header
// CHECK: [[BORROWED_ARG1:%.*]] = begin_borrow [[ARG1]]
// CHECK: [[TA:%.*]] = ref_tail_addr [[BORROWED_ARG1]] : $Header
// -- Once we have passed the address through a2p, we no longer provide any guarantees.
// -- We still need to make sure that the a2p itself is in the borrow site though.
// CHECK: [[A2P:%.*]] = address_to_pointer [[TA]]
// CHECK: end_borrow [[BORROWED_ARG1]]
// CHECK: destroy_value [[ARG1]]
// CHECK: return [[A2P]]
return Builtin.projectTailElems(h, ty)
}
// CHECK: } // end sil function '$s8builtins21projectTailElemsOwned{{[_0-9a-zA-Z]*}}F'
// CHECK-LABEL: sil hidden [ossa] @$s8builtins11getTailAddr{{[_0-9a-zA-Z]*}}F
func getTailAddr<T1, T2>(start: Builtin.RawPointer, i: Builtin.Word, ty1: T1.Type, ty2: T2.Type) -> Builtin.RawPointer {
// CHECK: [[P2A:%.*]] = pointer_to_address %0
// CHECK: [[TA:%.*]] = tail_addr [[P2A]] : $*T1, %1 : $Builtin.Word, $T2
// CHECK: [[A2P:%.*]] = address_to_pointer [[TA]]
// CHECK: return [[A2P]]
return Builtin.getTailAddr_Word(start, i, ty1, ty2)
}
// CHECK-LABEL: sil hidden [ossa] @$s8builtins25beginUnpairedModifyAccess{{[_0-9a-zA-Z]*}}F
func beginUnpairedModifyAccess<T1>(address: Builtin.RawPointer, scratch: Builtin.RawPointer, ty1: T1.Type) {
// CHECK: [[P2A_ADDR:%.*]] = pointer_to_address %0
// CHECK: [[P2A_SCRATCH:%.*]] = pointer_to_address %1
// CHECK: begin_unpaired_access [modify] [dynamic] [builtin] [[P2A_ADDR]] : $*T1, [[P2A_SCRATCH]] : $*Builtin.UnsafeValueBuffer
// CHECK: [[RESULT:%.*]] = tuple ()
// CHECK: [[RETURN:%.*]] = tuple ()
// CHECK: return [[RETURN]] : $()
Builtin.beginUnpairedModifyAccess(address, scratch, ty1);
}
// CHECK-LABEL: sil hidden [ossa] @$s8builtins30performInstantaneousReadAccess{{[_0-9a-zA-Z]*}}F
func performInstantaneousReadAccess<T1>(address: Builtin.RawPointer, scratch: Builtin.RawPointer, ty1: T1.Type) {
// CHECK: [[P2A_ADDR:%.*]] = pointer_to_address %0
// CHECK: [[SCRATCH:%.*]] = alloc_stack $Builtin.UnsafeValueBuffer
// CHECK: begin_unpaired_access [read] [dynamic] [no_nested_conflict] [builtin] [[P2A_ADDR]] : $*T1, [[SCRATCH]] : $*Builtin.UnsafeValueBuffer
// CHECK-NOT: end_{{.*}}access
// CHECK: [[RESULT:%.*]] = tuple ()
// CHECK: [[RETURN:%.*]] = tuple ()
// CHECK: return [[RETURN]] : $()
Builtin.performInstantaneousReadAccess(address, ty1);
}
// CHECK-LABEL: sil hidden [ossa] @$s8builtins15legacy_condfail{{[_0-9a-zA-Z]*}}F
func legacy_condfail(_ i: Builtin.Int1) {
Builtin.condfail(i)
// CHECK: cond_fail {{%.*}} : $Builtin.Int1, "unknown runtime failure"
}
// CHECK-LABEL: sil hidden [ossa] @$s8builtins8condfail{{[_0-9a-zA-Z]*}}F
func condfail(_ i: Builtin.Int1) {
Builtin.condfail_message(i, StaticString("message").unsafeRawPointer)
// CHECK: builtin "condfail_message"({{%.*}} : $Builtin.Int1, {{%.*}} : $Builtin.RawPointer) : $()
}
struct S {}
@objc class O {}
@objc protocol OP1 {}
@objc protocol OP2 {}
protocol P {}
// CHECK-LABEL: sil hidden [ossa] @$s8builtins10canBeClass{{[_0-9a-zA-Z]*}}F
func canBeClass<T>(_: T) {
// CHECK: integer_literal $Builtin.Int8, 1
Builtin.canBeClass(O.self)
// CHECK: integer_literal $Builtin.Int8, 1
Builtin.canBeClass(OP1.self)
// -- FIXME: 'OP1 & OP2' doesn't parse as a value
typealias ObjCCompo = OP1 & OP2
// CHECK: integer_literal $Builtin.Int8, 1
Builtin.canBeClass(ObjCCompo.self)
// CHECK: integer_literal $Builtin.Int8, 0
Builtin.canBeClass(S.self)
// CHECK: integer_literal $Builtin.Int8, 1
Builtin.canBeClass(C.self)
// CHECK: integer_literal $Builtin.Int8, 0
Builtin.canBeClass(P.self)
typealias MixedCompo = OP1 & P
// CHECK: integer_literal $Builtin.Int8, 0
Builtin.canBeClass(MixedCompo.self)
// CHECK: builtin "canBeClass"<T>
Builtin.canBeClass(T.self)
}
// FIXME: "T.Type.self" does not parse as an expression
// CHECK-LABEL: sil hidden [ossa] @$s8builtins18canBeClassMetatype{{[_0-9a-zA-Z]*}}F
func canBeClassMetatype<T>(_: T) {
// CHECK: integer_literal $Builtin.Int8, 0
typealias OT = O.Type
Builtin.canBeClass(OT.self)
// CHECK: integer_literal $Builtin.Int8, 0
typealias OP1T = OP1.Type
Builtin.canBeClass(OP1T.self)
// -- FIXME: 'OP1 & OP2' doesn't parse as a value
typealias ObjCCompoT = (OP1 & OP2).Type
// CHECK: integer_literal $Builtin.Int8, 0
Builtin.canBeClass(ObjCCompoT.self)
// CHECK: integer_literal $Builtin.Int8, 0
typealias ST = S.Type
Builtin.canBeClass(ST.self)
// CHECK: integer_literal $Builtin.Int8, 0
typealias CT = C.Type
Builtin.canBeClass(CT.self)
// CHECK: integer_literal $Builtin.Int8, 0
typealias PT = P.Type
Builtin.canBeClass(PT.self)
typealias MixedCompoT = (OP1 & P).Type
// CHECK: integer_literal $Builtin.Int8, 0
Builtin.canBeClass(MixedCompoT.self)
// CHECK: integer_literal $Builtin.Int8, 0
typealias TT = T.Type
Builtin.canBeClass(TT.self)
}
// CHECK-LABEL: sil hidden [ossa] @$s8builtins11fixLifetimeyyAA1CCF : $@convention(thin) (@guaranteed C) -> () {
func fixLifetime(_ c: C) {
// CHECK: bb0([[ARG:%.*]] : @guaranteed $C):
// CHECK: fix_lifetime [[ARG]] : $C
Builtin.fixLifetime(c)
}
// CHECK: } // end sil function '$s8builtins11fixLifetimeyyAA1CCF'
// CHECK-LABEL: sil hidden [ossa] @$s8builtins20assert_configuration{{[_0-9a-zA-Z]*}}F
func assert_configuration() -> Builtin.Int32 {
return Builtin.assert_configuration()
// CHECK: [[APPLY:%.*]] = builtin "assert_configuration"() : $Builtin.Int32
// CHECK: return [[APPLY]] : $Builtin.Int32
}
// CHECK-LABEL: sil hidden [ossa] @$s8builtins17assumeNonNegativeyBwBwF
func assumeNonNegative(_ x: Builtin.Word) -> Builtin.Word {
return Builtin.assumeNonNegative_Word(x)
// CHECK: [[APPLY:%.*]] = builtin "assumeNonNegative_Word"(%0 : $Builtin.Word) : $Builtin.Word
// CHECK: return [[APPLY]] : $Builtin.Word
}
// CHECK-LABEL: sil hidden [ossa] @$s8builtins11autoreleaseyyAA1OCF : $@convention(thin) (@guaranteed O) -> () {
// ==> SEMANTIC ARC TODO: This will be unbalanced... should we allow it?
// CHECK: bb0([[ARG:%.*]] : @guaranteed $O):
// CHECK: unmanaged_autorelease_value [[ARG]]
// CHECK: } // end sil function '$s8builtins11autoreleaseyyAA1OCF'
func autorelease(_ o: O) {
Builtin.autorelease(o)
}
// The 'unreachable' builtin is emitted verbatim by SILGen and eliminated during
// diagnostics.
// CHECK-LABEL: sil hidden [ossa] @$s8builtins11unreachable{{[_0-9a-zA-Z]*}}F
// CHECK: builtin "unreachable"()
// CHECK: return
// CANONICAL-LABEL: sil hidden @$s8builtins11unreachableyyF : $@convention(thin) () -> () {
func unreachable() {
Builtin.unreachable()
}
// CHECK-LABEL: sil hidden [ossa] @$s8builtins15reinterpretCast_1xBw_AA1DCAA1CCSgAGtAG_BwtF : $@convention(thin) (@guaranteed C, Builtin.Word) -> (Builtin.Word, @owned D, @owned Optional<C>, @owned C)
// CHECK: bb0([[ARG1:%.*]] : @guaranteed $C, [[ARG2:%.*]] : $Builtin.Word):
// CHECK-NEXT: debug_value
// CHECK-NEXT: debug_value
// CHECK-NEXT: [[ARG1_COPY1:%.*]] = copy_value [[ARG1]]
// CHECK-NEXT: [[ARG1_TRIVIAL:%.*]] = unchecked_trivial_bit_cast [[ARG1_COPY1]] : $C to $Builtin.Word
// CHECK-NEXT: [[ARG1_COPY2:%.*]] = copy_value [[ARG1]]
// CHECK-NEXT: [[ARG1_D:%.*]] = unchecked_ref_cast [[ARG1_COPY2]] : $C to $D
// CHECK-NEXT: [[ARG1_COPY3:%.*]] = copy_value [[ARG1]]
// CHECK-NEXT: [[ARG1_OPT:%.*]] = unchecked_ref_cast [[ARG1_COPY3]] : $C to $Optional<C>
// CHECK-NEXT: [[ARG2_FROM_WORD:%.*]] = unchecked_bitwise_cast [[ARG2]] : $Builtin.Word to $C
// CHECK-NEXT: [[ARG2_FROM_WORD_COPY:%.*]] = copy_value [[ARG2_FROM_WORD]]
// CHECK-NEXT: destroy_value [[ARG1_COPY1]]
// CHECK-NEXT: [[RESULT:%.*]] = tuple ([[ARG1_TRIVIAL]] : $Builtin.Word, [[ARG1_D]] : $D, [[ARG1_OPT]] : $Optional<C>, [[ARG2_FROM_WORD_COPY:%.*]] : $C)
// CHECK: return [[RESULT]]
func reinterpretCast(_ c: C, x: Builtin.Word) -> (Builtin.Word, D, C?, C) {
return (Builtin.reinterpretCast(c) as Builtin.Word,
Builtin.reinterpretCast(c) as D,
Builtin.reinterpretCast(c) as C?,
Builtin.reinterpretCast(x) as C)
}
// CHECK-LABEL: sil hidden [ossa] @$s8builtins19reinterpretAddrOnly{{[_0-9a-zA-Z]*}}F
func reinterpretAddrOnly<T, U>(_ t: T) -> U {
// CHECK: unchecked_addr_cast {{%.*}} : $*T to $*U
return Builtin.reinterpretCast(t)
}
// CHECK-LABEL: sil hidden [ossa] @$s8builtins28reinterpretAddrOnlyToTrivial{{[_0-9a-zA-Z]*}}F
func reinterpretAddrOnlyToTrivial<T>(_ t: T) -> Int {
// CHECK: copy_addr %0 to [initialization] [[INPUT:%.*]] : $*T
// CHECK: [[ADDR:%.*]] = unchecked_addr_cast [[INPUT]] : $*T to $*Int
// CHECK: [[VALUE:%.*]] = load [trivial] [[ADDR]]
// CHECK: destroy_addr [[INPUT]]
return Builtin.reinterpretCast(t)
}
// CHECK-LABEL: sil hidden [ossa] @$s8builtins27reinterpretAddrOnlyLoadable{{[_0-9a-zA-Z]*}}F
func reinterpretAddrOnlyLoadable<T>(_ a: Int, _ b: T) -> (T, Int) {
// CHECK: [[BUF:%.*]] = alloc_stack $Int
// CHECK: store {{%.*}} to [trivial] [[BUF]]
// CHECK: [[RES1:%.*]] = unchecked_addr_cast [[BUF]] : $*Int to $*T
// CHECK: copy_addr [[RES1]] to [initialization]
return (Builtin.reinterpretCast(a) as T,
// CHECK: [[RES:%.*]] = unchecked_addr_cast {{%.*}} : $*T to $*Int
// CHECK: load [trivial] [[RES]]
Builtin.reinterpretCast(b) as Int)
}
// CHECK-LABEL: sil hidden [ossa] @$s8builtins18castToBridgeObject{{[_0-9a-zA-Z]*}}F
// CHECK: [[ARG_COPY:%.*]] = copy_value %0
// CHECK: [[BO:%.*]] = ref_to_bridge_object [[ARG_COPY]] : $C, {{%.*}} : $Builtin.Word
// CHECK-NOT: destroy_value [[ARG_COPY]]
// CHECK: return [[BO]]
func castToBridgeObject(_ c: C, _ w: Builtin.Word) -> Builtin.BridgeObject {
return Builtin.castToBridgeObject(c, w)
}
// CHECK-LABEL: sil hidden [ossa] @$s8builtins23castRefFromBridgeObject{{[_0-9a-zA-Z]*}}F
// CHECK: bridge_object_to_ref [[BO:%.*]] : $Builtin.BridgeObject to $C
func castRefFromBridgeObject(_ bo: Builtin.BridgeObject) -> C {
return Builtin.castReferenceFromBridgeObject(bo)
}
// CHECK-LABEL: sil hidden [ossa] @$s8builtins30castBitPatternFromBridgeObject{{[_0-9a-zA-Z]*}}F
// CHECK: bridge_object_to_word [[BO:%.*]] : $Builtin.BridgeObject to $Builtin.Word
// CHECK-NOT: destroy_value [[BO]]
func castBitPatternFromBridgeObject(_ bo: Builtin.BridgeObject) -> Builtin.Word {
return Builtin.castBitPatternFromBridgeObject(bo)
}
// CHECK-LABEL: sil hidden [ossa] @$s8builtins16beginCOWMutationySbAA1CCzF
// CHECK: [[L:%.*]] = load [take] [[ADDR:%[0-9]*]]
// CHECK: ([[U:%.*]], [[B:%.*]]) = begin_cow_mutation [[L]]
// CHECK: store [[B]] to [init] [[ADDR]]
// CHECK: apply {{%[0-9]*}}([[U]]
func beginCOWMutation(_ c: inout C) -> Bool {
return Bool(_builtinBooleanLiteral: Builtin.beginCOWMutation(&c))
}
// CHECK-LABEL: sil hidden [ossa] @$s8builtins23beginCOWMutation_nativeySbAA1CCzF
// CHECK: [[L:%.*]] = load [take] [[ADDR:%[0-9]*]]
// CHECK: ([[U:%.*]], [[B:%.*]]) = begin_cow_mutation [native] [[L]]
// CHECK: store [[B]] to [init] [[ADDR]]
// CHECK: apply {{%[0-9]*}}([[U]]
func beginCOWMutation_native(_ c: inout C) -> Bool {
return Bool(_builtinBooleanLiteral: Builtin.beginCOWMutation_native(&c))
}
// CHECK-LABEL: sil hidden [ossa] @$s8builtins14endCOWMutationyyAA1CCzF
// CHECK: [[L:%.*]] = load [take] [[ADDR:%[0-9]*]]
// CHECK: [[B:%.*]] = end_cow_mutation [[L]]
// CHECK: store [[B]] to [init] [[ADDR]]
func endCOWMutation(_ c: inout C) {
Builtin.endCOWMutation(&c)
}
// ----------------------------------------------------------------------------
// isUnique variants
// ----------------------------------------------------------------------------
// NativeObject
// CHECK-LABEL: sil hidden [ossa] @$s8builtins8isUnique{{[_0-9a-zA-Z]*}}F
// CHECK: bb0(%0 : $*Optional<Builtin.NativeObject>):
// CHECK: [[WRITE:%.*]] = begin_access [modify] [unknown] %0 : $*Optional<Builtin.NativeObject>
// CHECK: [[BUILTIN:%.*]] = is_unique [[WRITE]] : $*Optional<Builtin.NativeObject>
// CHECK: return
func isUnique(_ ref: inout Builtin.NativeObject?) -> Bool {
return Bool(_builtinBooleanLiteral: Builtin.isUnique(&ref))
}
// NativeObject nonNull
// CHECK-LABEL: sil hidden [ossa] @$s8builtins8isUnique{{[_0-9a-zA-Z]*}}F
// CHECK: bb0(%0 : $*Builtin.NativeObject):
// CHECK: [[WRITE:%.*]] = begin_access [modify] [unknown] %0
// CHECK: [[BUILTIN:%.*]] = is_unique [[WRITE]] : $*Builtin.NativeObject
// CHECK: return
func isUnique(_ ref: inout Builtin.NativeObject) -> Bool {
return Bool(_builtinBooleanLiteral: Builtin.isUnique(&ref))
}
// AnyObject (ObjC)
// CHECK-LABEL: sil hidden [ossa] @$s8builtins8isUnique{{[_0-9a-zA-Z]*}}F
// CHECK: bb0(%0 : $*Optional<AnyObject>):
// CHECK: [[WRITE:%.*]] = begin_access [modify] [unknown] %0
// CHECK: [[BUILTIN:%.*]] = is_unique [[WRITE]] : $*Optional<AnyObject>
// CHECK: return
func isUnique(_ ref: inout Builtin.AnyObject?) -> Bool {
return Bool(_builtinBooleanLiteral: Builtin.isUnique(&ref))
}
// AnyObject (ObjC) nonNull
// CHECK-LABEL: sil hidden [ossa] @$s8builtins8isUnique{{[_0-9a-zA-Z]*}}F
// CHECK: bb0(%0 : $*AnyObject):
// CHECK: [[WRITE:%.*]] = begin_access [modify] [unknown] %0
// CHECK: [[BUILTIN:%.*]] = is_unique [[WRITE]] : $*AnyObject
// CHECK: return
func isUnique(_ ref: inout Builtin.AnyObject) -> Bool {
return Bool(_builtinBooleanLiteral: Builtin.isUnique(&ref))
}
// BridgeObject nonNull
// CHECK-LABEL: sil hidden [ossa] @$s8builtins8isUnique{{[_0-9a-zA-Z]*}}F
// CHECK: bb0(%0 : $*Builtin.BridgeObject):
// CHECK: [[WRITE:%.*]] = begin_access [modify] [unknown] %0
// CHECK: [[BUILTIN:%.*]] = is_unique [[WRITE]] : $*Builtin.BridgeObject
// CHECK: return
func isUnique(_ ref: inout Builtin.BridgeObject) -> Bool {
return Bool(_builtinBooleanLiteral: Builtin.isUnique(&ref))
}
// BridgeObject nonNull native
// CHECK-LABEL: sil hidden [ossa] @$s8builtins15isUnique_native{{[_0-9a-zA-Z]*}}F
// CHECK: bb0(%0 : $*Builtin.BridgeObject):
// CHECK: [[WRITE:%.*]] = begin_access [modify] [unknown] %0
// CHECK: [[CAST:%.*]] = unchecked_addr_cast [[WRITE]] : $*Builtin.BridgeObject to $*Builtin.NativeObject
// CHECK: return
func isUnique_native(_ ref: inout Builtin.BridgeObject) -> Bool {
return Bool(_builtinBooleanLiteral: Builtin.isUnique_native(&ref))
}
// ----------------------------------------------------------------------------
// Builtin.castReference
// ----------------------------------------------------------------------------
class A {}
protocol PUnknown {}
protocol PClass : class {}
// CHECK-LABEL: sil hidden [ossa] @$s8builtins19refcast_generic_any{{[_0-9a-zA-Z]*}}F
// CHECK: unchecked_ref_cast_addr T in %{{.*}} : $*T to AnyObject in %{{.*}} : $*AnyObject
func refcast_generic_any<T>(_ o: T) -> AnyObject {
return Builtin.castReference(o)
}
// CHECK-LABEL: sil hidden [ossa] @$s8builtins17refcast_class_anyyyXlAA1ACF :
// CHECK: bb0([[ARG:%.*]] : @guaranteed $A):
// CHECK: [[ARG_COPY:%.*]] = copy_value [[ARG]]
// CHECK: [[ARG_CASTED:%.*]] = unchecked_ref_cast [[ARG_COPY]] : $A to $AnyObject
// CHECK-NOT: destroy_value [[ARG]]
// CHECK: return [[ARG_CASTED]]
// CHECK: } // end sil function '$s8builtins17refcast_class_anyyyXlAA1ACF'
func refcast_class_any(_ o: A) -> AnyObject {
return Builtin.castReference(o)
}
// CHECK-LABEL: sil hidden [ossa] @$s8builtins20refcast_punknown_any{{[_0-9a-zA-Z]*}}F
// CHECK: unchecked_ref_cast_addr PUnknown in %{{.*}} : $*PUnknown to AnyObject in %{{.*}} : $*AnyObject
func refcast_punknown_any(_ o: PUnknown) -> AnyObject {
return Builtin.castReference(o)
}
// CHECK-LABEL: sil hidden [ossa] @$s8builtins18refcast_pclass_anyyyXlAA6PClass_pF :
// CHECK: bb0([[ARG:%.*]] : @guaranteed $PClass):
// CHECK: [[ARG_COPY:%.*]] = copy_value [[ARG]]
// CHECK: [[ARG_CAST:%.*]] = unchecked_ref_cast [[ARG_COPY]] : $PClass to $AnyObject
// CHECK: return [[ARG_CAST]]
// CHECK: } // end sil function '$s8builtins18refcast_pclass_anyyyXlAA6PClass_pF'
func refcast_pclass_any(_ o: PClass) -> AnyObject {
return Builtin.castReference(o)
}
// CHECK-LABEL: sil hidden [ossa] @$s8builtins20refcast_any_punknown{{[_0-9a-zA-Z]*}}F
// CHECK: unchecked_ref_cast_addr AnyObject in %{{.*}} : $*AnyObject to PUnknown in %{{.*}} : $*PUnknown
func refcast_any_punknown(_ o: AnyObject) -> PUnknown {
return Builtin.castReference(o)
}
// => SEMANTIC ARC TODO: This function is missing a borrow + extract + copy.
//
// CHECK-LABEL: sil hidden [ossa] @$s8builtins22unsafeGuaranteed_class{{[_0-9a-zA-Z]*}}F
// CHECK: bb0([[P:%.*]] : @guaranteed $A):
// CHECK: [[P_COPY:%.*]] = copy_value [[P]]
// CHECK: [[T:%.*]] = builtin "unsafeGuaranteed"<A>([[P_COPY]] : $A)
// CHECK: ([[R:%.*]], [[K:%.*]]) = destructure_tuple [[T]]
// CHECK: destroy_value [[R]]
// CHECK: [[P_COPY:%.*]] = copy_value [[P]]
// CHECK: return [[P_COPY]] : $A
// CHECK: }
func unsafeGuaranteed_class(_ a: A) -> A {
Builtin.unsafeGuaranteed(a)
return a
}
// CHECK-LABEL: $s8builtins24unsafeGuaranteed_generic{{[_0-9a-zA-Z]*}}F
// CHECK: bb0([[P:%.*]] : @guaranteed $T):
// CHECK: [[P_COPY:%.*]] = copy_value [[P]]
// CHECK: [[T:%.*]] = builtin "unsafeGuaranteed"<T>([[P_COPY]] : $T)
// CHECK: ([[R:%.*]], [[K:%.*]]) = destructure_tuple [[T]]
// CHECK: destroy_value [[R]]
// CHECK: [[P_RETURN:%.*]] = copy_value [[P]]
// CHECK: return [[P_RETURN]] : $T
// CHECK: }
func unsafeGuaranteed_generic<T: AnyObject> (_ a: T) -> T {
Builtin.unsafeGuaranteed(a)
return a
}
// CHECK_LABEL: sil hidden [ossa] @$s8builtins31unsafeGuaranteed_generic_return{{[_0-9a-zA-Z]*}}F
// CHECK: bb0([[P:%.*]] : @guaranteed $T):
// CHECK: [[P_COPY:%.*]] = copy_value [[P]]
// CHECK: [[T:%.*]] = builtin "unsafeGuaranteed"<T>([[P_COPY]] : $T)
// CHECK: ([[R:%.*]], [[K:%.*]]) = destructure_tuple [[T]]
// CHECK: [[S:%.*]] = tuple ([[R]] : $T, [[K]] : $Builtin.Int8)
// CHECK: return [[S]] : $(T, Builtin.Int8)
// CHECK: }
func unsafeGuaranteed_generic_return<T: AnyObject> (_ a: T) -> (T, Builtin.Int8) {
return Builtin.unsafeGuaranteed(a)
}
// CHECK-LABEL: sil hidden [ossa] @$s8builtins19unsafeGuaranteedEnd{{[_0-9a-zA-Z]*}}F
// CHECK: bb0([[P:%.*]] : $Builtin.Int8):
// CHECK: builtin "unsafeGuaranteedEnd"([[P]] : $Builtin.Int8)
// CHECK: [[S:%.*]] = tuple ()
// CHECK: return [[S]] : $()
// CHECK: }
func unsafeGuaranteedEnd(_ t: Builtin.Int8) {
Builtin.unsafeGuaranteedEnd(t)
}
// CHECK-LABEL: sil hidden [ossa] @$s8builtins10bindMemory{{[_0-9a-zA-Z]*}}F
// CHECK: bb0([[P:%.*]] : $Builtin.RawPointer, [[I:%.*]] : $Builtin.Word, [[T:%.*]] : $@thick T.Type):
// CHECK: bind_memory [[P]] : $Builtin.RawPointer, [[I]] : $Builtin.Word to $*T
// CHECK: return {{%.*}} : $()
// CHECK: }
func bindMemory<T>(ptr: Builtin.RawPointer, idx: Builtin.Word, _: T.Type) {
Builtin.bindMemory(ptr, idx, T.self)
}
//===----------------------------------------------------------------------===//
// RC Operations
//===----------------------------------------------------------------------===//
// SILGen test:
//
// CHECK-LABEL: sil hidden [ossa] @$s8builtins6retain{{[_0-9a-zA-Z]*}}F : $@convention(thin) (@guaranteed Builtin.NativeObject) -> () {
// CHECK: bb0([[P:%.*]] : @guaranteed $Builtin.NativeObject):
// CHECK: unmanaged_retain_value [[P]]
// CHECK: } // end sil function '$s8builtins6retain{{[_0-9a-zA-Z]*}}F'
// SIL Test. This makes sure that we properly clean up in -Onone SIL.
// CANONICAL-LABEL: sil hidden @$s8builtins6retain{{[_0-9a-zA-Z]*}}F : $@convention(thin) (@guaranteed Builtin.NativeObject) -> () {
// CANONICAL: bb0([[P:%.*]] : $Builtin.NativeObject):
// CANONICAL: strong_retain [[P]]
// CANONICAL-NOT: retain
// CANONICAL-NOT: release
// CANONICAL: } // end sil function '$s8builtins6retain{{[_0-9a-zA-Z]*}}F'
func retain(ptr: Builtin.NativeObject) {
Builtin.retain(ptr)
}
// SILGen test:
//
// CHECK-LABEL: sil hidden [ossa] @$s8builtins7release{{[_0-9a-zA-Z]*}}F : $@convention(thin) (@guaranteed Builtin.NativeObject) -> () {
// CHECK: bb0([[P:%.*]] : @guaranteed $Builtin.NativeObject):
// CHECK: unmanaged_release_value [[P]]
// CHECK-NOT: destroy_value [[P]]
// CHECK: } // end sil function '$s8builtins7release{{[_0-9a-zA-Z]*}}F'
// SIL Test. Make sure even in -Onone code, we clean this up properly:
// CANONICAL-LABEL: sil hidden @$s8builtins7release{{[_0-9a-zA-Z]*}}F : $@convention(thin) (@guaranteed Builtin.NativeObject) -> () {
// CANONICAL: bb0([[P:%.*]] : $Builtin.NativeObject):
// CANONICAL-NEXT: debug_value
// CANONICAL-NEXT: strong_release [[P]]
// CANONICAL-NEXT: tuple
// CANONICAL-NEXT: tuple
// CANONICAL-NEXT: return
// CANONICAL: } // end sil function '$s8builtins7release{{[_0-9a-zA-Z]*}}F'
func release(ptr: Builtin.NativeObject) {
Builtin.release(ptr)
}
//===----------------------------------------------------------------------===//
// Other Operations
//===----------------------------------------------------------------------===//
func once_helper() {}
// CHECK-LABEL: sil hidden [ossa] @$s8builtins4once7controlyBp_tF
// CHECK: [[T0:%.*]] = function_ref @$s8builtins11once_helperyyFTo : $@convention(c) () -> ()
// CHECK-NEXT: builtin "once"(%0 : $Builtin.RawPointer, [[T0]] : $@convention(c) () -> ())
func once(control: Builtin.RawPointer) {
Builtin.once(control, once_helper)
}
// CHECK-LABEL: sil hidden [ossa] @$s8builtins19valueToBridgeObjectyBbSuF : $@convention(thin) (UInt) -> @owned Builtin.BridgeObject {
// CHECK: bb0([[UINT:%.*]] : $UInt):
// CHECK: [[BI:%.*]] = struct_extract [[UINT]] : $UInt, #UInt._value
// CHECK: [[CAST:%.*]] = value_to_bridge_object [[BI]]
// CHECK: [[RET:%.*]] = copy_value [[CAST]] : $Builtin.BridgeObject
// CHECK: return [[RET]] : $Builtin.BridgeObject
// CHECK: } // end sil function '$s8builtins19valueToBridgeObjectyBbSuF'
func valueToBridgeObject(_ x: UInt) -> Builtin.BridgeObject {
return Builtin.valueToBridgeObject(x._value)
}
// CHECK-LABEL: sil hidden [ossa] @$s8builtins10assumeTrueyyBi1_F
// CHECK: builtin "assume_Int1"({{.*}} : $Builtin.Int1)
// CHECK: return
func assumeTrue(_ x: Builtin.Int1) {
Builtin.assume_Int1(x)
}
| 0469972a3a7836e26e5a8f6fe864eba4 | 41.526857 | 200 | 0.624224 | false | false | false | false |
ethan605/SwiftVD | refs/heads/master | swiftvd/swiftvd/viewcontrollers/TopicCell.swift | mit | 1 | //
// TopicCell.swift
// swiftvd
//
// Created by Ethan Nguyen on 6/8/14.
// Copyright (c) 2014 Volcano. All rights reserved.
//
import UIKit
struct SingletonTopicCell {
static var sharedInstance: TopicCell? = nil
static var token: dispatch_once_t = 0
}
class TopicCell: UITableViewCell {
@IBOutlet var lblTitle : UILabel = nil
@IBOutlet var imgFirstImage : UIImageView = nil
class func heightToFit() -> Float {
return 320
}
class func cellIdentifier() -> String {
return "TopicCell"
}
class func sharedCell() -> TopicCell {
dispatch_once(&SingletonTopicCell.token,
{
SingletonTopicCell.sharedInstance = TopicCell()
})
return SingletonTopicCell.sharedInstance!
}
func reloadCellWithData(topicData: MTopic) {
lblTitle.text = topicData.title
var sizeThatFits = lblTitle.sizeThatFits(CGSizeMake(lblTitle.frame.size.width, Float(Int32.max)))
lblTitle.frame.size.height = sizeThatFits.height
lblTitle.superview.frame.size.height = lblTitle.frame.origin.y*2 + lblTitle.frame.size.height
var coverPhoto = topicData.coverPhoto!
imgFirstImage.setImageWithURL(NSURL(string: coverPhoto.photoURL))
}
}
| 61ef1f7527c57c179bca6c966fa076e1 | 24.1875 | 101 | 0.701406 | false | false | false | false |
shalex9154/XCGLogger-Firebase | refs/heads/master | XCGLogger+Firebase/AppDelegate.swift | mit | 1 | //
// AppDelegate.swift
// XCGLogger+Firebase
//
// Created by Oleksii Shvachenko on 9/27/17.
// Copyright © 2017 oleksii. All rights reserved.
//
import UIKit
import XCGLogger
let log = XCGLogger.default
extension Tag {
static let sensitive = Tag("sensitive")
static let ui = Tag("ui")
static let data = Tag("data")
}
extension Dev {
static let dave = Dev("dave")
static let sabby = Dev("sabby")
}
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
let settingsPath = Bundle.main.path(forResource: "FirebaseSetting", ofType: "plist")!
let encryptionParams = FirebaseDestination.EncryptionParams(key: "w6xXnb4FwvQEeF1R", iv: "0123456789012345")
let destination = FirebaseDestination(firebaseSettingsPath: settingsPath, encryptionParams: encryptionParams)!
log.add(destination: destination)
log.debug(["Device": "iPhone", "Version": 7])
log.error("omg!")
log.severe("omg_2!")
log.info("omg_3!")
let tags = XCGLogger.Constants.userInfoKeyTags
log.error("some error with tag", userInfo: [tags: "iPhone X"])
log.debug("some error with tag", userInfo: [tags: ["iPhone X", "iPhone 8"]])
log.debug("A tagged log message", userInfo: Dev.dave | Tag.sensitive)
return true
}
}
| c872cfd31e42622e32fd5043c8a36a1c | 30.173913 | 142 | 0.712692 | false | false | false | false |
stripe/stripe-ios | refs/heads/master | StripePaymentSheet/StripePaymentSheet/PaymentSheet/BottomSheet/BottomSheetPresentationAnimator.swift | mit | 1 | //
// BottomSheetPresentationAnimator.swift
// StripePaymentSheet
//
// Copyright © 2022 Stripe, Inc. All rights reserved.
//
import UIKit
/// Handles the animation of the presentedViewController as it is presented or dismissed.
///
/// This is a vertical animation that
/// - Animates up from the bottom of the screen
/// - Dismisses from the top to the bottom of the screen
@objc(STPBottomSheetPresentationAnimator)
class BottomSheetPresentationAnimator: NSObject {
enum TransitionStyle {
case presentation
case dismissal
}
private let transitionStyle: TransitionStyle
required init(transitionStyle: TransitionStyle) {
self.transitionStyle = transitionStyle
super.init()
}
private func animatePresentation(transitionContext: UIViewControllerContextTransitioning) {
guard
let toVC = transitionContext.viewController(forKey: .to),
let fromVC = transitionContext.viewController(forKey: .from)
else { return }
// Calls viewWillAppear and viewWillDisappear
fromVC.beginAppearanceTransition(false, animated: true)
transitionContext.containerView.layoutIfNeeded()
// Move presented view offscreen (from the bottom)
toVC.view.frame = transitionContext.finalFrame(for: toVC)
toVC.view.frame.origin.y = transitionContext.containerView.frame.height
Self.animate({
transitionContext.containerView.setNeedsLayout()
transitionContext.containerView.layoutIfNeeded()
}) { didComplete in
// Calls viewDidAppear and viewDidDisappear
fromVC.endAppearanceTransition()
transitionContext.completeTransition(didComplete)
}
}
private func animateDismissal(transitionContext: UIViewControllerContextTransitioning) {
guard
let toVC = transitionContext.viewController(forKey: .to),
let fromVC = transitionContext.viewController(forKey: .from)
else { return }
// Calls viewWillAppear and viewWillDisappear
toVC.beginAppearanceTransition(true, animated: true)
Self.animate({
fromVC.view.frame.origin.y = transitionContext.containerView.frame.height
}) { didComplete in
fromVC.view.removeFromSuperview()
// Calls viewDidAppear and viewDidDisappear
toVC.endAppearanceTransition()
transitionContext.completeTransition(didComplete)
}
}
static func animate(
_ animations: @escaping () -> Void,
_ completion: ((Bool) -> Void)? = nil
) {
let params = UISpringTimingParameters()
let animator = UIViewPropertyAnimator(duration: 0, timingParameters: params)
animator.addAnimations(animations)
if let completion = completion {
animator.addCompletion { (_) in
completion(true)
}
}
animator.startAnimation()
}
}
// MARK: - UIViewControllerAnimatedTransitioning Delegate
extension BottomSheetPresentationAnimator: UIViewControllerAnimatedTransitioning {
func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?)
-> TimeInterval
{
// TODO This should depend on height so that velocity is constant
return 0.5
}
func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
switch transitionStyle {
case .presentation:
animatePresentation(transitionContext: transitionContext)
case .dismissal:
animateDismissal(transitionContext: transitionContext)
}
}
}
| 26dcdbf1ff86464ad4e0b502f4d6bbc6 | 34.046729 | 95 | 0.6704 | false | false | false | false |
JustinM1/S3SignerAWS | refs/heads/master | Sources/Dates.swift | mit | 1 | import Foundation
internal struct Dates {
/// The ISO8601 basic format timestamp of signature creation. YYYYMMDD'T'HHMMSS'Z'.
internal let long: String
/// The short timestamp of signature creation. YYYYMMDD.
internal let short: String
}
extension Dates {
internal init(date: Date) {
short = date.timestampShort
long = date.timestampLong
}
}
extension Date {
private static let shortdateFormatter: DateFormatter = {
let formatter = DateFormatter()
formatter.dateFormat = "yyyyMMdd"
formatter.timeZone = TimeZone(abbreviation: "UTC")
formatter.locale = Locale(identifier: "en_US_POSIX")
return formatter
}()
private static let longdateFormatter: DateFormatter = {
let formatter = DateFormatter()
formatter.dateFormat = "yyyyMMdd'T'HHmmss'Z'"
formatter.timeZone = TimeZone(abbreviation: "UTC")
formatter.locale = Locale(identifier: "en_US_POSIX")
return formatter
}()
internal var timestampShort: String {
return Date.shortdateFormatter.string(from: self)
}
internal var timestampLong: String {
return Date.longdateFormatter.string(from: self)
}
}
| c7438e25f7ccdf6b65323a5b3ae99f7c | 26.222222 | 88 | 0.666939 | false | false | false | false |
yomajkel/RingGraph | refs/heads/master | RingGraph/RingGraph/AnimationHelpers.swift | mit | 1 | //
// AnimationHelper.swift
// RingMeter
//
// Created by Michał Kreft on 13/04/15.
// Copyright (c) 2015 Michał Kreft. All rights reserved.
//
import Foundation
internal struct AnimationState {
let totalDuration: TimeInterval
var currentTime: TimeInterval = 0.0
init(totalDuration: TimeInterval) {
self.totalDuration = totalDuration
}
init(totalDuration: TimeInterval, progress: Float) {
self.totalDuration = totalDuration
self.currentTime = totalDuration * TimeInterval(progress)
}
func progress() -> Float {
return currentTime >= totalDuration ? 1.0 : Float(currentTime / totalDuration)
}
mutating func incrementDuration(delta: TimeInterval) {
currentTime += delta
}
}
internal struct RangeAnimationHelper {
let animationStart: Float
let animationEnd: Float
init(animationStart: Float = 0.0, animationEnd: Float = 1.0) {
self.animationStart = animationStart
self.animationEnd = animationEnd
}
func normalizedProgress(_ absoluteProgress: Float) -> Float {
var normalizedProgress: Float = 0.0
switch absoluteProgress {
case _ where absoluteProgress < animationStart:
normalizedProgress = 0.0
case _ where absoluteProgress > animationEnd:
normalizedProgress = 1.0
default:
let progressSpan = animationEnd - animationStart
normalizedProgress = (absoluteProgress - animationStart) / progressSpan
}
return normalizedProgress
}
}
struct RingGraphAnimationState {
let animationHelper: RangeAnimationHelper
let animationProgress: Float
let meterValues: [Float]
init(graph: RingGraph, animationProgress inProgress: Float) {
animationHelper = RangeAnimationHelper(animationStart: 0.3, animationEnd: 1.0)
let graphProgress = sinEaseOutValue(forAnimationProgress: animationHelper.normalizedProgress(inProgress))
animationProgress = graphProgress
let closureProgress = animationProgress
meterValues = graph.meters.map {meter -> Float in
return meter.normalizedValue * closureProgress
}
}
}
internal func sinEaseOutValue(forAnimationProgress progress: Float) -> Float {
return sin(progress * Float(Double.pi) / 2)
}
| 7ee1a86ad3f05b1b4f1870006bf58eac | 29.910256 | 113 | 0.664869 | false | false | false | false |
sstanic/Shopfred | refs/heads/master | Shopfred/Shopfred/View Controller/UserRegistrationViewController.swift | mit | 1 | //
// UserRegistrationViewController.swift
// Shopfred
//
// Created by Sascha Stanic on 17.09.17.
// Copyright © 2017 Sascha Stanic. All rights reserved.
//
import UIKit
import CoreData
/**
Shows the user registration view.
- important: Gets the current shopping space from the **DataStore**.
# Navigation
- **LoginViewController** (cancel)
- **StartViewController** (successful registration)
*/
class UserRegistrationViewController: UIViewController {
// MARK: - Outelts
@IBOutlet weak var labelUserRegistration: UILabel!
@IBOutlet weak var textFieldFirstName: UITextField!
@IBOutlet weak var textFieldLastName: UITextField!
@IBOutlet weak var textFieldEmail: UITextField!
@IBOutlet weak var textFieldPassword: UITextField!
@IBOutlet weak var textViewInformation: UITextView!
@IBOutlet weak var btnRegister: UIButton!
@IBOutlet weak var activityIndicator: UIActivityIndicatorView!
// MARK: - Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
self.hideKeyboardWhenTappedAround()
self.setStyle()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
// Check if registration is possible (in this version restricted to one user per shopping space)
// Anyway this check will currently always pass, the registration dialog is only reachable when not logged in
if let sp = DataStore.sharedInstance().shoppingStore.shoppingSpace {
if let users = sp.users {
if users.count == 1 {
let u = users.allObjects.first as! User
if u.id != Constants.UserNotSet {
self.textViewInformation.text = "A user is already registered with this shopping space. User email: \(u.email ?? "<unknown>")"
}
}
else {
self.textViewInformation.text = "Several users are already registered in this shopping space."
}
}
else {
// no users yet in shopping space => go ahead
}
}
else {
print("Shopping space not set. This should have been checked in start view.")
}
}
// MARK: - Styling
private func setStyle() {
self.labelUserRegistration.style(style: TextStyle.title)
self.textFieldFirstName.style(style: TextStyle.body)
self.textFieldLastName.style(style: TextStyle.body)
self.textFieldEmail.style(style: TextStyle.body)
self.textFieldPassword.style(style: TextStyle.body)
self.textViewInformation.style(style: TextStyle.body)
self.btnRegister.style(style: ViewStyle.Button.register)
self.view.style(style: ViewStyle.DetailsView.standard)
}
// MARK: - IBAction
@IBAction func registerClicked(_ sender: Any) {
let firstName = self.textFieldFirstName.text!
let lastName = self.textFieldLastName.text!
let email = self.textFieldEmail.text!
let password = self.textFieldPassword.text!
Utils.showActivityIndicator(self.view, activityIndicator: self.activityIndicator, alpha: 0.1)
DataStore.sharedInstance().userStore.registerNewUser(firstName: firstName, lastName: lastName, email: email, password: password) { user, error in
Utils.hideActivityIndicator(self.view, activityIndicator: self.activityIndicator)
if error != nil {
Utils.showAlert(self, alertMessage: "Error: \(error?.localizedDescription ?? "")", completion: nil)
}
else {
if DataStore.sharedInstance().userStore.CurrentUser == nil {
DataStore.sharedInstance().userStore.CurrentUser = user
UserDefaults.standard.set(true, forKey: Constants.IsLoggedIn)
UserDefaults.standard.set(user!.id!, forKey: Constants.CurrentUser)
}
UserDefaults.standard.set(true, forKey: Constants.IsLoggedIn)
if let navController = self.navigationController {
navController.popToRootViewController(animated: true)
}
else {
Utils.showAlert(self, alertMessage: "Sorry, something went wrong. Please restart the app.", completion: nil)
}
}
}
}
@IBAction func cancelClicked(_ sender: Any) {
self.navigateBack()
}
// MARK: - Navigation
private func navigateBack() {
if let navController = self.navigationController {
navController.popViewController(animated: true)
}
else {
Utils.showAlert(self, alertMessage: "Sorry, something went wrong. Please restart the app.", completion: nil)
}
}
}
| 82f55f568dfdaf7cd426f8f12dce0254 | 34.127517 | 153 | 0.587314 | false | false | false | false |
Felizolinha/WidGame | refs/heads/master | WidGame/WidGame/WidGame.swift | mit | 1 | //
// WidGame.swift
// NewGame
//
// Created by Luis Gustavo Avelino de Lima Jacinto on 19/06/17.
// Copyright © 2017 BEPiD. All rights reserved.
//
import Foundation
import SpriteKit
import NotificationCenter
/**
Defines which widget properties can be changed from the game scene.
- author: Matheus Felizola Freires
*/
public protocol WGDelegate {
///A bool that defines if the widget should be expandable or not.
var isExpandable:Bool {get set}
///A CGFloat that defines the widget's maximum height.
var maxHeight:CGFloat {get set}
}
/**
All your widget game scenes should inherit from this class, instead of SKScene.
- author: Matheus Felizola Freires
*/
open class WGScene:SKScene {
/**
Called when the active display mode changes.
You should override this method if you need to update your scene when the widget changes it's display mode.
The default implementation of this method is blank.
- parameters:
- activeDisplayMode: The new active display mode. See NCWidgetDisplayMode for possible values.
- maxSize: A CGSize object that represents the new maximum size this widget can have.
*/
open func widgetActiveDisplayModeDidChange(_ activeDisplayMode: NCWidgetDisplayMode, withMaximumSize maxSize: CGSize) {}
/**
Called when the widget's frame changes.
You should override this method if you need to update your scene when the widget updates it's frame. This usually happens when the widget is transitioning to a different display mode, or to a new preferred content size.
The default implementation for this method is blank.
- parameters:
- frame: A CGRect with the new frame size of the widget.
- author: Matheus Felizola Freires
*/
open func didUpdateWidgetFrame(to frame: CGRect) {}
/**
Allows your game scene to change the widget's expandability or maximum height.
Example of how to change the maximum height of your widget:
widgetDelegate.maxHeight = 200
*/
open var widgetDelegate: WGDelegate?
/**
Creates your scene object.
- parameters:
- size: The size of the scene in points.
- controller: The WGDelegate compliant view controller that is creating the scene.
- returns: A newly initialized WGScene object.
*/
public init(size: CGSize, controller: WGDelegate) {
super.init(size: size)
widgetDelegate = controller
scaleMode = SKSceneScaleMode.resizeFill
}
/**
Returns an object initialized from data in a given unarchiver.
You typically return self from init(coder:). If you have an advanced need that requires substituting a different object after decoding, you can do so in awakeAfter(using:).
- parameter decoder: An unarchiver object.
- returns: self, initialized using the data in decoder.
*/
public required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
/**
Your TodayViewController should inherit from WGViewController to implement WidGame's functionalities.
- author: Matheus Felizola Freires
*/
open class WGViewController: UIViewController, NCWidgetProviding, WGDelegate {
///The SKView that will present your WidGame scenes.
open var gameView: SKView?
/**
An enum that provides the reasons which your widget might close.
- author: Matheus Felizola Freires
*/
public enum ExitReason {
///Sent when the widget leaves the screen.
case leftTheScreen
///Sent when the widget receives a memory warning.
case memoryWarning
}
@IBInspectable
open var isExpandable: Bool = true {
didSet {
changeExpandability(to: isExpandable)
}
}
open var maxHeight:CGFloat = 359 {
didSet {
if extensionContext?.widgetActiveDisplayMode == .expanded {
preferredContentSize = CGSize(width: preferredContentSize.width, height: maxHeight)
}
}
}
/**
Sets the widget expandability.
- parameter value: A Bool value that tells the method if it should make the widget expandable or not.
- requires: iOS 10.0
- TODO: Create a fallback to versions earlier than iOS 10.0
- author: Matheus Felizola Freires
*/
private func changeExpandability(to value: Bool) {
if value {
if #available(iOSApplicationExtension 10.0, *) {
extensionContext?.widgetLargestAvailableDisplayMode = .expanded
} else {
// Fallback on earlier versions
}
} else {
if #available(iOSApplicationExtension 10.0, *) {
extensionContext?.widgetLargestAvailableDisplayMode = .compact
} else {
// Fallback on earlier versions
}
}
}
/**
Notifies the view controller that its view was removed from a view hierarchy.
You can override this method to perform additional tasks associated with dismissing or hiding the view. If you override this method, you must call super at some point in your implementation.
- parameter animated: If true, the disappearance of the view was animated.
*/
open override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
self.widgetMightClose(reason: .leftTheScreen)
}
/**
Sent to the view controller when the app receives a memory warning.
Your app never calls this method directly. Instead, this method is called when the system determines that the amount of available memory is low.
You can override this method to release any additional memory used by your view controller. If you do, your implementation of this method must call the super implementation at some point.
*/
open override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
self.widgetMightClose(reason: .memoryWarning)
}
/**
Called when the widget is in a situation that it might be closed. An exit reason is provided to the method, so your logic can react accordingly.
This method should be used for your save logic.
The default implementation of this method is blank.
- TODO: Find out if there are more things that might cause the widget to close.
- author: Matheus Felizola Freires
*/
open func widgetMightClose(reason: WGViewController.ExitReason) {}
/**
Notifies the container that the size of its view is about to change.
WidGame uses this method to set some widget configurations and creating your game view. It is this method who calls the presentInitialScene() method.
UIKit calls this method before changing the size of a presented view controller’s view. You can override this method in your own objects and use it to perform additional tasks related to the size change. For example, a container view controller might use this method to override the traits of its embedded child view controllers. Use the provided coordinator object to animate any changes you make.
If you override this method in your custom view controllers, always call super at some point in your implementation so that UIKit can forward the size change message appropriately. View controllers forward the size change message to their views and child view controllers. Presentation controllers forward the size change to their presented view controller.
- parameters:
- size: The new size for the container’s view.
- coordinator: The transition coordinator object managing the size change. You can use this object to animate your changes or get information about the transition that is in progress.
*/
open override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransition(to: size, with: coordinator)
if gameView == nil {
DispatchQueue.main.async { //Use a different thread to lower the chance of crash when leaving the widget screen and going back.
[unowned self] in
self.preferredContentSize = CGSize(width: 0, height: self.maxHeight)
self.changeExpandability(to: self.isExpandable)
self.gameView = SKView(frame: self.view.frame)
self.presentInitialScene()
self.view.addSubview(self.gameView!)
}
}
}
/**
Override this method to show your first scene and load any saved info.
The default implementation of this method is blank.
- author: Matheus Felizola Freires
*/
open func presentInitialScene() {}
/**
If you override the method below inside your TodayViewController, always call super at some point in your implementation so that WidGame can still update your gameView's frame and tell your game scene about these updates.
*/
open override func viewDidLayoutSubviews() {
gameView?.frame = view.frame //Update game view frame to reflect any changes in widget's size
if let scene = gameView?.scene as? WGScene {
scene.didUpdateWidgetFrame(to: view.frame)
}
super.viewDidLayoutSubviews()
}
/**
If you override the method below inside your TodayViewController, always call super at some point in your implementation so that WidGame can still delegate displayMode changes to your WGScene, and set the correct preferredContentSize to your widget.
*/
open func widgetActiveDisplayModeDidChange(_ activeDisplayMode: NCWidgetDisplayMode, withMaximumSize maxSize: CGSize) {
if activeDisplayMode == .expanded {
preferredContentSize = CGSize(width: maxSize.width, height: maxHeight)
} else {
preferredContentSize = maxSize
}
if let scene = gameView?.scene as? WGScene {
scene.widgetActiveDisplayModeDidChange(activeDisplayMode, withMaximumSize: preferredContentSize)
}
//Don't forget to call super.widgetActiveDisplayModeDidChange(activeDisplayMode, withMaximumSize: maxSize) on your code!
}
}
| b56c846213d58885b340f15a7ef860e9 | 40.855967 | 403 | 0.699636 | false | false | false | false |
nghialv/Sapporo | refs/heads/master | Sapporo/Sources/Cell/SACell.swift | mit | 1 | //
// SACell.swift
// Example
//
// Created by Le VanNghia on 6/29/15.
// Copyright (c) 2015 Le Van Nghia. All rights reserved.
//
import UIKit
open class SACell: UICollectionViewCell {
open internal(set) weak var _cellmodel: SACellModel?
open var shouldSelect = true
open var shouldDeselect = true
open var shouldHighlight = true
func configure(_ cellmodel: SACellModel) {
_cellmodel = cellmodel
configure()
}
open func configure() {}
open func configureForSizeCalculating(_ cellmodel: SACellModel) {
_cellmodel = cellmodel
}
open func willDisplay(_ collectionView: UICollectionView) {}
open func didEndDisplaying(_ collectionView: UICollectionView) {}
open func didHighlight(_ collectionView: UICollectionView) {}
open func didUnhighlight(_ collectionView: UICollectionView) {}
}
| fcc1de0112e91165962ae73ec83a1a4c | 25.939394 | 69 | 0.677165 | false | true | false | false |
cnbin/wikipedia-ios | refs/heads/master | Wikipedia/Legacy Data Migration/WMFLegacyImageDataMigration.swift | mit | 1 | //
// WMFLegacyImageDataMigration.swift
// Wikipedia
//
// Created by Brian Gerstle on 7/6/15.
// Copyright (c) 2015 Wikimedia Foundation. All rights reserved.
//
import Foundation
import PromiseKit
enum LegacyImageDataMigrationError : CancellableErrorType {
case Deinit
var cancelled: Bool {
return true
}
}
/// Migrate legacy image data for saved pages into WMFImageController.
@objc
public class WMFLegacyImageDataMigration : NSObject {
/// Image controller where data will be migrated.
let imageController: WMFImageController
/// List of saved pages which is saved when the tasks are finished processing.
let savedPageList: MWKSavedPageList
/// Data store which provides articles and saves the entries after processing.
private let legacyDataStore: MWKDataStore
static let savedPageQueueLabel = "org.wikimedia.wikipedia.legacyimagemigration.savedpagelist"
/// Serial queue for manipulating `savedPageList`.
private lazy var savedPageQueue: dispatch_queue_t = {
let savedPageQueue = dispatch_queue_create(savedPageQueueLabel, DISPATCH_QUEUE_SERIAL)
dispatch_set_target_queue(savedPageQueue, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0))
return savedPageQueue
}()
/// Background task manager which invokes the receiver's methods to migrate image data in the background.
private lazy var backgroundTaskManager: WMFBackgroundTaskManager<MWKSavedPageEntry> = {
WMFBackgroundTaskManager(
next: { [weak self] in
return self?.unmigratedEntry()
},
processor: { [weak self] entry in
return self?.migrateEntry(entry) ?? Promise<Void>(error: LegacyImageDataMigrationError.Deinit)
},
finalize: { [weak self] in
return self?.save() ?? Promise()
})
}()
/// Initialize a new migrator.
public required init(imageController: WMFImageController = WMFImageController.sharedInstance(),
legacyDataStore: MWKDataStore) {
self.imageController = imageController
self.legacyDataStore = legacyDataStore
self.savedPageList = self.legacyDataStore.userDataStore().savedPageList
super.init()
}
public func setupAndStart() -> Promise<Void> {
return self.backgroundTaskManager.start()
}
public func setupAndStart() -> AnyPromise {
return AnyPromise(bound: setupAndStart())
}
/// MARK: - Testable Methods
/// Save the receiver's saved page list, making sure to preserve the current list on disk.
func save() -> Promise<Void> {
// for each entry that we migrated
let migratedEntries = savedPageList.entries.filter() { $0.didMigrateImageData == true } as! [MWKSavedPageEntry]
let currentSavedPageList = legacyDataStore.userDataStore().savedPageList
// grab the corresponding entry from the list on disk
for migratedEntry: MWKSavedPageEntry in migratedEntries {
currentSavedPageList.updateEntryWithTitle(migratedEntry.title) { entry in
if !entry.didMigrateImageData {
// mark as migrated if necessary, and mark the list as dirty
entry.didMigrateImageData = true
return true
} else {
// if already migrated, leave dirty flag alone
return false
}
}
}
// save if dirty
return Promise().then() { () -> AnyPromise in
return currentSavedPageList.save()
}.asVoid()
}
func unmigratedEntry() -> MWKSavedPageEntry? {
var entry: MWKSavedPageEntry?
dispatch_sync(savedPageQueue) {
let allEntries = self.savedPageList.entries as! [MWKSavedPageEntry]
entry = allEntries.filter() { $0.didMigrateImageData == false }.first
}
return entry
}
/// Migrate all images in `entry` into `imageController`, then mark it as migrated.
func migrateEntry(entry: MWKSavedPageEntry) -> Promise<Void> {
NSLog("Migrating entry \(entry)")
return migrateAllImagesInArticleWithTitle(entry.title)
.then(on: savedPageQueue) { [weak self] in
self?.markEntryAsMigrated(entry)
}
}
/// Move an article's images into `imageController`, ignoring any errors.
func migrateAllImagesInArticleWithTitle(title: MWKTitle) -> Promise<Void> {
if let images = legacyDataStore.existingArticleWithTitle(title)?.allImageURLs() as? [NSURL] {
if images.count > 0 {
return images.reduce(Promise()) { (chain, url) -> Promise<Void> in
return chain.then(on: dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0)) { [weak self] in
guard let strongSelf: WMFLegacyImageDataMigration = self else {
return Promise(error: LegacyImageDataMigrationError.Deinit)
}
let filepath = strongSelf.legacyDataStore.pathForImageData(url.absoluteString, title: title)
let promise = strongSelf.imageController.importImage(fromFile: filepath, withURL: url)
return promise.recover() { (error: ErrorType) -> Promise<Void> in
#if DEBUG
// only return errors in debug, silently fail in production
if (error as NSError).code != NSFileNoSuchFileError {
return Promise(error: error)
}
#endif
return Promise()
}
}
}.asVoid()
}
}
return Promise()
}
/// Mark the given entry as having its image data migrated.
func markEntryAsMigrated(entry: MWKSavedPageEntry) {
savedPageList.updateEntryWithTitle(entry.title) { e in
e.didMigrateImageData = true
return true
}
}
} | 1c5c436902544457b98c872741ed4478 | 39.853333 | 124 | 0.623633 | false | false | false | false |
codepgq/LearningSwift | refs/heads/master | PresentTumblrAnimator/PresentTumblrAnimator/ViewController.swift | apache-2.0 | 1 | //
// ViewController.swift
// PresentTumblrAnimator
//
// Created by ios on 16/9/23.
// Copyright © 2016年 ios. All rights reserved.
//
import UIKit
struct model {
var icon = "animator1.jpg"
var name = "default"
var backImage = "animator1.jpg"
}
class ViewController: UIViewController ,UICollectionViewDelegate,UICollectionViewDataSource{
@IBOutlet weak var collectionView: UICollectionView!
let data = [
model(icon: "Chat", name: "小明", backImage: "animator1.jpg"),
model(icon: "Quote", name: "老王", backImage: "animator2.jpg"),
model(icon: "Audio", name: "隔壁大叔", backImage: "animator3.jpg"),
model(icon: "Link", name: "邻家淑女", backImage: "animator4.jpg")
]
override func viewDidLoad() {
super.viewDidLoad()
collectionView.delegate = self
collectionView.dataSource = self
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func preferredStatusBarStyle() -> UIStatusBarStyle {
return .LightContent
}
@IBAction func unwindToMainViewController (sender: UIStoryboardSegue){
self.dismissViewControllerAnimated(true, completion: nil)
}
}
extension ViewController {
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int{
return 10
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell{
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("collCell", forIndexPath: indexPath) as! CollectionViewCell
let model = data[indexPath.row % 4]
cell.backImage.image = UIImage(named: model.backImage)
cell.icon.image = UIImage(named:model.icon)
cell.nameLabel.text = model.name
return cell
}
}
| a9fb8ce29d8d07e2eabca8bcccfff079 | 29.734375 | 132 | 0.671581 | false | false | false | false |
cismet/belis-app | refs/heads/dev | belis-app/MainViewController.swift | mit | 1 |
//
// MainViewController.swift
// BelIS
//
// Created by Thorsten Hell on 08/12/14.
// Copyright (c) 2014 cismet. All rights reserved.
//
import UIKit;
import MapKit;
import ObjectMapper;
import MGSwipeTableCell
import JGProgressHUD
class MainViewController: UIViewController, UITableViewDataSource, UITableViewDelegate,CLLocationManagerDelegate, MKMapViewDelegate, UITextFieldDelegate, MGSwipeTableCellDelegate {
@IBOutlet weak var mapView: MKMapView!;
@IBOutlet weak var tableView: UITableView!;
@IBOutlet weak var mapTypeSegmentedControl: UISegmentedControl!;
@IBOutlet weak var mapToolbar: UIToolbar!;
@IBOutlet weak var focusToggle: UISwitch!
@IBOutlet weak var textfieldGeoSearch: UITextField!
@IBOutlet weak var brightenToggle: UISwitch!
@IBOutlet weak var itemArbeitsauftrag: UIBarButtonItem!
@IBOutlet weak var bbiMoreFunctionality: UIBarButtonItem!
@IBOutlet weak var bbiZoomToAllObjects: UIBarButtonItem!
var matchingSearchItems: [MKMapItem] = [MKMapItem]()
var matchingSearchItemsAnnotations: [MKPointAnnotation ] = [MKPointAnnotation]()
var loginViewController: LoginViewController?
var isLeuchtenEnabled=true;
var isMastenEnabled=true;
var isMauerlaschenEnabled=true;
var isleitungenEnabled=true;
var isSchaltstelleEnabled=true;
var highlightedLine : HighlightedMkPolyline?;
var selectedAnnotation : MKAnnotation?;
var user="";
var pass="";
var timer = Timer();
var mapRegionSetFromUserDefaults=false
let progressHUD = JGProgressHUD(style: JGProgressHUDStyle.dark)
var gotoUserLocationButton:MKUserTrackingBarButtonItem!;
var locationManager: CLLocationManager!
let focusRectShape = CAShapeLayer()
static let IMAGE_PICKER=UIImagePickerController()
var brightOverlay=MyBrightOverlay()
var shownDetails:DetailVC?
//MARK: Standard VC functions
override func viewDidLoad() {
super.viewDidLoad();
CidsConnector.sharedInstance().mainVC=self
locationManager=CLLocationManager();
locationManager.desiredAccuracy=kCLLocationAccuracyBest;
locationManager.distanceFilter=100.0;
locationManager.startUpdatingLocation();
locationManager.requestWhenInUseAuthorization()
gotoUserLocationButton=MKUserTrackingBarButtonItem(mapView:mapView);
mapToolbar.items!.insert(gotoUserLocationButton,at:0 );
//delegate stuff
locationManager.delegate=self;
mapView.delegate=self;
tableView.delegate=self;
//var tileOverlay = MyOSMMKTileOverlay()
// mapView.addOverlay(tileOverlay);
var lat: CLLocationDegrees = (UserDefaults.standard.double(forKey: "mapPosLat") as CLLocationDegrees?) ?? 0.0
var lng: CLLocationDegrees = (UserDefaults.standard.double(forKey: "mapPosLng") as CLLocationDegrees?) ?? 0.0
var altitude: Double = (UserDefaults.standard.double(forKey: "mapAltitude") as Double?) ?? 0.0
if lat == 0.0 {
lat=CidsConnector.sharedInstance().mapPosLat
}
if lng == 0.0 {
lng=CidsConnector.sharedInstance().mapPosLng
}
if altitude == 0.0 {
altitude = CidsConnector.sharedInstance().mapAltitude
}
let initLocation: CLLocationCoordinate2D = CLLocationCoordinate2DMake(lat, lng)
mapView.isRotateEnabled=false;
mapView.isZoomEnabled=true;
mapView.showsBuildings=true;
mapView.setCenter(initLocation, animated: true);
mapView.camera.altitude = altitude
mapRegionSetFromUserDefaults=true
log.warning("initial Position from UserDefaults= \(UserDefaults.standard.double(forKey: "mapPosLat")),\(UserDefaults.standard.double(forKey: "mapPosLng")) with an altitude of \(UserDefaults.standard.double(forKey: "mapAltitide"))")
log.warning("initial Position from CidsConnector= \(CidsConnector.sharedInstance().mapPosLat),\(CidsConnector.sharedInstance().mapPosLng) with an altitude of \(CidsConnector.sharedInstance().mapAltitude)")
log.info("initial Position= \(lat),\(lng) with an altitude of \(self.mapView.camera.altitude)")
focusRectShape.opacity = 0.4
focusRectShape.lineWidth = 2
focusRectShape.lineJoin = kCALineJoinMiter
focusRectShape.strokeColor = UIColor(red: 0.29, green: 0.53, blue: 0.53, alpha: 1).cgColor
focusRectShape.fillColor = UIColor(red: 0.51, green: 0.76, blue: 0.6, alpha: 1).cgColor
let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(MainViewController.mapTapped(_:)))
mapView.addGestureRecognizer(tapGestureRecognizer)
//UINavigationController(rootViewController: self)
textfieldGeoSearch.delegate=self
bbiMoreFunctionality.setTitleTextAttributes([
NSFontAttributeName : UIFont(name: GlyphTools.glyphFontName, size: 16)!],
for: UIControlState())
bbiMoreFunctionality.title=WebHostingGlyps.glyphs["icon-chevron-down"]
bbiZoomToAllObjects.setTitleTextAttributes([
NSFontAttributeName : UIFont(name: GlyphTools.glyphFontName, size: 20)!],
for: UIControlState())
bbiZoomToAllObjects.title=WebHostingGlyps.glyphs["icon-world"]
log.info(UIDevice.current.identifierForVendor!.uuidString)
itemArbeitsauftrag.title="Kein Arbeitsauftrag ausgewählt (\(CidsConnector.sharedInstance().selectedTeam?.name ?? "-"))"
}
override func viewDidAppear(_ animated: Bool) {
if CidsConnector.sharedInstance().selectedTeam != nil {
// let alert=UIAlertController(title: "Ausgewähltes Team",message:"\(CidsConnector.sharedInstance().selectedTeam ?? "???")", preferredStyle: UIAlertControllerStyle.alert)
// let okButton = UIAlertAction(title: "Ok", style: .default, handler: nil)
// alert.addAction(okButton)
// self.present(alert, animated: true, completion: nil)
}
else {
let alert=UIAlertController(title: "Kein Team ausgewählt",message:"Ohne ausgewähltes Team können Sie keine Arbeitsaufträge aufrufen.", preferredStyle: UIAlertControllerStyle.alert)
let okButton = UIAlertAction(title: "Ok", style: .default, handler: nil)
alert.addAction(okButton)
show(alert,sender: self)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
if (segue.identifier == "showSearchSelectionPopover") {
let selectionVC = segue.destination as! SelectionPopoverViewController
selectionVC.mainVC=self;
}
else if (segue.identifier == "showAdditionalFunctionalityPopover") {
let additionalFuncVC = segue.destination as! AdditionalFunctionalityPopoverViewController
additionalFuncVC.mainVC=self;
}
}
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
focusRectShape.removeFromSuperlayer()
coordinator.animate(alongsideTransition: nil, completion: { context in
if UIDevice.current.orientation.isLandscape {
log.verbose("landscape")
} else {
log.verbose("portraight")
}
self.ensureFocusRectangleIsDisplayedWhenAndWhereItShould()
})
}
//MARK: UITableViewDataSource
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return CidsConnector.sharedInstance().searchResults[Entity.byIndex(section)]?.count ?? 0
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell: TableViewCell = tableView.dequeueReusableCell(withIdentifier: "firstCellPrototype")as! TableViewCell
// var cellInfoProvider: CellInformationProviderProtocol = NoCellInformation()
cell.baseEntity=CidsConnector.sharedInstance().searchResults[Entity.byIndex((indexPath as NSIndexPath).section)]?[(indexPath as NSIndexPath).row]
if let obj=cell.baseEntity {
if let cellInfoProvider=obj as? CellInformationProviderProtocol {
cell.lblBezeichnung.text=cellInfoProvider.getMainTitle()
cell.lblStrasse.text=cellInfoProvider.getTertiaryInfo()
cell.lblSubText.text=cellInfoProvider.getSubTitle()
cell.lblZusatzinfo.text=cellInfoProvider.getQuaternaryInfo()
}
}
cell.delegate=self
if let left=cell.baseEntity as? LeftSwipeActionProvider {
cell.leftButtons=left.getLeftSwipeActions()
}
else {
cell.leftButtons=[]
}
if let right=cell.baseEntity as? RightSwipeActionProvider {
cell.rightButtons=right.getRightSwipeActions()
}
else {
cell.rightButtons=[]
}
//let fav=MGSwipeButton(title: "Fav", backgroundColor: UIColor.blueColor())
cell.leftSwipeSettings.transition = MGSwipeTransition.static
//configure right buttons
// let delete=MGSwipeButton(title: "Delete", backgroundColor: UIColor.redColor())
// let more=MGSwipeButton(title: "More",backgroundColor: UIColor.lightGrayColor())
//
// cell.rightButtons = [delete,more]
// cell.rightSwipeSettings.transition = MGSwipeTransition.Static
cell.leftExpansion.threshold=1.5
cell.leftExpansion.fillOnTrigger=true
//cell.leftExpansion.buttonIndex=0
return cell
}
func numberOfSections(in tableView: UITableView) -> Int {
return Entity.allValues.count
}
func swipeTableCell(_ cell: MGSwipeTableCell, shouldHideSwipeOnTap point: CGPoint) -> Bool {
return true
}
func swipeTableCellWillBeginSwiping(_ cell: MGSwipeTableCell) {
if let myTableViewCell=cell as? TableViewCell, let gbe=myTableViewCell.baseEntity as? GeoBaseEntity {
self.selectOnMap(gbe)
self.selectInTable(gbe, scrollToShow: false)
}
}
//MARK: UITableViewDelegate
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath){
log.verbose("didSelectRowAtIndexPath")
if let obj=CidsConnector.sharedInstance().searchResults[Entity.byIndex((indexPath as NSIndexPath).section)]?[(indexPath as NSIndexPath).row] {
selectOnMap(obj)
// lastSelection=obj
}
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
if let array=CidsConnector.sharedInstance().searchResults[Entity.byIndex(section)]{
if (array.count>0){
return 25
}
}
return 0.0
}
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
let title=Entity.byIndex(section).rawValue
if let array=CidsConnector.sharedInstance().searchResults[Entity.byIndex(section)]{
return title + " \(array.count)"
}
else {
return title
}
}
// MARK: CLLocationManagerDelegate
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
}
// MARK: NKMapViewDelegates
func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
if overlay is MKPolyline {
if overlay is GeoBaseEntityStyledMkPolylineAnnotation {
let polylineRenderer = MKPolylineRenderer(overlay: overlay)
polylineRenderer.strokeColor = UIColor(red: 228.0/255.0, green: 118.0/255.0, blue: 37.0/255.0, alpha: 0.8);
polylineRenderer.lineWidth = 2
return polylineRenderer
}
else if overlay is HighlightedMkPolyline {
let polylineRenderer = MKPolylineRenderer(overlay: overlay)
polylineRenderer.strokeColor = UIColor(red: 255.0/255.0, green: 224.0/255.0, blue: 110.0/255.0, alpha: 0.8);
polylineRenderer.lineWidth = 10
return polylineRenderer
}
}
else if let polygon = overlay as? GeoBaseEntityStyledMkPolygonAnnotation {
let polygonRenderer = MKPolygonRenderer(overlay: polygon)
if let styler = polygon.getGeoBaseEntity() as? PolygonStyler {
polygonRenderer.strokeColor = styler.getStrokeColor()
polygonRenderer.lineWidth = styler.getLineWidth()
polygonRenderer.fillColor=styler.getFillColor()
}else {
polygonRenderer.strokeColor = PolygonStylerConstants.strokeColor
polygonRenderer.lineWidth = PolygonStylerConstants.lineWidth
polygonRenderer.fillColor=PolygonStylerConstants.fillColor
}
return polygonRenderer
}
else if (overlay is MyBrightOverlay){
let renderer = MyBrightOverlayRenderer(tileOverlay: overlay as! MKTileOverlay);
return renderer;
}
return MKOverlayRenderer()
}
func mapView(_ mapView: MKMapView, regionDidChangeAnimated animated: Bool) {
if mapRegionSetFromUserDefaults {
log.verbose("Region changed to \(mapView.centerCoordinate.latitude),\(mapView.centerCoordinate.longitude) with an altitude of \(mapView.camera.altitude)")
CidsConnector.sharedInstance().mapPosLat=mapView.centerCoordinate.latitude
CidsConnector.sharedInstance().mapPosLng=mapView.centerCoordinate.longitude
CidsConnector.sharedInstance().mapAltitude=mapView.camera.altitude
}
}
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
if (annotation is GeoBaseEntityPointAnnotation){
let gbePA=annotation as! GeoBaseEntityPointAnnotation;
let reuseId = "belisAnnotation"
var anView = mapView.dequeueReusableAnnotationView(withIdentifier: reuseId)
if anView == nil {
anView = MKAnnotationView(annotation: gbePA, reuseIdentifier: reuseId)
}
else {
anView!.annotation = gbePA
}
//Set annotation-specific properties **AFTER**
//the view is dequeued or created...
anView!.canShowCallout = gbePA.shouldShowCallout;
anView!.image = gbePA.annotationImage
if let label=GlyphTools.sharedInstance().getGlyphedLabel(gbePA.glyphName) {
label.textColor=UIColor(red: 0.0, green: 0.48, blue: 1.0, alpha: 1.0)
anView!.leftCalloutAccessoryView=label
}
if let btn=GlyphTools.sharedInstance().getGlyphedButton("icon-chevron-right"){
btn.setTitleColor(UIColor(red: 0.8, green: 0.8, blue: 0.8, alpha: 1.0), for: UIControlState())
anView!.rightCalloutAccessoryView=btn
}
anView!.alpha=0.9
return anView
} else if (annotation is GeoBaseEntityStyledMkPolylineAnnotation){
let gbeSMKPA=annotation as! GeoBaseEntityStyledMkPolylineAnnotation;
let reuseId = "belisAnnotation"
var anView = mapView.dequeueReusableAnnotationView(withIdentifier: reuseId)
if anView == nil {
anView = MKAnnotationView(annotation: gbeSMKPA, reuseIdentifier: reuseId)
}
else {
anView!.annotation = gbeSMKPA
}
if let label=GlyphTools.sharedInstance().getGlyphedLabel(gbeSMKPA.glyphName) {
label.textColor=UIColor(red: 0.0, green: 0.48, blue: 1.0, alpha: 1.0)
anView!.leftCalloutAccessoryView=label
}
if let btn=GlyphTools.sharedInstance().getGlyphedButton("icon-chevron-right"){
btn.setTitleColor(UIColor(red: 0.8, green: 0.8, blue: 0.8, alpha: 1.0), for: UIControlState())
anView!.rightCalloutAccessoryView=btn
}
//Set annotation-specific properties **AFTER**
//the view is dequeued or created...
anView!.image = gbeSMKPA.annotationImage;
anView!.canShowCallout = gbeSMKPA.shouldShowCallout;
anView!.alpha=0.9
return anView
} else if (annotation is GeoBaseEntityStyledMkPolygonAnnotation){
let gbeSPGA=annotation as! GeoBaseEntityStyledMkPolygonAnnotation;
let reuseId = "belisAnnotation"
var anView = mapView.dequeueReusableAnnotationView(withIdentifier: reuseId)
if anView == nil {
anView = MKAnnotationView(annotation: gbeSPGA, reuseIdentifier: reuseId)
}
else {
anView!.annotation = gbeSPGA
}
if let label=GlyphTools.sharedInstance().getGlyphedLabel(gbeSPGA.glyphName) {
label.textColor=UIColor(red: 0.0, green: 0.48, blue: 1.0, alpha: 1.0)
anView!.leftCalloutAccessoryView=label
}
if let btn=GlyphTools.sharedInstance().getGlyphedButton("icon-chevron-right"){
btn.setTitleColor(UIColor(red: 0.8, green: 0.8, blue: 0.8, alpha: 1.0), for: UIControlState())
anView!.rightCalloutAccessoryView=btn
}
//Set annotation-specific properties **AFTER**
//the view is dequeued or created...
anView!.image = gbeSPGA.annotationImage;
anView!.canShowCallout = gbeSPGA.shouldShowCallout;
anView!.alpha=0.9
return anView
}
return nil;
}
func mapView(_ mapView: MKMapView, didChange mode: MKUserTrackingMode, animated: Bool) {
log.verbose("didChangeUserTrackingMode")
}
func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView) {
delayed(0.0)
{
if !view.annotation!.isKind(of: MatchingSearchItemsAnnotations.self) {
if view.annotation !== self.selectedAnnotation {
mapView.deselectAnnotation(view.annotation, animated: false)
if let selAnno=self.selectedAnnotation {
mapView.selectAnnotation(selAnno, animated: false)
}
}
}
}
log.verbose("didSelectAnnotationView >> \(String(describing: view.annotation!.title))")
}
func mapView(_ mapView: MKMapView, didDeselect view: MKAnnotationView) {
delayed(0.0)
{
if view.annotation === self.selectedAnnotation {
if let selAnno=self.selectedAnnotation {
mapView.selectAnnotation(selAnno, animated: false)
}
}
}
log.verbose("didDeselectAnnotationView >> \(String(describing: view.annotation!.title))")
}
//MARK: - IBActions
@IBAction func searchButtonTabbed(_ sender: AnyObject) {
removeAllEntityObjects()
self.tableView.reloadData();
let searchQueue=CancelableOperationQueue(name: "Objektsuche", afterCancellation: {
self.removeAllEntityObjects()
self.tableView.reloadData();
forceProgressInWaitingHUD(0)
hideWaitingHUD()
})
showWaitingHUD(queue: searchQueue, text:"Objektsuche")
var mRect : MKMapRect
if focusToggle.isOn {
mRect = createFocusRect()
}
else {
mRect = self.mapView.visibleMapRect;
}
let mRegion=MKCoordinateRegionForMapRect(mRect);
let x1=mRegion.center.longitude-(mRegion.span.longitudeDelta/2)
let y1=mRegion.center.latitude-(mRegion.span.latitudeDelta/2)
let x2=mRegion.center.longitude+(mRegion.span.longitudeDelta/2)
let y2=mRegion.center.latitude+(mRegion.span.latitudeDelta/2)
let ewktMapExtent="SRID=4326;POLYGON((\(x1) \(y1),\(x1) \(y2),\(x2) \(y2),\(x2) \(y1),\(x1) \(y1)))";
CidsConnector.sharedInstance().search(ewktMapExtent, leuchtenEnabled: isLeuchtenEnabled, mastenEnabled: isMastenEnabled, mauerlaschenEnabled: isMauerlaschenEnabled, leitungenEnabled: isleitungenEnabled,schaltstellenEnabled: isSchaltstelleEnabled, queue: searchQueue ) {
assert(!Thread.isMainThread )
DispatchQueue.main.async {
CidsConnector.sharedInstance().sortSearchResults()
self.tableView.reloadData();
for (_, objArray) in CidsConnector.sharedInstance().searchResults{
for obj in objArray {
obj.addToMapView(self.mapView);
}
}
hideWaitingHUD()
}
}
}
@IBAction func itemArbeitsauftragTapped(_ sender: AnyObject) {
if let gbe=CidsConnector.sharedInstance().selectedArbeitsauftrag {
let detailVC=DetailVC(nibName: "DetailVC", bundle: nil)
shownDetails=detailVC
let cellDataProvider=gbe as CellDataProvider
detailVC.sections=cellDataProvider.getDataSectionKeys()
detailVC.setCellData(cellDataProvider.getAllData())
detailVC.objectToShow=gbe
detailVC.title=cellDataProvider.getTitle()
let icon=UIBarButtonItem()
icon.action=#selector(MainViewController.back(_:))
//icon.image=getGlyphedImage("icon-chevron-left")
icon.image=GlyphTools.sharedInstance().getGlyphedImage("icon-chevron-left", fontsize: 11, size: CGSize(width: 14, height: 14))
detailVC.navigationItem.leftBarButtonItem = icon
let detailNC=UINavigationController(rootViewController: detailVC)
selectedAnnotation=nil
detailNC.modalPresentationStyle = UIModalPresentationStyle.popover
detailNC.popoverPresentationController?.barButtonItem = itemArbeitsauftrag
present(detailNC, animated: true, completion: nil)
}
else if let indexPath=tableView.indexPathForSelectedRow , let aa = CidsConnector.sharedInstance().searchResults[Entity.byIndex((indexPath as NSIndexPath).section)]?[(indexPath as NSIndexPath).row] as? Arbeitsauftrag {
selectArbeitsauftrag(aa)
}
}
@IBAction func mapTypeButtonTabbed(_ sender: AnyObject) {
switch(mapTypeSegmentedControl.selectedSegmentIndex){
case 0:
mapView.mapType=MKMapType.standard;
case 1:
mapView.mapType=MKMapType.hybrid;
case 2:
mapView.mapType=MKMapType.satellite;
default:
mapView.mapType=MKMapType.standard;
}
}
@IBAction func lookUpButtonTabbed(_ sender: AnyObject) {
if let team = CidsConnector.sharedInstance().selectedTeam {
selectArbeitsauftrag(nil,showActivityIndicator: false)
removeAllEntityObjects()
let aaSearchQueue=CancelableOperationQueue(name: "Arbeitsaufträge suchen", afterCancellation: {
self.selectArbeitsauftrag(nil,showActivityIndicator: false)
self.removeAllEntityObjects()
forceProgressInWaitingHUD(0)
hideWaitingHUD()
})
showWaitingHUD(queue: aaSearchQueue, text:"Arbeitsaufträge suchen")
CidsConnector.sharedInstance().searchArbeitsauftraegeForTeam(team, queue: aaSearchQueue) { () -> () in
DispatchQueue.main.async {
CidsConnector.sharedInstance().sortSearchResults()
self.tableView.reloadData();
var annos: [MKAnnotation]=[]
for (_, objArray) in CidsConnector.sharedInstance().searchResults{
for obj in objArray {
obj.addToMapView(self.mapView);
if let anno=obj.mapObject as? MKAnnotation {
annos.append(anno)
}
}
}
hideWaitingHUD(delayedText: "Veranlassungen werden im\nHintergrund nachgeladen", delay: 1)
DispatchQueue.main.async {
self.zoomToFitMapAnnotations(annos)
}
}
}
}
else {
let alert=UIAlertController(title: "Kein Team ausgewählt",message:"Bitte wählen Sie zuerst ein Team aus", preferredStyle: UIAlertControllerStyle.alert)
let okButton = UIAlertAction(title: "Ok", style: .default, handler: nil)
alert.addAction(okButton)
show(alert,sender: self)
}
}
@IBAction func focusItemTabbed(_ sender: AnyObject) {
focusToggle.setOn(!focusToggle.isOn, animated: true)
focusToggleValueChanged(self)
}
@IBAction func focusToggleValueChanged(_ sender: AnyObject) {
ensureFocusRectangleIsDisplayedWhenAndWhereItShould()
}
@IBAction func brightenItemTabbed(_ sender: AnyObject) {
brightenToggle.setOn(!brightenToggle.isOn, animated: true)
brightenToggleValueChanged(self)
}
@IBAction func brightenToggleValueChanged(_ sender: AnyObject) {
ensureBrightOverlayIsDisplayedWhenItShould()
}
@IBAction func geoSearchButtonTabbed(_ sender: AnyObject) {
if textfieldGeoSearch.text! != "" {
geoSearch()
}
}
@IBAction func geoSearchInputDidEnd(_ sender: AnyObject) {
geoSearch()
}
@IBAction func zoomToAllObjectsTapped(_ sender: AnyObject) {
var annos: [MKAnnotation]=[]
for (_, objArray) in CidsConnector.sharedInstance().searchResults{
for obj in objArray {
if let anno=obj.mapObject as? MKAnnotation {
annos.append(anno)
}
}
}
DispatchQueue.main.async {
self.zoomToFitMapAnnotations(annos)
}
}
// MARK: - Selector functions
func back(_ sender: UIBarButtonItem) {
if let details=shownDetails{
details.dismiss(animated: true, completion:
{ () -> Void in
CidsConnector.sharedInstance().selectedArbeitsauftrag=nil
self.selectArbeitsauftrag(nil)
self.shownDetails=nil
})
}
}
func createFocusRect() -> MKMapRect {
let mRect = self.mapView.visibleMapRect;
let newSize = MKMapSize(width: mRect.size.width/3,height: mRect.size.height/3)
let newOrigin = MKMapPoint(x: mRect.origin.x+newSize.width, y: mRect.origin.y+newSize.height)
return MKMapRect(origin: newOrigin,size: newSize)
}
func zoomToFitMapAnnotations(_ annos: [MKAnnotation]) {
if annos.count == 0 {return}
var topLeftCoordinate = CLLocationCoordinate2D(latitude: -90, longitude: 180)
var bottomRightCoordinate = CLLocationCoordinate2D(latitude: 90, longitude: -180)
for annotation in annos {
if let poly=annotation as? MKMultiPoint {
let points=poly.points()
for i in 0 ... poly.pointCount-1 { //last point is jwd (dono why)
let coord = MKCoordinateForMapPoint(points[i])
topLeftCoordinate.longitude = fmin(topLeftCoordinate.longitude, coord.longitude)
topLeftCoordinate.latitude = fmax(topLeftCoordinate.latitude, coord.latitude)
bottomRightCoordinate.longitude = fmax(bottomRightCoordinate.longitude, coord.longitude)
bottomRightCoordinate.latitude = fmin(bottomRightCoordinate.latitude, coord.latitude)
}
}
else {
topLeftCoordinate.longitude = fmin(topLeftCoordinate.longitude, annotation.coordinate.longitude)
topLeftCoordinate.latitude = fmax(topLeftCoordinate.latitude, annotation.coordinate.latitude)
bottomRightCoordinate.longitude = fmax(bottomRightCoordinate.longitude, annotation.coordinate.longitude)
bottomRightCoordinate.latitude = fmin(bottomRightCoordinate.latitude, annotation.coordinate.latitude)
}
}
let center = CLLocationCoordinate2D(latitude: topLeftCoordinate.latitude - (topLeftCoordinate.latitude - bottomRightCoordinate.latitude) * 0.5, longitude: topLeftCoordinate.longitude - (topLeftCoordinate.longitude - bottomRightCoordinate.longitude) * 0.5)
// Add a little extra space on the sides
let span = MKCoordinateSpanMake(fabs(topLeftCoordinate.latitude - bottomRightCoordinate.latitude) * 1.3, fabs(bottomRightCoordinate.longitude - topLeftCoordinate.longitude) * 1.3)
var region = MKCoordinateRegion(center: center, span: span)
region = self.mapView.regionThatFits(region)
self.mapView.setRegion(region, animated: true)
}
func selectArbeitsauftrag(_ arbeitsauftrag: Arbeitsauftrag?, showActivityIndicator: Bool = true) {
let sel=selectedAnnotation
selectedAnnotation=nil
if let s=sel {
mapView.deselectAnnotation(s, animated: false)
}
CidsConnector.sharedInstance().selectedArbeitsauftrag=arbeitsauftrag
if showActivityIndicator {
showWaitingHUD(queue: CancelableOperationQueue(name:"dummy", afterCancellation: {}))
}
let overlays=self.mapView.overlays
self.mapView.removeOverlays(overlays)
for anno in self.mapView.selectedAnnotations {
self.mapView.deselectAnnotation(anno, animated: false)
}
var zoomToShowAll=true
if let aa=arbeitsauftrag {
CidsConnector.sharedInstance().allArbeitsauftraegeBeforeCurrentSelection=CidsConnector.sharedInstance().searchResults
fillArbeitsauftragIntoTable(aa)
} else {
itemArbeitsauftrag.title="Kein Arbeitsauftrag ausgewählt (\(CidsConnector.sharedInstance().selectedTeam?.name ?? "-"))"
self.removeAllEntityObjects()
CidsConnector.sharedInstance().searchResults=CidsConnector.sharedInstance().allArbeitsauftraegeBeforeCurrentSelection
zoomToShowAll=false
}
visualizeAllSearchResultsInMap(zoomToShowAll: zoomToShowAll, showActivityIndicator: showActivityIndicator)
}
func fillArbeitsauftragIntoTable(_ arbeitsauftrag: Arbeitsauftrag) {
removeAllEntityObjects()
itemArbeitsauftrag.title="\(arbeitsauftrag.nummer!) (\(CidsConnector.sharedInstance().selectedTeam?.name ?? "-"))"
if let protokolle=arbeitsauftrag.protokolle {
for prot in protokolle {
if let _=CidsConnector.sharedInstance().searchResults[Entity.PROTOKOLLE] {
CidsConnector.sharedInstance().searchResults[Entity.PROTOKOLLE]!.append(prot)
}
else {
CidsConnector.sharedInstance().searchResults.updateValue([prot], forKey: Entity.PROTOKOLLE)
}
}
}
}
func visualizeAllSearchResultsInMap(zoomToShowAll: Bool,showActivityIndicator:Bool ) {
func doIt(){
self.selectedAnnotation=nil
self.mapView.deselectAnnotation(selectedAnnotation, animated: false)
var annos: [MKAnnotation]=[]
for (_, objArray) in CidsConnector.sharedInstance().searchResults{
for obj in objArray {
obj.addToMapView(self.mapView);
if let anno=obj.mapObject as? MKAnnotation {
annos.append(anno)
}
}
}
if zoomToShowAll {
self.zoomToFitMapAnnotations(annos)
}
if showActivityIndicator {
hideWaitingHUD()
}
}
if Thread.isMainThread {
doIt()
}
else {
DispatchQueue.main.async {
doIt()
}
}
}
// MARK: - public functions
func mapTapped(_ sender: UITapGestureRecognizer) {
let touchPt = sender.location(in: mapView)
//let hittedUI = mapView.hitTest(touchPt, withEvent: nil)
// println(hittedUI)
log.verbose("mapTabbed")
let buffer=CGFloat(22)
var foundPolyline: GeoBaseEntityStyledMkPolylineAnnotation?
var foundPoint: GeoBaseEntityPointAnnotation?
var foundPolygon: GeoBaseEntityStyledMkPolygonAnnotation?
for anno: AnyObject in mapView.annotations {
if let pointAnnotation = anno as? GeoBaseEntityPointAnnotation {
let cgPoint = mapView.convert(pointAnnotation.coordinate, toPointTo: mapView)
let path = CGMutablePath()
path.move(to: cgPoint)
path.addLine(to: cgPoint)
let fuzzyPath=CGPath(__byStroking: path, transform: nil, lineWidth: buffer, lineCap: CGLineCap.round, lineJoin: CGLineJoin.round, miterLimit: 0.0)
if (fuzzyPath?.contains(touchPt) == true) {
foundPoint = pointAnnotation
log.verbose("foundPoint")
selectOnMap(foundPoint?.getGeoBaseEntity())
selectInTable(foundPoint?.getGeoBaseEntity())
break
}
}
}
if (foundPoint == nil){
for overlay: AnyObject in mapView.overlays {
if let lineAnnotation = overlay as? GeoBaseEntityStyledMkPolylineAnnotation{
let path = CGMutablePath()
for i in 0...lineAnnotation.pointCount-1 {
let mapPoint = lineAnnotation.points()[i]
let cgPoint = mapView.convert(MKCoordinateForMapPoint(mapPoint), toPointTo: mapView)
if i==0 {
path.move(to: cgPoint)
}
else {
path.addLine(to: cgPoint);
}
}
let fuzzyPath=CGPath(__byStroking: path, transform: nil, lineWidth: buffer, lineCap: CGLineCap.round, lineJoin: CGLineJoin.round, miterLimit: 0.0)
if (fuzzyPath?.contains(touchPt) == true) {
foundPolyline = lineAnnotation
break
}
}
if let polygonAnnotation = overlay as? GeoBaseEntityStyledMkPolygonAnnotation {
let path = CGMutablePath()
for i in 0...polygonAnnotation.pointCount-1 {
let mapPoint = polygonAnnotation.points()[i]
let cgPoint = mapView.convert(MKCoordinateForMapPoint(mapPoint), toPointTo: mapView)
if i==0 {
path.move(to: cgPoint)
}
else {
path.addLine(to: cgPoint)
}
}
if (path.contains(touchPt) == true ) {
foundPolygon=polygonAnnotation
break
}
}
}
if let hitPolyline = foundPolyline {
selectOnMap(hitPolyline.getGeoBaseEntity())
selectInTable(hitPolyline.getGeoBaseEntity())
}
else if let hitPolygon=foundPolygon{
selectOnMap(hitPolygon.getGeoBaseEntity())
selectInTable(hitPolygon.getGeoBaseEntity())
}
else {
selectOnMap(nil)
}
}
}
func selectOnMap(_ geoBaseEntityToSelect : GeoBaseEntity?){
if highlightedLine != nil {
mapView.remove(highlightedLine!);
}
if (selectedAnnotation != nil){
mapView.deselectAnnotation(selectedAnnotation, animated: false)
}
if let geoBaseEntity = geoBaseEntityToSelect{
let mapObj=geoBaseEntity.mapObject
if let mO=mapObj as? MKAnnotation {
mapView.selectAnnotation(mO, animated: true);
selectedAnnotation=mapObj as? MKAnnotation
}
if mapObj is GeoBaseEntityPointAnnotation {
}
else if mapObj is GeoBaseEntityStyledMkPolylineAnnotation {
let line = mapObj as! GeoBaseEntityStyledMkPolylineAnnotation;
highlightedLine = HighlightedMkPolyline(points: line.points(), count: line.pointCount);
mapView.remove(line);
mapView.add(highlightedLine!);
mapView.add(line); //bring the highlightedLine below the line
} else if mapObj is GeoBaseEntityStyledMkPolygonAnnotation {
//let polygon=mapObj as! GeoBaseEntityStyledMkPolygonAnnotation
//let annos=[polygon]
//zoomToFitMapAnnotations(annos)
}
} else {
selectedAnnotation=nil
}
}
func selectInTable(_ geoBaseEntityToSelect : GeoBaseEntity?, scrollToShow: Bool=true){
if let geoBaseEntity = geoBaseEntityToSelect{
let entity=geoBaseEntity.getType()
//need old fashioned loop for index
for i in 0...CidsConnector.sharedInstance().searchResults[entity]!.count-1 {
var results : [GeoBaseEntity] = CidsConnector.sharedInstance().searchResults[entity]!
if results[i].id == geoBaseEntity.id {
if scrollToShow {
tableView.selectRow(at: IndexPath(row: i, section: entity.index()), animated: true, scrollPosition: UITableViewScrollPosition.top)
}
else {
tableView.selectRow(at: IndexPath(row: i, section: entity.index()), animated: true, scrollPosition: UITableViewScrollPosition.none)
}
break;
}
}
}
}
func mapView(_ mapView: MKMapView, annotationView view: MKAnnotationView, calloutAccessoryControlTapped control: UIControl) {
//var detailVC=LeuchtenDetailsViewController()
// var detailVC=storyboard!.instantiateViewControllerWithIdentifier("LeuchtenDetails") as UIViewController
var geoBaseEntity: GeoBaseEntity?
if let pointAnnotation = view.annotation as? GeoBaseEntityPointAnnotation {
geoBaseEntity=pointAnnotation.geoBaseEntity
}
else if let lineAnnotation = view.annotation as? GeoBaseEntityStyledMkPolylineAnnotation {
geoBaseEntity=lineAnnotation.geoBaseEntity
}else if let polygonAnnotation = view.annotation as? GeoBaseEntityStyledMkPolygonAnnotation {
geoBaseEntity=polygonAnnotation.geoBaseEntity
}
if let gbe = geoBaseEntity {
let detailVC=DetailVC(nibName: "DetailVC", bundle: nil)
if let cellDataProvider=gbe as? CellDataProvider {
detailVC.sections=cellDataProvider.getDataSectionKeys()
detailVC.setCellData(cellDataProvider.getAllData())
detailVC.objectToShow=gbe
detailVC.title=cellDataProvider.getTitle()
let icon=UIBarButtonItem()
icon.image=GlyphTools.sharedInstance().getGlyphedImage(cellDataProvider.getDetailGlyphIconString())
detailVC.navigationItem.leftBarButtonItem = icon
}
if let actionProvider=gbe as? ActionProvider {
detailVC.actions=actionProvider.getAllActions()
let action = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.action, target: detailVC, action:#selector(DetailVC.moreAction))
detailVC.navigationItem.rightBarButtonItem = action
}
let detailNC=UINavigationController(rootViewController: detailVC)
selectedAnnotation=nil
mapView.deselectAnnotation(view.annotation, animated: false)
detailNC.modalPresentationStyle = UIModalPresentationStyle.popover
detailNC.popoverPresentationController?.sourceView = mapView
detailNC.popoverPresentationController?.sourceRect = view.frame
detailNC.popoverPresentationController?.permittedArrowDirections = UIPopoverArrowDirection.any
present(detailNC, animated: true, completion: nil)
}
}
func clearAll() {
CidsConnector.sharedInstance().selectedArbeitsauftrag=nil
CidsConnector.sharedInstance().allArbeitsauftraegeBeforeCurrentSelection=[Entity: [GeoBaseEntity]]()
CidsConnector.sharedInstance().veranlassungsCache=[String:Veranlassung]()
removeAllEntityObjects()
}
func removeAllEntityObjects(){
for (_, entityArray) in CidsConnector.sharedInstance().searchResults{
for obj in entityArray {
DispatchQueue.main.async {
obj.removeFromMapView(self.mapView);
}
}
}
CidsConnector.sharedInstance().searchResults=[Entity: [GeoBaseEntity]]()
DispatchQueue.main.async {
self.tableView.reloadData();
}
}
// MARK: - private funcs
fileprivate func geoSearch(){
if matchingSearchItems.count>0 {
self.mapView.removeAnnotations(self.matchingSearchItemsAnnotations)
self.matchingSearchItems.removeAll(keepingCapacity: false)
matchingSearchItemsAnnotations.removeAll(keepingCapacity: false)
}
let request = MKLocalSearchRequest()
request.naturalLanguageQuery = "Wuppertal, \(textfieldGeoSearch.text!)"
request.region = mapView.region
let localSearch = MKLocalSearch(request: request)
localSearch.start { (responseIn, errorIn) -> Void in
if let error = errorIn {
log.error("Error occured in search: \(error.localizedDescription)")
} else if let response=responseIn {
if response.mapItems.count == 0 {
log.warning("No matches found")
} else {
log.verbose("Matches found")
for item in response.mapItems as [MKMapItem] {
self.matchingSearchItems.append(item as MKMapItem)
log.verbose("Matching items = \(self.matchingSearchItems.count)")
let annotation = MatchingSearchItemsAnnotations()
annotation.coordinate = item.placemark.coordinate
annotation.title = item.name
self.matchingSearchItemsAnnotations.append(annotation)
self.mapView.addAnnotation(annotation)
}
self.mapView.showAnnotations(self.matchingSearchItemsAnnotations, animated: true)
}
}
}
}
fileprivate func ensureBrightOverlayIsDisplayedWhenItShould(){
if brightenToggle.isOn {
let overlays=mapView.overlays
mapView.removeOverlays(overlays)
mapView.add(brightOverlay)
mapView.addOverlays(overlays)
}
else {
mapView.remove(brightOverlay)
}
}
fileprivate func ensureFocusRectangleIsDisplayedWhenAndWhereItShould(){
focusRectShape.removeFromSuperlayer()
if focusToggle.isOn {
let path = UIBezierPath()
let w = self.mapView.frame.width / 3
let h = self.mapView.frame.height / 3
let x1 = w
let y1 = h
let x2 = x1 + w
let y2 = y1
let x3 = x2
let y3 = y2 + h
let x4 = x1
let y4 = y3
path.move(to: CGPoint(x: x1, y: y1))
path.addLine(to: CGPoint(x: x2, y: y2))
path.addLine(to: CGPoint(x: x3, y: y3))
path.addLine(to: CGPoint(x: x4, y: y4))
path.close()
focusRectShape.path = path.cgPath
mapView.layer.addSublayer(focusRectShape)
}
}
// func textFieldShouldReturn(textField: UITextField) -> Bool {
// self.view.endEditing(true)
// return false
// }
}
| 1a8a2b9fefb8f804d9c0a8068c7b0993 | 42.103226 | 277 | 0.600894 | false | false | false | false |
GreenCom-Networks/ios-charts | refs/heads/master | Advanced/Pods/Charts/Charts/Classes/Highlight/BarChartHighlighter.swift | apache-2.0 | 7 | //
// ChartBarHighlighter.swift
// Charts
//
// Created by Daniel Cohen Gindi on 26/7/15.
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/ios-charts
//
import Foundation
import CoreGraphics
public class BarChartHighlighter: ChartHighlighter
{
public override func getHighlight(x x: Double, y: Double) -> ChartHighlight?
{
let h = super.getHighlight(x: x, y: y)
if h === nil
{
return h
}
else
{
if let set = self.chart?.data?.getDataSetByIndex(h!.dataSetIndex) as? BarChartDataSet
{
if set.isStacked
{
// create an array of the touch-point
var pt = CGPoint()
pt.y = CGFloat(y)
// take any transformer to determine the x-axis value
self.chart?.getTransformer(set.axisDependency).pixelToValue(&pt)
return getStackedHighlight(old: h, set: set, xIndex: h!.xIndex, dataSetIndex: h!.dataSetIndex, yValue: Double(pt.y))
}
}
return h
}
}
public override func getXIndex(x: Double) -> Int
{
if let barChartData = self.chart?.data as? BarChartData
{
if !barChartData.isGrouped
{
return super.getXIndex(x)
}
else
{
let baseNoSpace = getBase(x)
let setCount = barChartData.dataSetCount
var xIndex = Int(baseNoSpace) / setCount
let valCount = barChartData.xValCount
if xIndex < 0
{
xIndex = 0
}
else if xIndex >= valCount
{
xIndex = valCount - 1
}
return xIndex
}
}
else
{
return 0
}
}
public override func getDataSetIndex(xIndex xIndex: Int, x: Double, y: Double) -> Int
{
if let barChartData = self.chart?.data as? BarChartData
{
if !barChartData.isGrouped
{
return 0
}
else
{
let baseNoSpace = getBase(x)
let setCount = barChartData.dataSetCount
var dataSetIndex = Int(baseNoSpace) % setCount
if dataSetIndex < 0
{
dataSetIndex = 0
}
else if dataSetIndex >= setCount
{
dataSetIndex = setCount - 1
}
return dataSetIndex
}
}
else
{
return 0
}
}
/// This method creates the Highlight object that also indicates which value of a stacked BarEntry has been selected.
/// - parameter old: the old highlight object before looking for stacked values
/// - parameter set:
/// - parameter xIndex:
/// - parameter dataSetIndex:
/// - parameter yValue:
/// - returns:
public func getStackedHighlight(old old: ChartHighlight?, set: BarChartDataSet, xIndex: Int, dataSetIndex: Int, yValue: Double) -> ChartHighlight?
{
let entry = set.entryForXIndex(xIndex) as? BarChartDataEntry
if entry?.values === nil
{
return old
}
if let ranges = getRanges(entry: entry!)
where ranges.count > 0
{
let stackIndex = getClosestStackIndex(ranges: ranges, value: yValue)
let h = ChartHighlight(xIndex: xIndex, dataSetIndex: dataSetIndex, stackIndex: stackIndex, range: ranges[stackIndex])
return h
}
return nil
}
/// Returns the index of the closest value inside the values array / ranges (stacked barchart) to the value given as a parameter.
/// - parameter entry:
/// - parameter value:
/// - returns:
public func getClosestStackIndex(ranges ranges: [ChartRange]?, value: Double) -> Int
{
if ranges == nil
{
return 0
}
var stackIndex = 0
for range in ranges!
{
if range.contains(value)
{
return stackIndex
}
else
{
stackIndex += 1
}
}
let length = max(ranges!.count - 1, 0)
return (value > ranges![length].to) ? length : 0
}
/// Returns the base x-value to the corresponding x-touch value in pixels.
/// - parameter x:
/// - returns:
public func getBase(x: Double) -> Double
{
if let barChartData = self.chart?.data as? BarChartData
{
// create an array of the touch-point
var pt = CGPoint()
pt.x = CGFloat(x)
// take any transformer to determine the x-axis value
self.chart?.getTransformer(ChartYAxis.AxisDependency.Left).pixelToValue(&pt)
let xVal = Double(pt.x)
let setCount = barChartData.dataSetCount ?? 0
// calculate how often the group-space appears
let steps = Int(xVal / (Double(setCount) + Double(barChartData.groupSpace)))
let groupSpaceSum = Double(barChartData.groupSpace) * Double(steps)
let baseNoSpace = xVal - groupSpaceSum
return baseNoSpace
}
else
{
return 0.0
}
}
/// Splits up the stack-values of the given bar-entry into Range objects.
/// - parameter entry:
/// - returns:
public func getRanges(entry entry: BarChartDataEntry) -> [ChartRange]?
{
let values = entry.values
if (values == nil)
{
return nil
}
var negRemain = -entry.negativeSum
var posRemain: Double = 0.0
var ranges = [ChartRange]()
ranges.reserveCapacity(values!.count)
for i in 0 ..< values!.count
{
let value = values![i]
if value < 0
{
ranges.append(ChartRange(from: negRemain, to: negRemain + abs(value)))
negRemain += abs(value)
}
else
{
ranges.append(ChartRange(from: posRemain, to: posRemain+value))
posRemain += value
}
}
return ranges
}
}
| 296b46a963974c9f0078a96f63c3aee0 | 27.829167 | 150 | 0.489088 | false | false | false | false |
Pocketbrain/nativeadslib-ios | refs/heads/master | PocketMediaNativeAds/Core/adPosition/MarginAdPosition.swift | mit | 1 | //
// MarginAdPosition.swift
// PocketMediaNativeAds
//
// Created by Iain Munro on 04/10/2016.
//
//
import Foundation
/**
Error this the MarginAdPosition can throw if asked for a position
*/
public enum MarginAdPositionError: Error {
/// Invalid margin is set.
case invalidmargin
}
/**
This ad position implementation makes the ads show up at a set interval (margin).
*/
@objc
open class MarginAdPosition: NSObject, AdPosition {
/// The margin (interval). Every x amount of position place an ad.
fileprivate var margin: Int = 2
/// The offset before an ad should appear.
fileprivate var adPositionOffset: Int = -1
/// The current value the positioner is at.
fileprivate var currentValue: Int = 0
/**
Initializer.
- parameter margin: The amount of entries before an ad. (default 2).
- paramter adPositionOffset: The offset before an ad should appear.
*/
public init(margin: Int = 2, adPositionOffset: Int = 0) {
super.init()
self.margin = margin + 1
setadPositionOffset(adPositionOffset)
reset()
}
/**
Called every time the positions are calculated. It resets the ad positioner.
*/
open func reset() {
self.currentValue = adPositionOffset
}
/**
Generates a unique position (integer) of where a new ad should be located.
- Returns:
a unique integer of where a new ad should be located.
- Important:
This method throws if it can't return a unique position
*/
open func getAdPosition(_ maxSize: Int) throws -> NSNumber {
if margin < 1 {
throw MarginAdPositionError.invalidmargin
}
currentValue += margin
return NSNumber(value: currentValue as Int)
}
/**
Setter method to set self.adPositionOffset.
- parameter position: The position of the first ad. Default is 0
*/
open func setadPositionOffset(_ position: Int) {
self.adPositionOffset = position < 0 ? 0 : position - 1
}
}
| bc9a517444849ca6c2bfb6db96ffe688 | 27.25 | 82 | 0.651917 | false | false | false | false |
srn214/Floral | refs/heads/master | Floral/Pods/SwiftLocation/Sources/Auto Complete/Services/GoogleAutoCompleteRequest.swift | mit | 1 | //
// SwiftLocation - Efficient Location Tracking for iOS
//
// Created by Daniele Margutti
// - Web: https://www.danielemargutti.com
// - Twitter: https://twitter.com/danielemargutti
// - Mail: [email protected]
//
// Copyright © 2019 Daniele Margutti. Licensed under MIT License.
import Foundation
public class GoogleAutoCompleteRequest: AutoCompleteRequest {
// MARK: - Private Properties -
/// JSON Operation
private var jsonOperation: JSONOperation?
// MARK: - Public Functions -
public override func start() {
guard state != .expired else {
return
}
// Compose the request URL
guard let url = composeURL() else {
dispatch(data: .failure(.generic("Failed to compose valid request's URL.")))
return
}
jsonOperation = JSONOperation(url, timeout: self.timeout?.interval)
jsonOperation?.start { response in
switch response {
case .failure(let error):
self.stop(reason: error, remove: true)
case .success(let json):
// Validate google response
let status: String? = valueAtKeyPath(root: json, ["status"])
if status != "OK",
let errorMsg: String = valueAtKeyPath(root: json, ["error_message"]), !errorMsg.isEmpty {
self.stop(reason: .generic(errorMsg), remove: true)
return
}
switch self.options!.operation {
case .partialSearch:
let places = self.parsePartialMatchJSON(json)
self.dispatch(data: .success(places), andComplete: true)
case .placeDetail:
var places = [PlaceMatch]()
if let resultNode: Any = valueAtKeyPath(root: json, ["result"]) {
let place = Place(googleJSON: resultNode)
places.append(.fullMatch(place))
}
self.value = places
self.dispatch(data: .success(places), andComplete: true)
}
}
}
}
// MARK: - Private Helper Functions -
private func parsePartialMatchJSON(_ json: Any) -> [PlaceMatch] {
let rawList: [Any]? = valueAtKeyPath(root: json, ["predictions"])
let list: [PlaceMatch]? = rawList?.map({ rawItem in
let place = PlacePartialMatch(googleJSON: rawItem)
return PlaceMatch.partialMatch(place)
})
return list ?? []
}
private func composeURL() -> URL? {
guard let APIKey = (options as? GoogleOptions)?.APIKey else {
dispatch(data: .failure(.missingAPIKey))
return nil
}
var serverParams = [URLQueryItem]()
var baseURL: URL!
switch options!.operation {
case .partialSearch:
baseURL = URL(string: "https://maps.googleapis.com/maps/api/place/autocomplete/json")!
serverParams.append(URLQueryItem(name: "input", value: options!.operation.value))
case .placeDetail:
baseURL = URL(string: "https://maps.googleapis.com/maps/api/place/details/json")!
serverParams.append(URLQueryItem(name: "placeid", value: options!.operation.value))
}
var urlComponents = URLComponents(url: baseURL, resolvingAgainstBaseURL: false)
serverParams.append(URLQueryItem(name: "key", value: APIKey)) // google api key
serverParams += (options?.serverParams() ?? [])
urlComponents?.queryItems = serverParams
return urlComponents?.url
}
}
| 8091a8b37c6cf7e1bcec4f7e8991435f | 35.269231 | 109 | 0.562831 | false | false | false | false |
XCEssentials/UniFlow | refs/heads/master | Sources/0_Helpers/Publisher+Dispatcher.swift | mit | 1 | /*
MIT License
Copyright (c) 2016 Maxim Khatskevich ([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 Combine
//---
public
extension Publisher
{
func executeNow()
{
_ = sink(receiveCompletion: { _ in }, receiveValue: { _ in })
}
}
// MARK: - Access log - Processed vs. Rejected
public
extension Publisher where Output == Dispatcher.AccessReport, Failure == Never
{
var onProcessed: AnyPublisher<Dispatcher.ProcessedActionReport, Failure>
{
return self
.compactMap {
switch $0.outcome
{
case .success(let mutations):
return .init(
timestamp: $0.timestamp,
mutations: mutations,
storage: $0.storage,
origin: $0.origin
)
default:
return nil
}
}
.eraseToAnyPublisher()
}
var onRejected: AnyPublisher<Dispatcher.RejectedActionReport, Failure>
{
return self
.compactMap {
switch $0.outcome
{
case .failure(let reason):
return .init(
timestamp: $0.timestamp,
reason: reason,
storage: $0.storage,
origin: $0.origin
)
default:
return nil
}
}
.eraseToAnyPublisher()
}
}
// MARK: - Access log - Processed - get individual mutations
public
extension Publisher where Output == Dispatcher.ProcessedActionReport, Failure == Never
{
var perEachMutation: AnyPublisher<Storage.HistoryElement, Failure>
{
flatMap(\.mutations.publisher).eraseToAnyPublisher()
}
}
public
extension Publisher where Output == Storage.HistoryElement, Failure == Never
{
func `as`<T: SomeMutationDecriptor>(
_: T.Type
) -> AnyPublisher<T, Failure> {
compactMap(T.init(from:)).eraseToAnyPublisher()
}
}
// MARK: - Access log - Processed - get features statuses (dashboard)
public
extension Publisher where Output == Dispatcher.ProcessedActionReport, Failure == Never
{
var statusReport: AnyPublisher<[FeatureStatus], Failure>
{
self
.filter {
!$0.mutations.isEmpty
}
.map {
$0.storage
.allStates
.map(
FeatureStatus.init
)
}
.eraseToAnyPublisher()
}
}
public
extension Publisher where Output == [FeatureStatus], Failure == Never
{
func matched(
with features: [SomeFeature.Type]
) -> AnyPublisher<Output, Failure> {
self
.map { existingStatuses in
features
.map { feature in
existingStatuses
.first(where: {
if
let state = $0.state
{
return type(of: state).feature.name == feature.name
}
else
{
return false
}
})
?? .init(missing: feature)
}
}
.eraseToAnyPublisher()
}
}
| 21cd2c3f87e96e29692358eccf20731e | 28.544379 | 87 | 0.494092 | false | false | false | false |
wireapp/wire-ios | refs/heads/develop | Wire-iOS Tests/AudioRecordKeyboardViewControllerTests.swift | gpl-3.0 | 1 | //
// Wire
// Copyright (C) 2016 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
import XCTest
@testable import Wire
final class MockAudioRecordKeyboardDelegate: AudioRecordViewControllerDelegate {
var didCancelHitCount = 0
func audioRecordViewControllerDidCancel(_ audioRecordViewController: AudioRecordBaseViewController) {
didCancelHitCount += 1
}
var didStartRecordingHitCount = 0
func audioRecordViewControllerDidStartRecording(_ audioRecordViewController: AudioRecordBaseViewController) {
didStartRecordingHitCount += 1
}
var wantsToSendAudioHitCount = 0
func audioRecordViewControllerWantsToSendAudio(_ audioRecordViewController: AudioRecordBaseViewController, recordingURL: URL, duration: TimeInterval, filter: AVSAudioEffectType) {
wantsToSendAudioHitCount += 1
}
}
final class MockAudioRecorder: AudioRecorderType {
var format: AudioRecorderFormat = .wav
var state: AudioRecorderState = .initializing
var fileURL: URL? = Bundle(for: MockAudioRecorder.self).url(forResource: "audio_sample", withExtension: "m4a")
var maxRecordingDuration: TimeInterval? = 25 * 60
var maxFileSize: UInt64? = 25 * 1024 * 1024 - 32
var currentDuration: TimeInterval = 0.0
var recordTimerCallback: ((TimeInterval) -> Void)?
var recordLevelCallBack: ((RecordingLevel) -> Void)?
var playingStateCallback: ((PlayingState) -> Void)?
var recordStartedCallback: (() -> Void)?
var recordEndedCallback: ((VoidResult) -> Void)?
var startRecordingHitCount = 0
func startRecording(_ completion: @escaping (Bool) -> Void) {
state = .recording(start: 0)
startRecordingHitCount += 1
completion(true)
}
var stopRecordingHitCount = 0
@discardableResult func stopRecording() -> Bool {
state = .stopped
stopRecordingHitCount += 1
return true
}
var deleteRecordingHitCount = 0
func deleteRecording() {
deleteRecordingHitCount += 1
}
var playRecordingHitCount = 0
func playRecording() {
playRecordingHitCount += 1
}
var stopPlayingHitCount = 0
func stopPlaying() {
stopPlayingHitCount += 1
}
func levelForCurrentState() -> RecordingLevel {
return 0
}
func durationForCurrentState() -> TimeInterval? {
return 0
}
func alertForRecording(error: RecordingError) -> UIAlertController? {
return nil
}
}
final class AudioRecordKeyboardViewControllerTests: XCTestCase {
var sut: AudioRecordKeyboardViewController!
var audioRecorder: MockAudioRecorder!
var mockDelegate: MockAudioRecordKeyboardDelegate!
override func setUp() {
super.setUp()
self.audioRecorder = MockAudioRecorder()
self.mockDelegate = MockAudioRecordKeyboardDelegate()
self.sut = AudioRecordKeyboardViewController(audioRecorder: self.audioRecorder)
self.sut.delegate = self.mockDelegate
}
override func tearDown() {
self.sut = nil
self.audioRecorder = nil
self.mockDelegate = nil
super.tearDown()
}
func testThatItStartsRecordingWhenClickingRecordButton() {
// when
self.sut.recordButton.sendActions(for: .touchUpInside)
// then
XCTAssertEqual(self.audioRecorder.startRecordingHitCount, 1)
XCTAssertEqual(self.audioRecorder.stopRecordingHitCount, 0)
XCTAssertEqual(self.audioRecorder.deleteRecordingHitCount, 0)
XCTAssertEqual(self.sut.state, AudioRecordKeyboardViewController.State.recording)
XCTAssertEqual(self.mockDelegate.didStartRecordingHitCount, 1)
}
func testThatItStartsRecordingWhenClickingRecordArea() {
// when
self.sut.recordButtonPressed(self)
// then
XCTAssertEqual(self.audioRecorder.startRecordingHitCount, 1)
XCTAssertEqual(self.audioRecorder.stopRecordingHitCount, 0)
XCTAssertEqual(self.audioRecorder.deleteRecordingHitCount, 0)
XCTAssertEqual(self.sut.state, AudioRecordKeyboardViewController.State.recording)
XCTAssertEqual(self.mockDelegate.didStartRecordingHitCount, 1)
}
func testThatItStopsRecordingWhenClickingStopButton() {
// when
self.sut.recordButtonPressed(self)
// and when
self.sut.stopRecordButton.sendActions(for: .touchUpInside)
// then
XCTAssertEqual(self.audioRecorder.startRecordingHitCount, 1)
XCTAssertEqual(self.audioRecorder.stopRecordingHitCount, 1)
XCTAssertEqual(self.audioRecorder.deleteRecordingHitCount, 0)
XCTAssertEqual(self.sut.state, AudioRecordKeyboardViewController.State.recording)
XCTAssertEqual(self.mockDelegate.didStartRecordingHitCount, 1)
}
func testThatItSwitchesToEffectsScreenAfterRecord() {
// when
self.sut.recordButton.sendActions(for: .touchUpInside)
// and when
self.audioRecorder.recordEndedCallback!(.success)
// then
XCTAssertEqual(self.sut.state, AudioRecordKeyboardViewController.State.effects)
}
func testThatItSwitchesToRecordingAfterRecordDiscarded() {
// when
self.sut.recordButton.sendActions(for: .touchUpInside)
// and when
self.audioRecorder.recordEndedCallback!(.success)
XCTAssertEqual(self.sut.state, AudioRecordKeyboardViewController.State.effects)
// and when
self.sut.redoButton.sendActions(for: .touchUpInside)
// then
XCTAssertEqual(self.sut.state, AudioRecordKeyboardViewController.State.ready)
XCTAssertEqual(self.mockDelegate.didStartRecordingHitCount, 1)
XCTAssertEqual(self.audioRecorder.deleteRecordingHitCount, 1)
}
func testThatItCallsErrorDelegateCallback() {
// when
self.sut.recordButton.sendActions(for: .touchUpInside)
// and when
self.audioRecorder.recordEndedCallback!(.success)
XCTAssertEqual(self.sut.state, AudioRecordKeyboardViewController.State.effects)
// and when
self.sut.cancelButton.sendActions(for: .touchUpInside)
// then
XCTAssertEqual(self.mockDelegate.didStartRecordingHitCount, 1)
XCTAssertEqual(self.mockDelegate.didCancelHitCount, 1)
}
}
| e7670d33609e07451913c1bd03bd986a | 33.615 | 183 | 0.712552 | false | false | false | false |
gintsmurans/SwiftCollection | refs/heads/master | Examples/ApiRouter.swift | mit | 2 | //
// ApiRouter.swift
//
// Created by Gints Murans on 15.08.16.
// Copyright © 2016. g. 4Apps. All rights reserved.
//
import Foundation
import Alamofire
import NetworkExtension
enum ApiRouter: URLRequestConvertible {
case authorize()
case users()
case units
case unitDetails(eanCode: String)
case findPallet(palletNumber: String)
case upload(data: [String: Any])
static let baseURLString = "https://\(Config.api.domain)"
var method: HTTPMethod {
switch self {
// GET
case .authorize:
fallthrough
case .users:
return .get
// POST
case .upload:
return .post
}
}
var path: String {
switch self {
case .authorize:
return "/settings/auth/basic"
case .users:
return "/inventory/api/users"
case .upload:
return "/inventory/api/upload"
}
}
var describing: String {
return urlString
}
var urlString: String {
return "\(ApiRouter.baseURLString)\(path)"
}
func asURLRequest() throws -> URLRequest {
let url = try ApiRouter.baseURLString.asURL()
var urlRequest = URLRequest(url: url.appendingPathComponent(path))
urlRequest.httpMethod = method.rawValue
switch self {
case .upload(let data):
urlRequest = try URLEncoding.default.encode(urlRequest, with: data)
default:
break
}
return urlRequest
}
}
var unitsCache = CacheObject(name: "ApiUnits")
extension Api {
func loadUsers(callback: ApiCallback? = nil) {
// Request
let innerCallback: ApiCallback = { (data, error) in
if let error = error {
if let callback = callback {
callback(nil, error)
}
return
}
self.request(ApiRouter.users()) { (data, error) in
if error != nil {
if let callback = callback {
callback(nil, error)
}
return
}
guard let dataC = data as? [String: Any] else {
print(data!)
if let callback = callback {
callback(nil, ApiError.apiGeneralError(message: "There was an Unknown issue with data", url: nil))
}
return
}
guard let items = dataC["items"] as? [[String: Any]] else {
if let callback = callback {
callback(nil, ApiError.apiGeneralError(message: "There was an Unknown issue with data", url: nil))
}
return
}
if let callback = callback {
callback(items, nil)
}
}
}
// Authenticate first then call all those callbacks
self.authenticateNetworkManager(innerCallback)
}
func upload(_ postData: [String: Any], callback: ApiCallback?) {
// Request
let innerCallback: ApiCallback = { (data, error) in
if let error = error {
if let callback = callback {
callback(nil, error)
}
return
}
self.request(ApiRouter.upload(data: postData), returnType: .json, callback: { (data, error) in
guard let callback = callback else {
return
}
if error != nil {
callback(nil, error)
return
}
callback(data, nil)
})
}
// Authenticate first then call all those callbacks
self.authenticateNetworkManager(innerCallback)
}
}
| 46613d58ece7ee9c1d02fcbd5b0c6dfd | 25.821918 | 122 | 0.501788 | false | false | false | false |
ja-mes/experiments | refs/heads/master | iOS/Permanent Storage/Permanent Storage/AppDelegate.swift | mit | 1 | //
// AppDelegate.swift
// Permanent Storage
//
// Created by James Brown on 8/4/16.
// Copyright © 2016 James Brown. All rights reserved.
//
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> 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 throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
self.saveContext()
}
// MARK: - Core Data stack
lazy var applicationDocumentsDirectory: NSURL = {
// The directory the application uses to store the Core Data store file. This code uses a directory named "com.example.Permanent_Storage" in the application's documents Application Support directory.
let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
return urls[urls.count-1]
}()
lazy var managedObjectModel: NSManagedObjectModel = {
// The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model.
let modelURL = NSBundle.mainBundle().URLForResource("Permanent_Storage", withExtension: "momd")!
return NSManagedObjectModel(contentsOfURL: modelURL)!
}()
lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = {
// The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail.
// Create the coordinator and store
let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("SingleViewCoreData.sqlite")
var failureReason = "There was an error creating or loading the application's saved data."
do {
try coordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil)
} catch {
// Report any error we got.
var dict = [String: AnyObject]()
dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data"
dict[NSLocalizedFailureReasonErrorKey] = failureReason
dict[NSUnderlyingErrorKey] = error as NSError
let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
// Replace this with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(wrappedError), \(wrappedError.userInfo)")
abort()
}
return coordinator
}()
lazy var managedObjectContext: NSManagedObjectContext = {
// Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail.
let coordinator = self.persistentStoreCoordinator
var managedObjectContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType)
managedObjectContext.persistentStoreCoordinator = coordinator
return managedObjectContext
}()
// MARK: - Core Data Saving support
func saveContext () {
if managedObjectContext.hasChanges {
do {
try managedObjectContext.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nserror = error as NSError
NSLog("Unresolved error \(nserror), \(nserror.userInfo)")
abort()
}
}
}
}
| 568c46cbaf6d86026dd7f3d24b14b2e9 | 54.099099 | 291 | 0.720078 | false | false | false | false |
jalehman/todolist-mvvm | refs/heads/master | todolist-mvvm/TodoTableViewModel.swift | mit | 1 | //
// TodoListViewModel.swift
// todolist-mvvm
//
// Created by Josh Lehman on 11/6/15.
// Copyright © 2015 JL. All rights reserved.
//
import Foundation
import ReactiveCocoa
class TodoTableViewModel: ViewModel {
// MARK: Properties
let todos = MutableProperty<[TodoCellViewModel]>([])
let presentCreateTodo: Action<(), CreateTodoViewModel, NoError>
let deleteTodo: Action<(todos: [TodoCellViewModel], cell: TodoCellViewModel), NSIndexPath?, NoError>
// MARK: API
override init(services: ViewModelServicesProtocol) {
self.presentCreateTodo = Action { () -> SignalProducer<CreateTodoViewModel, NoError> in
return SignalProducer(value: CreateTodoViewModel(services: services))
}
self.deleteTodo = Action { (todos: [TodoCellViewModel], cell: TodoCellViewModel) -> SignalProducer<NSIndexPath?, NoError> in
let deleteIndex = todos.indexOf { x -> Bool in
return x.todo == cell.todo
}
if let idx = deleteIndex {
return services.todo.delete(cell.todo)
.map { _ in NSIndexPath(forRow: idx, inSection: 0) }
}
return SignalProducer(value: nil)
}
let createdTodoSignal = presentCreateTodo.values
.flatMap(.Latest) { (vm: CreateTodoViewModel) -> Signal<Todo, NoError> in
return vm.create.values
}
// When "presentCreateTodo" sends a value, push the resulting ViewModel
presentCreateTodo.values.observeNext(services.push)
// When "cancel" sends a value from inside CreateTodoViewModel, pop
presentCreateTodo.values
.flatMap(.Latest) { vm in vm.cancel.values.map { _ in vm } }
.observeNext(services.pop)
// When "create" sends a value from inside CreateTodoViewModel, pop
presentCreateTodo.values
.flatMap(.Latest) { vm in vm.create.values.map { _ in vm } }
.observeNext(services.pop)
super.init(services: services)
func prependTodo(todo: Todo) -> [TodoCellViewModel] {
let new = TodoCellViewModel(services: services, todo: todo)
var tmp = todos.value
tmp.insert(new, atIndex: 0)
return tmp
}
// Whenever a todo is created, create a new viewmodel for it, prepend it to the latest array of todos, and bind the result to todos
todos <~ createdTodoSignal.map(prependTodo)
func removeTodo(at: NSIndexPath?) -> [TodoCellViewModel] {
var tmp = todos.value
tmp.removeAtIndex(at!.row)
return tmp
}
// Whenever a todo is deleted, remove it from the backing array
todos <~ deleteTodo.values.filter { $0 != nil }.map(removeTodo)
}
func clearCompleted() {
for todo in todos.value {
if todo.completed.value {
deleteTodo.apply((todos: todos.value, cell: todo)).start()
}
}
}
} | 6c095bccea4553f6961c42fc6832fc47 | 34.426966 | 139 | 0.58915 | false | false | false | false |
bhajian/raspi-remote | refs/heads/master | Carthage/Checkouts/ios-sdk/Source/TextToSpeechV1/Models/Customization.swift | mit | 1 | /**
* Copyright IBM Corporation 2016
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
import Foundation
import Freddy
/** A custom voice model supported by the Text to Speech service. */
public struct Customization: JSONDecodable {
/// The GUID of the custom voice model.
public let customizationID: String
/// The name of the custom voice model.
public let name: String
/// The language of the custom voice model
public let language: String
/// GUID of the service credentials for the owner of the custom voice model.
public let owner: String
/// The UNIX timestamp that indicates when the custom voice model was created.
/// The timestamp is a count of seconds since the UNIX Epoch of January 1, 1970
/// Coordinated Universal Time (UTC).
public let created: Int
/// The UNIX timestamp that indicates when the custom voice model was last modified.
/// Equals created when a new voice model is first added but has yet to be changed.
public let lastModified: Int
/// A description of the custom voice model.
public let description: String?
/// Used internally to initialize a `Customization` model from JSON.
public init(json: JSON) throws {
customizationID = try json.string("customization_id")
name = try json.string("name")
language = try json.string("language")
owner = try json.string("owner")
created = try json.int("created")
lastModified = try json.int("last_modified")
description = try? json.string("description")
}
}
| bff1c3f1cf7a264fc305f0e5a531f6bb | 36.210526 | 88 | 0.690712 | false | false | false | false |
jindulys/Wikipedia | refs/heads/master | Wikipedia/Code/WMFTableOfContentsViewController.swift | mit | 1 |
import UIKit
public protocol WMFTableOfContentsViewControllerDelegate : AnyObject {
/**
Notifies the delegate that the controller will display
Use this to update the ToC if needed
*/
func tableOfContentsControllerWillDisplay(controller: WMFTableOfContentsViewController)
/**
The delegate is responsible for dismissing the view controller
*/
func tableOfContentsController(controller: WMFTableOfContentsViewController,
didSelectItem item: TableOfContentsItem)
/**
The delegate is responsible for dismissing the view controller
*/
func tableOfContentsControllerDidCancel(controller: WMFTableOfContentsViewController)
func tableOfContentsArticleSite() -> MWKSite
}
public class WMFTableOfContentsViewController: UITableViewController, WMFTableOfContentsAnimatorDelegate {
let tableOfContentsFunnel: ToCInteractionFunnel
var items: [TableOfContentsItem] {
didSet{
self.tableView.reloadData()
}
}
//optional becuase it requires a reference to self to inititialize
var animator: WMFTableOfContentsAnimator?
weak var delegate: WMFTableOfContentsViewControllerDelegate?
// MARK: - Init
public required init(presentingViewController: UIViewController, items: [TableOfContentsItem], delegate: WMFTableOfContentsViewControllerDelegate) {
self.items = items
self.delegate = delegate
tableOfContentsFunnel = ToCInteractionFunnel()
super.init(nibName: nil, bundle: nil)
self.animator = WMFTableOfContentsAnimator(presentingViewController: presentingViewController, presentedViewController: self)
self.animator?.delegate = self
modalPresentationStyle = .Custom
transitioningDelegate = self.animator
}
public required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - Sections
func indexPathForItem(item: TableOfContentsItem) -> NSIndexPath? {
if let row = items.indexOf({ item.isEqual($0) }) {
return NSIndexPath(forRow: row, inSection: 0)
} else {
return nil
}
}
public func selectAndScrollToItem(atIndex index: Int, animated: Bool) {
selectAndScrollToItem(items[index], animated: animated)
}
public func selectAndScrollToItem(item: TableOfContentsItem, animated: Bool) {
guard let indexPath = indexPathForItem(item) else {
fatalError("No indexPath known for TOC item \(item)")
}
deselectAllRows()
tableView.selectRowAtIndexPath(indexPath, animated: animated, scrollPosition: UITableViewScrollPosition.Top)
addHighlightOfItemsRelatedTo(item, animated: false)
}
// MARK: - Selection
public func deselectAllRows() {
guard let selectedIndexPaths = tableView.indexPathsForSelectedRows else {
return
}
for (_, element) in selectedIndexPaths.enumerate() {
if let cell: WMFTableOfContentsCell = tableView.cellForRowAtIndexPath(element) as? WMFTableOfContentsCell {
cell.setSectionSelected(false, animated: false)
}
}
}
public func addHighlightOfItemsRelatedTo(item: TableOfContentsItem, animated: Bool) {
guard let visibleIndexPaths = tableView.indexPathsForVisibleRows else {
return
}
for (_, indexPath) in visibleIndexPaths.enumerate() {
if let otherItem: TableOfContentsItem = items[indexPath.row],
cell: WMFTableOfContentsCell = tableView.cellForRowAtIndexPath(indexPath) as? WMFTableOfContentsCell {
cell.setSectionSelected(otherItem.shouldBeHighlightedAlongWithItem(item), animated: animated)
}
}
}
// MARK: - Header
func forceUpdateHeaderFrame(){
//See reason for fix here: http://stackoverflow.com/questions/16471846/is-it-possible-to-use-autolayout-with-uitableviews-tableheaderview
self.tableView.tableHeaderView!.setNeedsLayout()
self.tableView.tableHeaderView!.layoutIfNeeded()
let headerHeight = self.tableView.tableHeaderView!.systemLayoutSizeFittingSize(UILayoutFittingCompressedSize).height
var headerFrame = self.tableView.tableHeaderView!.frame;
headerFrame.size.height = headerHeight
self.tableView.tableHeaderView!.frame = headerFrame;
self.tableView.tableHeaderView = self.tableView.tableHeaderView
}
// MARK: - UIViewController
public override func viewDidLoad() {
super.viewDidLoad()
let header = WMFTableOfContentsHeader.wmf_viewFromClassNib()
assert(delegate != nil, "TOC delegate not set!")
header.articleSite = delegate?.tableOfContentsArticleSite()
self.tableView.tableHeaderView = header
tableView.registerNib(WMFTableOfContentsCell.wmf_classNib(),
forCellReuseIdentifier: WMFTableOfContentsCell.reuseIdentifier())
clearsSelectionOnViewWillAppear = false
tableView.estimatedRowHeight = 44.0
tableView.rowHeight = UITableViewAutomaticDimension
automaticallyAdjustsScrollViewInsets = false
tableView.contentInset = UIEdgeInsetsMake(UIApplication.sharedApplication().statusBarFrame.size.height, 0, 0, 0)
tableView.separatorStyle = .None
}
public override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
self.forceUpdateHeaderFrame()
self.delegate?.tableOfContentsControllerWillDisplay(self)
tableOfContentsFunnel.logOpen()
}
public override func viewDidDisappear(animated: Bool) {
super.viewDidDisappear(animated)
deselectAllRows()
}
public override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) {
coordinator.animateAlongsideTransition({ (context) -> Void in
self.forceUpdateHeaderFrame()
}) { (context) -> Void in
}
}
// MARK: - UITableViewDataSource
public override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return items.count
}
public override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(WMFTableOfContentsCell.reuseIdentifier(), forIndexPath: indexPath) as! WMFTableOfContentsCell
let selectedItems: [TableOfContentsItem] = tableView.indexPathsForSelectedRows?.map() { items[$0.row] } ?? []
let item = items[indexPath.row]
let shouldHighlight = selectedItems.reduce(false) { shouldHighlight, selectedItem in
shouldHighlight || item.shouldBeHighlightedAlongWithItem(selectedItem)
}
cell.setItem(item)
cell.setSectionSelected(shouldHighlight, animated: false)
return cell
}
// MARK: - UITableViewDelegate
public override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let item = items[indexPath.row]
deselectAllRows()
tableOfContentsFunnel.logClick()
addHighlightOfItemsRelatedTo(item, animated: true)
delegate?.tableOfContentsController(self, didSelectItem: item)
}
public func tableOfContentsAnimatorDidTapBackground(controller: WMFTableOfContentsAnimator) {
tableOfContentsFunnel.logClose()
delegate?.tableOfContentsControllerDidCancel(self)
}
}
| 15e63af911d5ccf9fcd2c44619e29231 | 40.139785 | 156 | 0.705044 | false | false | false | false |
SaberVicky/LoveStory | refs/heads/master | LoveStory/Feature/Publish/LSPublishViewController.swift | mit | 1 | //
// LSPublishViewController.swift
// LoveStory
//
// Created by songlong on 2016/12/29.
// Copyright © 2016年 com.Saber. All rights reserved.
//
import UIKit
import SnapKit
import SVProgressHUD
import Qiniu
class LSPublishViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
var toolBar: UIView!
var editTextView = UITextView()
var imgSelectButton = UIButton()
var recordSoundButton = UIButton()
var recordVideoButton = UIButton()
var publishImgUrl: String?
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor(red: 240 / 255.0, green: 240 / 255.0, blue: 240 / 255.0, alpha: 1)
title = "新建"
navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发布", style: .plain, target: self, action: #selector(LSPublishViewController.publish))
setupUI()
NotificationCenter.default.addObserver(self, selector: #selector(keyBoardWillShow), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyBoardWillHide), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
}
func keyBoardWillShow(note: Notification) {
let durationT = 0.25
let deltaY = 216
let animations:(() -> Void) = {
self.toolBar.transform = CGAffineTransform(translationX: 0,y: -(CGFloat)(deltaY)-30)
}
let options : UIViewAnimationOptions = UIViewAnimationOptions(rawValue: 7)
UIView.animate(withDuration: durationT, delay: 0, options:options, animations: animations, completion: nil)
}
func keyBoardWillHide() {
}
func publish() {
let account = LSUser.currentUser()?.user_account
var params: [String : String?]
if publishImgUrl != nil {
params = ["user_account": account, "publish_text" : editTextView.text, "img_url": publishImgUrl]
} else {
params = ["user_account": account, "publish_text" : editTextView.text]
}
LSNetworking.sharedInstance.request(method: .GET, URLString: API_PUBLISH, parameters: params, success: { (task, responseObject) in
SVProgressHUD.showSuccess(withStatus: "发布成功")
}, failure: { (task, error) in
SVProgressHUD.showError(withStatus: "发布失败")
})
}
func setupUI() {
editTextView.backgroundColor = .lightGray
editTextView.font = UIFont.systemFont(ofSize: 18)
editTextView.autocorrectionType = .no
editTextView.autocapitalizationType = .none
imgSelectButton.setTitle("选择图片", for: .normal)
imgSelectButton.setTitleColor(.black, for: .normal)
imgSelectButton.addTarget(self, action: #selector(LSPublishViewController.gotoImageLibrary), for: .touchUpInside)
recordSoundButton.setTitle("录音", for: .normal)
recordSoundButton.setTitleColor(.black, for: .normal)
recordSoundButton.addTarget(self, action: #selector(LSPublishViewController.gotoRecord), for: .touchUpInside)
recordVideoButton.setTitle("录像", for: .normal)
recordVideoButton.setTitleColor(.black, for: .normal)
recordVideoButton.addTarget(self, action: #selector(LSPublishViewController.gotoRecordVideo), for: .touchUpInside)
view.addSubview(editTextView)
view.addSubview(imgSelectButton)
view.addSubview(recordSoundButton)
view.addSubview(recordVideoButton)
editTextView.snp.makeConstraints { (make) in
make.top.left.right.equalTo(0)
make.height.equalTo(self.view).multipliedBy(0.5)
}
imgSelectButton.snp.makeConstraints { (make) in
make.centerX.equalTo(self.view)
make.top.equalTo(editTextView.snp.bottom).offset(20)
}
recordSoundButton.snp.makeConstraints { (make) in
make.centerX.equalTo(self.view)
make.top.equalTo(imgSelectButton.snp.bottom).offset(20)
}
recordVideoButton.snp.makeConstraints { (make) in
make.centerX.equalTo(self.view)
make.top.equalTo(recordSoundButton.snp.bottom).offset(20)
}
toolBar = UIView(frame: CGRect(x: 0, y: LSHeight - 30 - 66, width: LSWidth, height: 30))
toolBar.backgroundColor = .black
view.addSubview(toolBar)
}
func gotoRecordVideo() {
navigationController?.pushViewController(LSRecordVideoViewController(), animated: true)
}
func gotoRecord() {
navigationController?.pushViewController(LSRecordSoundViewController(), animated: true)
}
func gotoImageLibrary() {
if UIImagePickerController.isSourceTypeAvailable(.photoLibrary) {
let imgPicker = UIImagePickerController()
imgPicker.sourceType = .photoLibrary
imgPicker.delegate = self
present(imgPicker, animated: true, completion: nil)
} else {
let alert = UIAlertController(title: "", message: nil, preferredStyle: .alert)
present(alert, animated: true, completion: nil)
}
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
picker.dismiss(animated:true, completion:nil)
let img = info[UIImagePickerControllerOriginalImage] as? UIImage
let icon = UIImageView(image: img)
view.addSubview(icon)
icon.snp.makeConstraints { (make) in
make.top.left.equalTo(0)
make.width.height.equalTo(UIScreen.main.bounds.size.width / 2)
}
LSNetworking.sharedInstance.request(method: .GET, URLString: API_GET_QINIU_PARAMS, parameters: nil, success: { (task, responseObject) in
let config = QNConfiguration.build({ (builder) in
builder?.setZone(QNZone.zone1())
})
let dic = responseObject as! NSDictionary
let token : String = dic["token"] as! String
let key : String = dic["key"] as! String
self.publishImgUrl = dic["img_url"] as? String
let option = QNUploadOption(progressHandler: { (key, percent) in
LSPrint("percent = \(percent)")
})
let upManager = QNUploadManager(configuration: config)
upManager?.putFile(self.getImagePath(image: img!), key: key, token: token, complete: { (info, key, resp) in
if (info?.isOK)! {
LSPrint("上传成功")
self.publish()
} else {
SVProgressHUD.showError(withStatus: "上传失败")
LSPrint("上传失败")
}
LSPrint(info)
LSPrint(resp)
}, option: option)
}, failure: { (task, error) in
print(error)
})
}
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
picker.dismiss(animated: true, completion: nil)
}
func getImagePath(image: UIImage) -> String {
var data: Data?
// if UIImagePNGRepresentation(image) == nil {
// data = UIImageJPEGRepresentation(image, 0.3)
// } else {
// data = UIImagePNGRepresentation(image)
// }
data = UIImageJPEGRepresentation(image, 0.3)
let documentsPath = NSHomeDirectory().appending("/Documents")
let manager = FileManager.default
do {
try manager.createDirectory(at: URL(string: documentsPath)!, withIntermediateDirectories: true, attributes: nil)
} catch let error as NSError {
LSPrint(error.localizedDescription)
}
let path = documentsPath.appending("/theImage.jpg")
manager.createFile(atPath: path, contents: data, attributes: nil)
return path
}
}
| 047a4b58c8a3f543d3392ad1f4f55936 | 34.957082 | 153 | 0.599905 | false | false | false | false |
Arnoymous/AListViewController | refs/heads/develop | Carthage/Checkouts/AlamofireObjectMapper/Carthage/Checkouts/ObjectMapper/Sources/HexColorTransform.swift | apache-2.0 | 35 | //
// HexColorTransform.swift
// ObjectMapper
//
// Created by Vitaliy Kuzmenko on 10/10/16.
// Copyright © 2016 hearst. All rights reserved.
//
#if os(iOS) || os(tvOS) || os(watchOS)
import UIKit
#elseif os(macOS)
import Cocoa
#endif
#if os(iOS) || os(tvOS) || os(watchOS) || os(macOS)
open class HexColorTransform: TransformType {
#if os(iOS) || os(tvOS) || os(watchOS)
public typealias Object = UIColor
#else
public typealias Object = NSColor
#endif
public typealias JSON = String
var prefix: Bool = false
var alpha: Bool = false
public init(prefixToJSON: Bool = false, alphaToJSON: Bool = false) {
alpha = alphaToJSON
prefix = prefixToJSON
}
open func transformFromJSON(_ value: Any?) -> Object? {
if let rgba = value as? String {
if rgba.hasPrefix("#") {
let index = rgba.characters.index(rgba.startIndex, offsetBy: 1)
let hex = rgba.substring(from: index)
return getColor(hex: hex)
} else {
return getColor(hex: rgba)
}
}
return nil
}
open func transformToJSON(_ value: Object?) -> JSON? {
if let value = value {
return hexString(color: value)
}
return nil
}
fileprivate func hexString(color: Object) -> String {
let comps = color.cgColor.components!
let r = Int(comps[0] * 255)
let g = Int(comps[1] * 255)
let b = Int(comps[2] * 255)
let a = Int(comps[3] * 255)
var hexString: String = ""
if prefix {
hexString = "#"
}
hexString += String(format: "%02X%02X%02X", r, g, b)
if alpha {
hexString += String(format: "%02X", a)
}
return hexString
}
fileprivate func getColor(hex: String) -> Object? {
var red: CGFloat = 0.0
var green: CGFloat = 0.0
var blue: CGFloat = 0.0
var alpha: CGFloat = 1.0
let scanner = Scanner(string: hex)
var hexValue: CUnsignedLongLong = 0
if scanner.scanHexInt64(&hexValue) {
switch (hex.characters.count) {
case 3:
red = CGFloat((hexValue & 0xF00) >> 8) / 15.0
green = CGFloat((hexValue & 0x0F0) >> 4) / 15.0
blue = CGFloat(hexValue & 0x00F) / 15.0
case 4:
red = CGFloat((hexValue & 0xF000) >> 12) / 15.0
green = CGFloat((hexValue & 0x0F00) >> 8) / 15.0
blue = CGFloat((hexValue & 0x00F0) >> 4) / 15.0
alpha = CGFloat(hexValue & 0x000F) / 15.0
case 6:
red = CGFloat((hexValue & 0xFF0000) >> 16) / 255.0
green = CGFloat((hexValue & 0x00FF00) >> 8) / 255.0
blue = CGFloat(hexValue & 0x0000FF) / 255.0
case 8:
red = CGFloat((hexValue & 0xFF000000) >> 24) / 255.0
green = CGFloat((hexValue & 0x00FF0000) >> 16) / 255.0
blue = CGFloat((hexValue & 0x0000FF00) >> 8) / 255.0
alpha = CGFloat(hexValue & 0x000000FF) / 255.0
default:
// Invalid RGB string, number of characters after '#' should be either 3, 4, 6 or 8
return nil
}
} else {
// "Scan hex error
return nil
}
#if os(iOS) || os(tvOS) || os(watchOS)
return UIColor(red: red, green: green, blue: blue, alpha: alpha)
#else
return NSColor(calibratedRed: red, green: green, blue: blue, alpha: alpha)
#endif
}
}
#endif
| bc4fdac0d84befca22aecf841e21e60b | 25.982759 | 87 | 0.611502 | false | false | false | false |
jianghongbing/APIReferenceDemo | refs/heads/master | UIKit/UIPresentationController/UIPresentationController/ViewController.swift | mit | 1 | //
// ViewController.swift
// UIPresentationController
//
// Created by pantosoft on 2018/7/27.
// Copyright © 2018年 jianghongbing. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
var customTransitioningDelegate: UIViewControllerTransitioningDelegate?
@IBAction func buttonTapped(_ sender: Any) {
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let destinationViewController = storyboard.instantiateViewController(withIdentifier: "destinationViewController")
let presentationController = PresentationController(presentedViewController: destinationViewController, presenting: self)
customTransitioningDelegate = presentationController
destinationViewController.transitioningDelegate = presentationController
destinationViewController.modalPresentationStyle = .custom
present(destinationViewController, animated: true, completion: nil)
}
}
| 15c052b2e808f7dd53405657a576adbc | 40.391304 | 129 | 0.777311 | false | false | false | false |
ewhitley/CDAKit | refs/heads/master | CDAKit/health-data-standards/lib/import/c32/c32_care_goal_importer.swift | mit | 1 | //
// immunization_importer.swift
// CDAKit
//
// Created by Eric Whitley on 1/21/16.
// Copyright © 2016 Eric Whitley. All rights reserved.
//
import Foundation
import Fuzi
class CDAKImport_C32_CareGoalImporter: CDAKImport_CDA_SectionImporter {
override init(entry_finder: CDAKImport_CDA_EntryFinder = CDAKImport_CDA_EntryFinder(entry_xpath: "//cda:section[cda:templateId/@root='2.16.840.1.113883.3.88.11.83.124']/cda:entry/cda:*[cda:templateId/@root='2.16.840.1.113883.10.20.1.25']")) {
super.init(entry_finder: entry_finder)
entry_class = CDAKEntry.self
}
// NOTE this returns a generic "CDAKEntry" - but it could be any number of sub-types
override func create_entry(goal_element: XMLElement, nrh: CDAKImport_CDA_NarrativeReferenceHandler = CDAKImport_CDA_NarrativeReferenceHandler()) -> CDAKEntry? {
//original Ruby used "name" - which is "node_name"
//looks like Fuzi calls this "tag"
var importer: CDAKImport_CDA_SectionImporter
switch goal_element.tag! {
case "observation": importer = CDAKImport_CDA_ResultImporter()
case "supply": importer = CDAKImport_CDA_MedicalEquipmentImporter()
case "substanceAdministration": importer = CDAKImport_CDA_MedicationImporter()
case "encounter": importer = CDAKImport_CDA_EncounterImporter()
case "procedure": importer = CDAKImport_CDA_ProcedureImporter()
//this bit here - not in the original Ruby - added our own entry_finder into the mix...
//was originally sending nil arguments
default: importer = CDAKImport_CDA_SectionImporter(entry_finder: self.entry_finder) //#don't need entry xpath, since we already have the entry
}
if let care_goal = importer.create_entry(goal_element, nrh: nrh) {
extract_negation(goal_element, entry: care_goal)
return care_goal
}
return nil
}
} | 127daa4a4306ca559f519cc1911ba55d | 41.295455 | 244 | 0.712903 | false | false | false | false |
RamonGilabert/Walker | refs/heads/master | Source/Constructors/Spring.swift | mit | 1 | import UIKit
/**
Spring starts a series of blocks of spring animations, it can have multiple parameters.
- Parameter delay: The delay that this chain should wait to be triggered.
- Parameter spring: The value of the spring in the animation.
- Parameter friction: The value of the friction that the layer will present.
- Parameter mass: The value of the mass of the layer.
- Parameter tolerance: The tolerance that will default to 0.0001.
- Returns: A series of ingredients that you can configure with all the animatable properties.
*/
@discardableResult public func spring(_ view: UIView, delay: TimeInterval = 0, spring: CGFloat, friction: CGFloat,
mass: CGFloat, tolerance: CGFloat = 0.0001, kind: Animation.Spring = .spring, animations: (Ingredient) -> Void) -> Distillery {
let builder = constructor([view], delay, spring, friction, mass, tolerance, kind)
animations(builder.ingredients[0])
validate(builder.distillery)
return builder.distillery
}
/**
Spring starts a series of blocks of spring animations, it can have multiple parameters.
- Parameter delay: The delay that this chain should wait to be triggered.
- Parameter spring: The value of the spring in the animation.
- Parameter friction: The value of the friction that the layer will present.
- Parameter mass: The value of the mass of the layer.
- Parameter tolerance: The tolerance that will default to 0.0001.
- Returns: A series of ingredients that you can configure with all the animatable properties.
*/
@discardableResult public func spring(_ firstView: UIView, _ secondView: UIView,
delay: TimeInterval = 0, spring: CGFloat, friction: CGFloat,
mass: CGFloat, tolerance: CGFloat = 0.0001, kind: Animation.Spring = .spring, animations: (Ingredient, Ingredient) -> Void) -> Distillery {
let builder = constructor([firstView, secondView], delay, spring, friction, mass, tolerance, kind)
animations(builder.ingredients[0], builder.ingredients[1])
validate(builder.distillery)
return builder.distillery
}
/**
Spring starts a series of blocks of spring animations, it can have multiple parameters.
- Parameter delay: The delay that this chain should wait to be triggered.
- Parameter spring: The value of the spring in the animation.
- Parameter friction: The value of the friction that the layer will present.
- Parameter mass: The value of the mass of the layer.
- Parameter tolerance: The tolerance that will default to 0.0001.
- Returns: A series of ingredients that you can configure with all the animatable properties.
*/
@discardableResult public func spring(_ firstView: UIView, _ secondView: UIView, _ thirdView: UIView,
delay: TimeInterval = 0, spring: CGFloat, friction: CGFloat,
mass: CGFloat, tolerance: CGFloat = 0.0001, kind: Animation.Spring = .spring , animations: (Ingredient, Ingredient, Ingredient) -> Void) -> Distillery {
let builder = constructor([firstView, secondView, thirdView], delay, spring, friction, mass, tolerance, kind)
animations(builder.ingredients[0], builder.ingredients[1], builder.ingredients[2])
validate(builder.distillery)
return builder.distillery
}
@discardableResult private func constructor(_ views: [UIView], _ delay: TimeInterval, _ spring: CGFloat,
_ friction: CGFloat, _ mass: CGFloat, _ tolerance: CGFloat, _ calculation: Animation.Spring) -> (ingredients: [Ingredient], distillery: Distillery) {
let distillery = Distillery()
var ingredients: [Ingredient] = []
views.forEach {
ingredients.append(Ingredient(distillery: distillery, view: $0, spring: spring,
friction: friction, mass: mass, tolerance: tolerance, calculation: calculation))
}
distillery.delays.append(delay)
distillery.ingredients = [ingredients]
return (ingredients: ingredients, distillery: distillery)
}
private func validate(_ distillery: Distillery) {
var shouldProceed = true
distilleries.forEach {
if let ingredients = $0.ingredients.first, let ingredient = ingredients.first , ingredient.finalValues.isEmpty {
shouldProceed = false
return
}
}
distillery.shouldProceed = shouldProceed
if shouldProceed {
distilleries.append(distillery)
distillery.animate()
}
}
| 18da306fe854f264c7ef8a5d1a5dde6f | 40.588235 | 155 | 0.740217 | false | false | false | false |
KevinCoble/AIToolbox | refs/heads/master | Playgrounds/NeuralNetwork.playground/Sources/LSTMNeuralNetwork.swift | apache-2.0 | 2 | //
// LSTMNeuralNetwork.swift
// AIToolbox
//
// Created by Kevin Coble on 5/20/16.
// Copyright © 2016 Kevin Coble. All rights reserved.
//
import Foundation
import Accelerate
final class LSTMNeuralNode {
// Activation function
let activation : NeuralActivationFunction
let numInputs : Int
let numFeedback : Int
// Weights
let numWeights : Int // This includes weights from inputs and from feedback for input, forget, cell, and output
var Wi : [Double]
var Ui : [Double]
var Wf : [Double]
var Uf : [Double]
var Wc : [Double]
var Uc : [Double]
var Wo : [Double]
var Uo : [Double]
var h : Double // Last result calculated
var outputHistory : [Double] // History of output for the sequence
var lastCellState : Double // Last cell state calculated
var cellStateHistory : [Double] // History of cell state for the sequence
var ho : Double // Last output gate calculated
var outputGateHistory : [Double] // History of output gate result for the sequence
var hc : Double
var memoryCellHistory : [Double] // History of cell activation result for the sequence
var hi : Double // Last input gate calculated
var inputGateHistory : [Double] // History of input gate result for the sequence
var hf : Double // Last forget gate calculated
var forgetGateHistory : [Double] // History of forget gate result for the sequence
var 𝟃E𝟃h : Double // Gradient in error with respect to output of this node for this time step plus future time steps
var 𝟃E𝟃zo : Double // Gradient in error with respect to weighted sum of the output gate
var 𝟃E𝟃zi : Double // Gradient in error with respect to weighted sum of the input gate
var 𝟃E𝟃zf : Double // Gradient in error with respect to weighted sum of the forget gate
var 𝟃E𝟃zc : Double // Gradient in error with respect to weighted sum of the memory cell
var 𝟃E𝟃cellState : Double // Gradient in error with respect to state of the memory cell
var 𝟃E𝟃Wi : [Double]
var 𝟃E𝟃Ui : [Double]
var 𝟃E𝟃Wf : [Double]
var 𝟃E𝟃Uf : [Double]
var 𝟃E𝟃Wc : [Double]
var 𝟃E𝟃Uc : [Double]
var 𝟃E𝟃Wo : [Double]
var 𝟃E𝟃Uo : [Double]
var rmspropDecay : Double? // Decay rate for rms prop weight updates. If nil, rmsprop is not used
/// Create the LSTM neural network node with a set activation function
init(numInputs : Int, numFeedbacks : Int, activationFunction: NeuralActivationFunction)
{
activation = activationFunction
self.numInputs = numInputs + 1 // Add one weight for the bias term
self.numFeedback = numFeedbacks
// Weights
numWeights = (self.numInputs + self.numFeedback) * 4 // input, forget, cell and output all have weights
Wi = []
Ui = []
Wf = []
Uf = []
Wc = []
Uc = []
Wo = []
Uo = []
h = 0.0
outputHistory = []
lastCellState = 0.0
cellStateHistory = []
ho = 0.0
outputGateHistory = []
hc = 0.0
memoryCellHistory = []
hi = 0.0
inputGateHistory = []
hf = 0.0
forgetGateHistory = []
𝟃E𝟃h = 0.0
𝟃E𝟃zo = 0.0
𝟃E𝟃zi = 0.0
𝟃E𝟃zf = 0.0
𝟃E𝟃zc = 0.0
𝟃E𝟃cellState = 0.0
𝟃E𝟃Wi = []
𝟃E𝟃Ui = []
𝟃E𝟃Wf = []
𝟃E𝟃Uf = []
𝟃E𝟃Wc = []
𝟃E𝟃Uc = []
𝟃E𝟃Wo = []
𝟃E𝟃Uo = []
}
// Initialize the weights
func initWeights(_ startWeights: [Double]!)
{
if let startWeights = startWeights {
if (startWeights.count == 1) {
Wi = [Double](repeating: startWeights[0], count: numInputs)
Ui = [Double](repeating: startWeights[0], count: numFeedback)
Wf = [Double](repeating: startWeights[0], count: numInputs)
Uf = [Double](repeating: startWeights[0], count: numFeedback)
Wc = [Double](repeating: startWeights[0], count: numInputs)
Uc = [Double](repeating: startWeights[0], count: numFeedback)
Wo = [Double](repeating: startWeights[0], count: numInputs)
Uo = [Double](repeating: startWeights[0], count: numFeedback)
}
else if (startWeights.count == (numInputs+numFeedback) * 4) {
// Full weight array, just split into the eight weight arrays
var index = 0
Wi = Array(startWeights[index..<index+numInputs])
index += numInputs
Ui = Array(startWeights[index..<index+numFeedback])
index += numFeedback
Wf = Array(startWeights[index..<index+numInputs])
index += numInputs
Uf = Array(startWeights[index..<index+numFeedback])
index += numFeedback
Wc = Array(startWeights[index..<index+numInputs])
index += numInputs
Uc = Array(startWeights[index..<index+numFeedback])
index += numFeedback
Wo = Array(startWeights[index..<index+numInputs])
index += numInputs
Uo = Array(startWeights[index..<index+numFeedback])
index += numFeedback
}
else {
// Get the weights and bias start indices
let numValues = startWeights.count
var inputStart : Int
var forgetStart : Int
var cellStart : Int
var outputStart : Int
var sectionLength : Int
if ((numValues % 4) == 0) {
// Evenly divisible by 4, pass each quarter
sectionLength = numValues / 4
inputStart = 0
forgetStart = sectionLength
cellStart = sectionLength * 2
outputStart = sectionLength * 3
}
else {
// Use the values for all sections
inputStart = 0
forgetStart = 0
cellStart = 0
outputStart = 0
sectionLength = numValues
}
Wi = []
var index = inputStart // Last number (if more than 1) goes into the bias weight, then repeat the initial
for _ in 0..<numInputs-1 {
if (index >= sectionLength-1) { index = inputStart } // Wrap if necessary
Wi.append(startWeights[index])
index += 1
}
Wi.append(startWeights[inputStart + sectionLength - 1]) // Add the bias term
Ui = []
for _ in 0..<numFeedback {
if (index >= sectionLength-1) { index = inputStart } // Wrap if necessary
Ui.append(startWeights[index])
index += 1
}
index = forgetStart
Wf = []
for _ in 0..<numInputs-1 {
if (index >= sectionLength-1) { index = forgetStart } // Wrap if necessary
Wi.append(startWeights[index])
index += 1
}
Wf.append(startWeights[forgetStart + sectionLength - 1]) // Add the bias term
Uf = []
for _ in 0..<numFeedback {
if (index >= sectionLength-1) { index = forgetStart } // Wrap if necessary
Uf.append(startWeights[index])
index += 1
}
index = cellStart
Wc = []
for _ in 0..<numInputs-1 {
if (index >= sectionLength-1) { index = cellStart } // Wrap if necessary
Wc.append(startWeights[index])
index += 1
}
Wc.append(startWeights[cellStart + sectionLength - 1]) // Add the bias term
Uc = []
for _ in 0..<numFeedback {
if (index >= sectionLength-1) { index = cellStart } // Wrap if necessary
Uc.append(startWeights[index])
index += 1
}
index = outputStart
Wo = []
for _ in 0..<numInputs-1 {
if (index >= sectionLength-1) { index = outputStart } // Wrap if necessary
Wo.append(startWeights[index])
index += 1
}
Wo.append(startWeights[outputStart + sectionLength - 1]) // Add the bias term
Uo = []
for _ in 0..<numFeedback {
if (index >= sectionLength-1) { index = outputStart } // Wrap if necessary
Uo.append(startWeights[index])
index += 1
}
}
}
else {
Wi = []
for _ in 0..<numInputs-1 {
Wi.append(Gaussian.gaussianRandom(0.0, standardDeviation: 1.0 / Double(numInputs-1))) // input weights - Initialize to a random number to break initial symmetry of the network, scaled to the inputs
}
Wi.append(Gaussian.gaussianRandom(-2.0, standardDeviation:1.0)) // Bias weight - Initialize to a negative number to have inputs learn to feed in
Ui = []
for _ in 0..<numFeedback {
Ui.append(Gaussian.gaussianRandom(0.0, standardDeviation: 1.0 / Double(numFeedback))) // feedback weights - Initialize to a random number to break initial symmetry of the network, scaled to the inputs
}
Wf = []
for _ in 0..<numInputs-1 {
Wf.append(Gaussian.gaussianRandom(0.0, standardDeviation: 1.0 / Double(numInputs-1))) // input weights - Initialize to a random number to break initial symmetry of the network, scaled to the inputs
}
Wf.append(Gaussian.gaussianRandom(2.0, standardDeviation:1.0)) // Bias weight - Initialize to a positive number to turn off forget (output close to 1) until it 'learns' to forget
Uf = []
for _ in 0..<numFeedback {
Uf.append(Gaussian.gaussianRandom(0.0, standardDeviation: 1.0 / Double(numFeedback))) // feedback weights - Initialize to a random number to break initial symmetry of the network, scaled to the inputs
}
Wc = []
for _ in 0..<numInputs-1 {
Wc.append(Gaussian.gaussianRandom(0.0, standardDeviation: 1.0 / Double(numInputs-1))) // input weights - Initialize to a random number to break initial symmetry of the network, scaled to the inputs
}
Wc.append(Gaussian.gaussianRandom(0.0, standardDeviation:1.0)) // Bias weight - Initialize to a random number to break initial symmetry of the network
Uc = []
for _ in 0..<numFeedback {
Uc.append(Gaussian.gaussianRandom(0.0, standardDeviation: 1.0 / Double(numFeedback))) // feedback weights - Initialize to a random number to break initial symmetry of the network, scaled to the inputs
}
Wo = []
for _ in 0..<numInputs-1 {
Wo.append(Gaussian.gaussianRandom(0.0, standardDeviation: 1.0 / Double(numInputs-1))) // input weights - Initialize to a random number to break initial symmetry of the network, scaled to the inputs
}
Wo.append(Gaussian.gaussianRandom(-2.0, standardDeviation:1.0)) // Bias weight - Initialize to a negative number to limit output until network learns when output is needed
Uo = []
for _ in 0..<numFeedback {
Uo.append(Gaussian.gaussianRandom(0.0, standardDeviation: 1.0 / Double(numFeedback))) // feedback weights - Initialize to a random number to break initial symmetry of the network, scaled to the inputs
}
}
}
func setRMSPropDecay(_ decay: Double?)
{
rmspropDecay = decay
}
func feedForward(_ x: [Double], hPrev: [Double]) -> Double
{
// Get the input gate value
var zi = 0.0
var sum = 0.0
vDSP_dotprD(Wi, 1, x, 1, &zi, vDSP_Length(numInputs))
vDSP_dotprD(Ui, 1, hPrev, 1, &sum, vDSP_Length(numFeedback))
zi += sum
hi = 1.0 / (1.0 + exp(-zi))
// Get the forget gate value
var zf = 0.0
vDSP_dotprD(Wf, 1, x, 1, &zf, vDSP_Length(numInputs))
vDSP_dotprD(Uf, 1, hPrev, 1, &sum, vDSP_Length(numFeedback))
zf += sum
hf = 1.0 / (1.0 + exp(-zf))
// Get the output gate value
var zo = 0.0
vDSP_dotprD(Wo, 1, x, 1, &zo, vDSP_Length(numInputs))
vDSP_dotprD(Uo, 1, hPrev, 1, &sum, vDSP_Length(numFeedback))
zo += sum
ho = 1.0 / (1.0 + exp(-zo))
// Get the memory cell z sumation
var zc = 0.0
vDSP_dotprD(Wc, 1, x, 1, &zc, vDSP_Length(numInputs))
vDSP_dotprD(Uc, 1, hPrev, 1, &sum, vDSP_Length(numFeedback))
zc += sum
// Use the activation function function for the nonlinearity
switch (activation) {
case .none:
hc = zc
break
case .hyperbolicTangent:
hc = tanh(zc)
break
case .sigmoidWithCrossEntropy:
fallthrough
case .sigmoid:
hc = 1.0 / (1.0 + exp(-zc))
break
case .rectifiedLinear:
hc = zc
if (zc < 0) { hc = 0.0 }
break
case .softSign:
hc = zc / (1.0 + abs(zc))
break
case .softMax:
hc = exp(zc)
break
}
// Combine the forget and input gates into the cell summation
lastCellState = lastCellState * hf + hc * hi
// Use the activation function function for the nonlinearity
let squashedCellState = getSquashedCellState()
// Multiply the cell value by the output gate value to get the final result
h = squashedCellState * ho
return h
}
func getSquashedCellState() -> Double
{
// Use the activation function function for the nonlinearity
var squashedCellState : Double
switch (activation) {
case .none:
squashedCellState = lastCellState
break
case .hyperbolicTangent:
squashedCellState = tanh(lastCellState)
break
case .sigmoidWithCrossEntropy:
fallthrough
case .sigmoid:
squashedCellState = 1.0 / (1.0 + exp(-lastCellState))
break
case .rectifiedLinear:
squashedCellState = lastCellState
if (lastCellState < 0) { squashedCellState = 0.0 }
break
case .softSign:
squashedCellState = lastCellState / (1.0 + abs(lastCellState))
break
case .softMax:
squashedCellState = exp(lastCellState)
break
}
return squashedCellState
}
// Get the partial derivitive of the error with respect to the weighted sum
func getFinalNode𝟃E𝟃zs(_ 𝟃E𝟃h: Double)
{
// Store 𝟃E/𝟃h, set initial future error contributions to zero, and have the hidden layer routine do the work
self.𝟃E𝟃h = 𝟃E𝟃h
get𝟃E𝟃zs()
}
func reset𝟃E𝟃hs()
{
𝟃E𝟃h = 0.0
}
func addTo𝟃E𝟃hs(_ addition: Double)
{
𝟃E𝟃h += addition
}
func getWeightTimes𝟃E𝟃zs(_ weightIndex: Int) ->Double
{
var sum = Wo[weightIndex] * 𝟃E𝟃zo
sum += Wf[weightIndex] * 𝟃E𝟃zf
sum += Wc[weightIndex] * 𝟃E𝟃zc
sum += Wi[weightIndex] * 𝟃E𝟃zi
return sum
}
func getFeedbackWeightTimes𝟃E𝟃zs(_ weightIndex: Int) ->Double
{
var sum = Uo[weightIndex] * 𝟃E𝟃zo
sum += Uf[weightIndex] * 𝟃E𝟃zf
sum += Uc[weightIndex] * 𝟃E𝟃zc
sum += Ui[weightIndex] * 𝟃E𝟃zi
return sum
}
func get𝟃E𝟃zs()
{
// 𝟃E𝟃h contains 𝟃E/𝟃h for the current time step plus all future time steps.
// h = ho * squashedCellState -->
// 𝟃E/𝟃zo = 𝟃E/𝟃h ⋅ 𝟃h/𝟃ho ⋅ 𝟃ho/𝟃zo = 𝟃E/𝟃h ⋅ squashedCellState ⋅ (ho - ho²)
// 𝟃E/𝟃cellState = 𝟃E/𝟃h ⋅ 𝟃h/𝟃squashedCellState ⋅ 𝟃squashedCellState/𝟃cellState
// = 𝟃E/𝟃h ⋅ ho ⋅ act'(cellState) + 𝟃E_future/𝟃cellState (from previous backpropogation step)
𝟃E𝟃zo = 𝟃E𝟃h * getSquashedCellState() * (ho - ho * ho)
𝟃E𝟃cellState = 𝟃E𝟃h * ho * getActPrime(getSquashedCellState()) + 𝟃E𝟃cellState
// cellState = prevCellState * hf + hc * hi -->
// 𝟃E/𝟃zf = 𝟃E𝟃cellState ⋅ 𝟃cellState/𝟃hf ⋅ 𝟃hf/𝟃zf = 𝟃E𝟃cellState ⋅ prevCellState ⋅ (hf - hf²)
// 𝟃E/𝟃zc = 𝟃E𝟃cellState ⋅ 𝟃cellState/𝟃hc ⋅ 𝟃hc/𝟃zc = 𝟃E𝟃cellState ⋅ hi ⋅ act'(zc)
// 𝟃E/𝟃zi = 𝟃E𝟃cellState ⋅ 𝟃cellState/𝟃hi ⋅ 𝟃hi/𝟃zi = 𝟃E𝟃cellState ⋅ hc ⋅ (hi - hi²)
𝟃E𝟃zf = 𝟃E𝟃cellState * getPreviousCellState() * (hf - hf * hf)
𝟃E𝟃zc = 𝟃E𝟃cellState * hi * getActPrime(hc)
𝟃E𝟃zi = 𝟃E𝟃cellState * hc * (hi - hi * hi)
}
func getActPrime(_ h: Double) -> Double
{
// derivitive of the non-linearity: tanh' -> 1 - result^2, sigmoid -> result - result^2, rectlinear -> 0 if result<0 else 1
var actPrime = 0.0
switch (activation) {
case .none:
break
case .hyperbolicTangent:
actPrime = (1 - h * h)
break
case .sigmoidWithCrossEntropy:
fallthrough
case .sigmoid:
actPrime = (h - h * h)
break
case .rectifiedLinear:
actPrime = h <= 0.0 ? 0.0 : 1.0
break
case .softSign:
// Reconstitute z from h
var z : Double
if (h < 0) { // Negative z
z = h / (1.0 + h)
actPrime = -1.0 / ((1.0 + z) * (1.0 + z))
}
else { // Positive z
z = h / (1.0 - h)
actPrime = 1.0 / ((1.0 + z) * (1.0 + z))
}
break
case .softMax:
// Should not get here - SoftMax is only valid on output layer
break
}
return actPrime
}
func getPreviousCellState() -> Double
{
let prevValue = cellStateHistory.last
if (prevValue == nil) { return 0.0 }
return prevValue!
}
func clearWeightChanges()
{
𝟃E𝟃Wi = [Double](repeating: 0.0, count: numInputs)
𝟃E𝟃Ui = [Double](repeating: 0.0, count: numFeedback)
𝟃E𝟃Wf = [Double](repeating: 0.0, count: numInputs)
𝟃E𝟃Uf = [Double](repeating: 0.0, count: numFeedback)
𝟃E𝟃Wc = [Double](repeating: 0.0, count: numInputs)
𝟃E𝟃Uc = [Double](repeating: 0.0, count: numFeedback)
𝟃E𝟃Wo = [Double](repeating: 0.0, count: numInputs)
𝟃E𝟃Uo = [Double](repeating: 0.0, count: numFeedback)
}
func appendWeightChanges(_ x: [Double], hPrev: [Double]) -> Double
{
// Update each weight accumulation
// With 𝟃E/𝟃zo, we can get 𝟃E/𝟃Wo. zo = Wo⋅x + Uo⋅h(t-1)). 𝟃zo/𝟃Wo = x --> 𝟃E/𝟃Wo = 𝟃E/𝟃zo ⋅ 𝟃zo/𝟃Wo = 𝟃E/𝟃zo ⋅ x
vDSP_vsmaD(x, 1, &𝟃E𝟃zo, 𝟃E𝟃Wo, 1, &𝟃E𝟃Wo, 1, vDSP_Length(numInputs))
// 𝟃E/𝟃Uo. zo = Wo⋅x + Uo⋅h(t-1). 𝟃zo/𝟃Uo = h(t-1) --> 𝟃E/𝟃Uo = 𝟃E/𝟃zo ⋅ 𝟃zo/𝟃Uo = 𝟃E/𝟃zo ⋅ h(t-1)
vDSP_vsmaD(hPrev, 1, &𝟃E𝟃zo, 𝟃E𝟃Uo, 1, &𝟃E𝟃Uo, 1, vDSP_Length(numFeedback))
// With 𝟃E/𝟃zi, we can get 𝟃E/𝟃Wi. zi = Wi⋅x + Ui⋅h(t-1). 𝟃zi/𝟃Wi = x --> 𝟃E/𝟃Wi = 𝟃E/𝟃zi ⋅ 𝟃zi/𝟃Wi = 𝟃E/𝟃zi ⋅ x
vDSP_vsmaD(x, 1, &𝟃E𝟃zi, 𝟃E𝟃Wi, 1, &𝟃E𝟃Wi, 1, vDSP_Length(numInputs))
// 𝟃E/𝟃Ui. i = Wi⋅x + Ui⋅h(t-1). 𝟃zi/𝟃Ui = h(t-1) --> 𝟃E/𝟃Ui = 𝟃E/𝟃zi ⋅ 𝟃zi/𝟃Ui = 𝟃E/𝟃zi ⋅ h(t-1)
vDSP_vsmaD(hPrev, 1, &𝟃E𝟃zi, 𝟃E𝟃Ui, 1, &𝟃E𝟃Ui, 1, vDSP_Length(numFeedback))
// With 𝟃E/𝟃zf, we can get 𝟃E/𝟃Wf. zf = Wf⋅x + Uf⋅h(t-1). 𝟃zf/𝟃Wf = x --> 𝟃E/𝟃Wf = 𝟃E/𝟃zf ⋅ 𝟃zf/𝟃Wf = 𝟃E/𝟃zf ⋅ x
vDSP_vsmaD(x, 1, &𝟃E𝟃zf, 𝟃E𝟃Wf, 1, &𝟃E𝟃Wf, 1, vDSP_Length(numInputs))
// 𝟃E/𝟃Uf. f = Wf⋅x + Uf⋅h(t-1). 𝟃zf/𝟃Uf = h(t-1) --> 𝟃E/𝟃Uf = 𝟃E/𝟃zf ⋅ 𝟃zf/𝟃Uf = 𝟃E/𝟃zf ⋅ h(t-1)
vDSP_vsmaD(hPrev, 1, &𝟃E𝟃zf, 𝟃E𝟃Uf, 1, &𝟃E𝟃Uf, 1, vDSP_Length(numFeedback))
// With 𝟃E/𝟃zc, we can get 𝟃E/𝟃Wc. za = Wc⋅x + Uc⋅h(t-1). 𝟃za/𝟃Wa = x --> 𝟃E/𝟃Wc = 𝟃E/𝟃zc ⋅ 𝟃zc/𝟃Wc = 𝟃E/𝟃zc ⋅ x
vDSP_vsmaD(x, 1, &𝟃E𝟃zc, 𝟃E𝟃Wc, 1, &𝟃E𝟃Wc, 1, vDSP_Length(numInputs))
// 𝟃E/𝟃Ua. f = Wc⋅x + Uc⋅h(t-1). 𝟃zc/𝟃Uc = h(t-1) --> 𝟃E/𝟃Uc = 𝟃E/𝟃zc ⋅ 𝟃zc/𝟃Uc = 𝟃E/𝟃zc ⋅ h(t-1)
vDSP_vsmaD(hPrev, 1, &𝟃E𝟃zc, 𝟃E𝟃Uc, 1, &𝟃E𝟃Uc, 1, vDSP_Length(numFeedback))
return h
}
func updateWeightsFromAccumulations(_ averageTrainingRate: Double)
{
// Update the weights from the accumulations
// weights -= accumulation * averageTrainingRate
var η = -averageTrainingRate
vDSP_vsmaD(𝟃E𝟃Wi, 1, &η, Wi, 1, &Wi, 1, vDSP_Length(numInputs))
vDSP_vsmaD(𝟃E𝟃Ui, 1, &η, Ui, 1, &Ui, 1, vDSP_Length(numFeedback))
vDSP_vsmaD(𝟃E𝟃Wf, 1, &η, Wf, 1, &Wf, 1, vDSP_Length(numInputs))
vDSP_vsmaD(𝟃E𝟃Uf, 1, &η, Uf, 1, &Uf, 1, vDSP_Length(numFeedback))
vDSP_vsmaD(𝟃E𝟃Wc, 1, &η, Wc, 1, &Wc, 1, vDSP_Length(numInputs))
vDSP_vsmaD(𝟃E𝟃Uc, 1, &η, Uc, 1, &Uc, 1, vDSP_Length(numFeedback))
vDSP_vsmaD(𝟃E𝟃Wo, 1, &η, Wo, 1, &Wo, 1, vDSP_Length(numInputs))
vDSP_vsmaD(𝟃E𝟃Uo, 1, &η, Uo, 1, &Uo, 1, vDSP_Length(numFeedback))
}
func decayWeights(_ decayFactor : Double)
{
var λ = decayFactor // Needed for unsafe pointer conversion
vDSP_vsmulD(Wi, 1, &λ, &Wi, 1, vDSP_Length(numInputs-1))
vDSP_vsmulD(Ui, 1, &λ, &Ui, 1, vDSP_Length(numFeedback))
vDSP_vsmulD(Wf, 1, &λ, &Wf, 1, vDSP_Length(numInputs-1))
vDSP_vsmulD(Uf, 1, &λ, &Uf, 1, vDSP_Length(numFeedback))
vDSP_vsmulD(Wc, 1, &λ, &Wc, 1, vDSP_Length(numInputs-1))
vDSP_vsmulD(Uc, 1, &λ, &Uc, 1, vDSP_Length(numFeedback))
vDSP_vsmulD(Wo, 1, &λ, &Wo, 1, vDSP_Length(numInputs-1))
vDSP_vsmulD(Uo, 1, &λ, &Uo, 1, vDSP_Length(numFeedback))
}
func resetSequence()
{
h = 0.0
lastCellState = 0.0
ho = 0.0
hc = 0.0
hi = 0.0
hf = 0.0
𝟃E𝟃zo = 0.0
𝟃E𝟃zi = 0.0
𝟃E𝟃zf = 0.0
𝟃E𝟃zc = 0.0
𝟃E𝟃cellState = 0.0
outputHistory = [0.0] // first 'previous' value is zero
cellStateHistory = [0.0] // first 'previous' value is zero
outputGateHistory = [0.0] // first 'previous' value is zero
memoryCellHistory = [0.0] // first 'previous' value is zero
inputGateHistory = [0.0] // first 'previous' value is zero
forgetGateHistory = [0.0] // first 'previous' value is zero
}
func storeRecurrentValues()
{
outputHistory.append(h)
cellStateHistory.append(lastCellState)
outputGateHistory.append(ho)
memoryCellHistory.append(hc)
inputGateHistory.append(hi)
forgetGateHistory.append(hf)
}
func getLastRecurrentValue()
{
h = outputHistory.removeLast()
lastCellState = cellStateHistory.removeLast()
ho = outputGateHistory.removeLast()
hc = memoryCellHistory.removeLast()
hi = inputGateHistory.removeLast()
hf = forgetGateHistory.removeLast()
}
func getPreviousOutputValue() -> Double
{
let prevValue = outputHistory.last
if (prevValue == nil) { return 0.0 }
return prevValue!
}
}
final class LSTMNeuralLayer: NeuralLayer {
// Nodes
var nodes : [LSTMNeuralNode]
var dataSet : DataSet? // Sequence data set (inputs and outputs)
/// Create the neural network layer based on a tuple (number of nodes, activation function)
init(numInputs : Int, layerDefinition: (layerType: NeuronLayerType, numNodes: Int, activation: NeuralActivationFunction, auxiliaryData: AnyObject?))
{
nodes = []
for _ in 0..<layerDefinition.numNodes {
nodes.append(LSTMNeuralNode(numInputs: numInputs, numFeedbacks: layerDefinition.numNodes, activationFunction: layerDefinition.activation))
}
}
// Initialize the weights
func initWeights(_ startWeights: [Double]!)
{
if let startWeights = startWeights {
if (startWeights.count >= nodes.count * nodes[0].numWeights) {
// If there are enough weights for all nodes, split the weights and initialize
var startIndex = 0
for node in nodes {
let subArray = Array(startWeights[startIndex...(startIndex+node.numWeights-1)])
node.initWeights(subArray)
startIndex += node.numWeights
}
}
else {
// If there are not enough weights for all nodes, initialize each node with the set given
for node in nodes {
node.initWeights(startWeights)
}
}
}
else {
// No specified weights - just initialize normally
for node in nodes {
node.initWeights(nil)
}
}
}
func getWeights() -> [Double]
{
var weights: [Double] = []
for node in nodes {
weights += node.Wi
weights += node.Ui
weights += node.Wf
weights += node.Uf
weights += node.Wc
weights += node.Uc
weights += node.Wo
weights += node.Uo
}
return weights
}
func setRMSPropDecay(_ decay: Double?)
{
for node in nodes {
node.setRMSPropDecay(decay)
}
}
func getLastOutput() -> [Double]
{
var h: [Double] = []
for node in nodes {
h.append(node.h)
}
return h
}
func getNodeCount() -> Int
{
return nodes.count
}
func getWeightsPerNode()-> Int
{
return nodes[0].numWeights
}
func getActivation()-> NeuralActivationFunction
{
return nodes[0].activation
}
func feedForward(_ x: [Double]) -> [Double]
{
// Gather the previous outputs for the feedback
var hPrev : [Double] = []
for node in nodes {
hPrev.append(node.getPreviousOutputValue())
}
var outputs : [Double] = []
// Assume input array already has bias constant 1.0 appended
// Fully-connected nodes means all nodes get the same input array
if (nodes[0].activation == .softMax) {
var sum = 0.0
for node in nodes { // Sum each output
sum += node.feedForward(x, hPrev: hPrev)
}
let scale = 1.0 / sum // Do division once for efficiency
for node in nodes { // Get the outputs scaled by the sum to give the probability distribuition for the output
node.h *= scale
outputs.append(node.h)
}
}
else {
for node in nodes {
outputs.append(node.feedForward(x, hPrev: hPrev))
}
}
return outputs
}
func getFinalLayer𝟃E𝟃zs(_ 𝟃E𝟃h: [Double])
{
for nNodeIndex in 0..<nodes.count {
// Start with the portion from the squared error term
nodes[nNodeIndex].getFinalNode𝟃E𝟃zs(𝟃E𝟃h[nNodeIndex])
}
}
func getLayer𝟃E𝟃zs(_ nextLayer: NeuralLayer)
{
// Get 𝟃E/𝟃h
for nNodeIndex in 0..<nodes.count {
// Reset the 𝟃E/𝟃h total
nodes[nNodeIndex].reset𝟃E𝟃hs()
// Add each portion from the nodes in the next forward layer
nodes[nNodeIndex].addTo𝟃E𝟃hs(nextLayer.get𝟃E𝟃hForNodeInPreviousLayer(nNodeIndex))
// Add each portion from the nodes in this layer, using the feedback weights. This adds 𝟃Efuture/𝟃h
for node in nodes {
nodes[nNodeIndex].addTo𝟃E𝟃hs(node.getFeedbackWeightTimes𝟃E𝟃zs(nNodeIndex))
}
}
// Calculate 𝟃E/𝟃zs for this time step from 𝟃E/𝟃h
for node in nodes {
node.get𝟃E𝟃zs()
}
}
func get𝟃E𝟃hForNodeInPreviousLayer(_ inputIndex: Int) ->Double
{
var sum = 0.0
for node in nodes {
sum += node.getWeightTimes𝟃E𝟃zs(inputIndex)
}
return sum
}
func clearWeightChanges()
{
for node in nodes {
node.clearWeightChanges()
}
}
func appendWeightChanges(_ x: [Double]) -> [Double]
{
// Gather the previous outputs for the feedback
var hPrev : [Double] = []
for node in nodes {
hPrev.append(node.getPreviousOutputValue())
}
var outputs : [Double] = []
// Assume input array already has bias constant 1.0 appended
// Fully-connected nodes means all nodes get the same input array
for node in nodes {
outputs.append(node.appendWeightChanges(x, hPrev: hPrev))
}
return outputs
}
func updateWeightsFromAccumulations(_ averageTrainingRate: Double, weightDecay: Double)
{
// Have each node update it's weights from the accumulations
for node in nodes {
if (weightDecay < 1) { node.decayWeights(weightDecay) }
node.updateWeightsFromAccumulations(averageTrainingRate)
}
}
func decayWeights(_ decayFactor : Double)
{
for node in nodes {
node.decayWeights(decayFactor)
}
}
func getSingleNodeClassifyValue() -> Double
{
let activation = nodes[0].activation
if (activation == .hyperbolicTangent || activation == .rectifiedLinear) { return 0.0 }
return 0.5
}
func resetSequence()
{
for node in nodes {
node.resetSequence()
}
}
func storeRecurrentValues()
{
for node in nodes {
node.storeRecurrentValues()
}
}
func retrieveRecurrentValues(_ sequenceIndex: Int)
{
// Set the last recurrent value in the history array to the last output
for node in nodes {
node.getLastRecurrentValue()
}
}
func gradientCheck(x: [Double], ε: Double, Δ: Double, network: NeuralNetwork) -> Bool
{
//!!
return true
}
}
| cc98eff164fa517c4f904eba27c1abdd | 36.759281 | 220 | 0.52133 | false | false | false | false |
antonio081014/LeeCode-CodeBase | refs/heads/main | Swift/image-overlap.swift | mit | 2 | /**
* https://leetcode.com/problems/image-overlap/
*
*
*/
// Date: Sun Sep 6 00:42:52 PDT 2020
class Solution {
func largestOverlap(_ C: [[Int]], _ D: [[Int]]) -> Int {
func calc(_ A: [[Int]], _ B: [[Int]]) -> Int {
let n1 = A.count
let n2 = B.count
let m1 = A[0].count
let m2 = B[0].count
var maxCount = 0
for x1 in 0 ..< n1 {
for y1 in 0 ..< m1 {
var xx = 0
var count = 0
while xx + x1 < n1, xx < n2 {
var yy = 0
while yy + y1 < m1, yy < m2 {
// print("\(xx):\(yy) - \(x1):\(y1)")
if A[x1 + xx][y1 + yy] == 1, B[xx][yy] == 1 {
count += 1
}
yy += 1
}
xx += 1
}
// print("\(x1) - \(y1) : \(count)")
maxCount = max(maxCount, count)
}
}
return maxCount
}
return max(calc(C, D), calc(D, C))
}
} | 142f4e98c420afe1acf283191aec958d | 30.307692 | 73 | 0.3 | false | false | false | false |
material-motion/motion-transitioning-objc | refs/heads/develop | examples/supplemental/PhotoAlbum.swift | apache-2.0 | 2 | /*
Copyright 2017-present The Material Motion Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import Foundation
import UIKit
let numberOfImageAssets = 10
let numberOfPhotosInAlbum = 30
class PhotoAlbum {
let photos: [Photo]
let identifierToIndex: [String: Int]
init() {
var photos: [Photo] = []
var identifierToIndex: [String: Int] = [:]
for index in 0..<numberOfPhotosInAlbum {
let photo = Photo(name: "image\(index % numberOfImageAssets)")
photos.append(photo)
identifierToIndex[photo.uuid] = index
}
self.photos = photos
self.identifierToIndex = identifierToIndex
}
}
| 1de79a460c3651c635ed0a4873ab745f | 29.052632 | 73 | 0.734676 | false | false | false | false |
Ataraxiis/MGW-Esport | refs/heads/develop | Carthage/Checkouts/Moya/Carthage/Checkouts/RxSwift/RxSwift/Observables/Implementations/RetryWhen.swift | apache-2.0 | 60 | //
// RetryWhen.swift
// Rx
//
// Created by Junior B. on 06/10/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
class RetryTriggerSink<S: SequenceType, O: ObserverType, TriggerObservable: ObservableType, Error where S.Generator.Element : ObservableType, S.Generator.Element.E == O.E>
: ObserverType {
typealias E = TriggerObservable.E
typealias Parent = RetryWhenSequenceSinkIter<S, O, TriggerObservable, Error>
private let _parent: Parent
init(parent: Parent) {
_parent = parent
}
func on(event: Event<E>) {
switch event {
case .Next:
_parent._parent._lastError = nil
_parent._parent.schedule(.MoveNext)
case .Error(let e):
_parent._parent.forwardOn(.Error(e))
_parent._parent.dispose()
case .Completed:
_parent._parent.forwardOn(.Completed)
_parent._parent.dispose()
}
}
}
class RetryWhenSequenceSinkIter<S: SequenceType, O: ObserverType, TriggerObservable: ObservableType, Error where S.Generator.Element : ObservableType, S.Generator.Element.E == O.E>
: SingleAssignmentDisposable
, ObserverType {
typealias E = O.E
typealias Parent = RetryWhenSequenceSink<S, O, TriggerObservable, Error>
private let _parent: Parent
private let _errorHandlerSubscription = SingleAssignmentDisposable()
init(parent: Parent) {
_parent = parent
}
func on(event: Event<E>) {
switch event {
case .Next:
_parent.forwardOn(event)
case .Error(let error):
_parent._lastError = error
if let failedWith = error as? Error {
// dispose current subscription
super.dispose()
let errorHandlerSubscription = _parent._notifier.subscribe(RetryTriggerSink(parent: self))
_errorHandlerSubscription.disposable = errorHandlerSubscription
_parent._errorSubject.on(.Next(failedWith))
}
else {
_parent.forwardOn(.Error(error))
_parent.dispose()
}
case .Completed:
_parent.forwardOn(event)
_parent.dispose()
}
}
override func dispose() {
super.dispose()
_errorHandlerSubscription.dispose()
}
}
class RetryWhenSequenceSink<S: SequenceType, O: ObserverType, TriggerObservable: ObservableType, Error where S.Generator.Element : ObservableType, S.Generator.Element.E == O.E>
: TailRecursiveSink<S, O> {
typealias Element = O.E
typealias Parent = RetryWhenSequence<S, TriggerObservable, Error>
let _lock = NSRecursiveLock()
private let _parent: Parent
private var _lastError: ErrorType?
private let _errorSubject = PublishSubject<Error>()
private let _handler: Observable<TriggerObservable.E>
private let _notifier = PublishSubject<TriggerObservable.E>()
init(parent: Parent, observer: O) {
_parent = parent
_handler = parent._notificationHandler(_errorSubject).asObservable()
super.init(observer: observer)
}
override func done() {
if let lastError = _lastError {
forwardOn(.Error(lastError))
_lastError = nil
}
else {
forwardOn(.Completed)
}
dispose()
}
override func extract(observable: Observable<E>) -> SequenceGenerator? {
// It is important to always return `nil` here because there are sideffects in the `run` method
// that are dependant on particular `retryWhen` operator so single operator stack can't be reused in this
// case.
return nil
}
override func subscribeToNext(source: Observable<E>) -> Disposable {
let iter = RetryWhenSequenceSinkIter(parent: self)
iter.disposable = source.subscribe(iter)
return iter
}
override func run(sources: SequenceGenerator) -> Disposable {
let triggerSubscription = _handler.subscribe(_notifier.asObserver())
let superSubscription = super.run(sources)
return StableCompositeDisposable.create(superSubscription, triggerSubscription)
}
}
class RetryWhenSequence<S: SequenceType, TriggerObservable: ObservableType, Error where S.Generator.Element : ObservableType> : Producer<S.Generator.Element.E> {
typealias Element = S.Generator.Element.E
private let _sources: S
private let _notificationHandler: Observable<Error> -> TriggerObservable
init(sources: S, notificationHandler: Observable<Error> -> TriggerObservable) {
_sources = sources
_notificationHandler = notificationHandler
}
override func run<O : ObserverType where O.E == Element>(observer: O) -> Disposable {
let sink = RetryWhenSequenceSink<S, O, TriggerObservable, Error>(parent: self, observer: observer)
sink.disposable = sink.run((self._sources.generate(), nil))
return sink
}
} | d5bdeaa408f7247e95c349dabdf4c864 | 32.666667 | 180 | 0.642305 | false | false | false | false |
jmgc/swift | refs/heads/master | stdlib/public/core/StringBridge.swift | apache-2.0 | 1 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2018 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import SwiftShims
/// Effectively an untyped NSString that doesn't require foundation.
@usableFromInline
internal typealias _CocoaString = AnyObject
#if _runtime(_ObjC)
// Swift's String bridges NSString via this protocol and these
// variables, allowing the core stdlib to remain decoupled from
// Foundation.
@objc private protocol _StringSelectorHolder : _NSCopying {
@objc var length: Int { get }
@objc var hash: UInt { get }
@objc(characterAtIndex:)
func character(at offset: Int) -> UInt16
@objc(getCharacters:range:)
func getCharacters(
_ buffer: UnsafeMutablePointer<UInt16>, range aRange: _SwiftNSRange
)
@objc(_fastCStringContents:)
func _fastCStringContents(
_ requiresNulTermination: Int8
) -> UnsafePointer<CChar>?
@objc(_fastCharacterContents)
func _fastCharacterContents() -> UnsafePointer<UInt16>?
@objc(getBytes:maxLength:usedLength:encoding:options:range:remainingRange:)
func getBytes(_ buffer: UnsafeMutableRawPointer?,
maxLength maxBufferCount: Int,
usedLength usedBufferCount: UnsafeMutablePointer<Int>?,
encoding: UInt,
options: UInt,
range: _SwiftNSRange,
remaining leftover: UnsafeMutablePointer<_SwiftNSRange>?) -> Int8
@objc(compare:options:range:locale:)
func compare(_ string: _CocoaString,
options: UInt,
range: _SwiftNSRange,
locale: AnyObject?) -> Int
@objc(newTaggedNSStringWithASCIIBytes_:length_:)
func createTaggedString(bytes: UnsafePointer<UInt8>,
count: Int) -> AnyObject?
}
/*
Passing a _CocoaString through _objc() lets you call ObjC methods that the
compiler doesn't know about, via the protocol above. In order to get good
performance, you need a double indirection like this:
func a -> _objc -> func a'
because any refcounting @_effects on 'a' will be lost when _objc breaks ARC's
knowledge that the _CocoaString and _StringSelectorHolder are the same object.
*/
@inline(__always)
private func _objc(_ str: _CocoaString) -> _StringSelectorHolder {
return unsafeBitCast(str, to: _StringSelectorHolder.self)
}
@_effects(releasenone)
private func _copyNSString(_ str: _StringSelectorHolder) -> _CocoaString {
return str.copy(with: nil)
}
@usableFromInline // @testable
@_effects(releasenone)
internal func _stdlib_binary_CFStringCreateCopy(
_ source: _CocoaString
) -> _CocoaString {
return _copyNSString(_objc(source))
}
@_effects(readonly)
private func _NSStringLen(_ str: _StringSelectorHolder) -> Int {
return str.length
}
@usableFromInline // @testable
@_effects(readonly)
internal func _stdlib_binary_CFStringGetLength(
_ source: _CocoaString
) -> Int {
if let len = getConstantTaggedCocoaContents(source)?.utf16Length {
return len
}
return _NSStringLen(_objc(source))
}
@_effects(readonly)
internal func _isNSString(_ str:AnyObject) -> Bool {
if getConstantTaggedCocoaContents(str) != nil {
return true
}
return _swift_stdlib_isNSString(str) != 0
}
@_effects(readonly)
private func _NSStringCharactersPtr(_ str: _StringSelectorHolder) -> UnsafeMutablePointer<UTF16.CodeUnit>? {
return UnsafeMutablePointer(mutating: str._fastCharacterContents())
}
@usableFromInline // @testable
@_effects(readonly)
internal func _stdlib_binary_CFStringGetCharactersPtr(
_ source: _CocoaString
) -> UnsafeMutablePointer<UTF16.CodeUnit>? {
return _NSStringCharactersPtr(_objc(source))
}
@_effects(releasenone)
private func _NSStringGetCharacters(
from source: _StringSelectorHolder,
range: Range<Int>,
into destination: UnsafeMutablePointer<UTF16.CodeUnit>
) {
source.getCharacters(destination, range: _SwiftNSRange(
location: range.startIndex,
length: range.count)
)
}
/// Copies a slice of a _CocoaString into contiguous storage of sufficient
/// capacity.
@_effects(releasenone)
internal func _cocoaStringCopyCharacters(
from source: _CocoaString,
range: Range<Int>,
into destination: UnsafeMutablePointer<UTF16.CodeUnit>
) {
_NSStringGetCharacters(from: _objc(source), range: range, into: destination)
}
@_effects(readonly)
private func _NSStringGetCharacter(
_ target: _StringSelectorHolder, _ position: Int
) -> UTF16.CodeUnit {
return target.character(at: position)
}
@_effects(readonly)
internal func _cocoaStringSubscript(
_ target: _CocoaString, _ position: Int
) -> UTF16.CodeUnit {
return _NSStringGetCharacter(_objc(target), position)
}
@_effects(releasenone)
private func _NSStringCopyUTF8(
_ o: _StringSelectorHolder,
into bufPtr: UnsafeMutableRawBufferPointer
) -> Int? {
let ptr = bufPtr.baseAddress._unsafelyUnwrappedUnchecked
let len = o.length
var remainingRange = _SwiftNSRange(location: 0, length: 0)
var usedLen = 0
let success = 0 != o.getBytes(
ptr,
maxLength: bufPtr.count,
usedLength: &usedLen,
encoding: _cocoaUTF8Encoding,
options: 0,
range: _SwiftNSRange(location: 0, length: len),
remaining: &remainingRange
)
if success && remainingRange.length == 0 {
return usedLen
}
return nil
}
@_effects(releasenone)
internal func _cocoaStringCopyUTF8(
_ target: _CocoaString,
into bufPtr: UnsafeMutableRawBufferPointer
) -> Int? {
return _NSStringCopyUTF8(_objc(target), into: bufPtr)
}
@_effects(readonly)
private func _NSStringUTF8Count(
_ o: _StringSelectorHolder,
range: Range<Int>
) -> Int? {
var remainingRange = _SwiftNSRange(location: 0, length: 0)
var usedLen = 0
let success = 0 != o.getBytes(
UnsafeMutableRawPointer(Builtin.inttoptr_Word(0._builtinWordValue)),
maxLength: 0,
usedLength: &usedLen,
encoding: _cocoaUTF8Encoding,
options: 0,
range: _SwiftNSRange(location: range.startIndex, length: range.count),
remaining: &remainingRange
)
if success && remainingRange.length == 0 {
return usedLen
}
return nil
}
@_effects(readonly)
internal func _cocoaStringUTF8Count(
_ target: _CocoaString,
range: Range<Int>
) -> Int? {
if range.isEmpty { return 0 }
return _NSStringUTF8Count(_objc(target), range: range)
}
@_effects(readonly)
private func _NSStringCompare(
_ o: _StringSelectorHolder, _ other: _CocoaString
) -> Int {
let range = _SwiftNSRange(location: 0, length: o.length)
let options = UInt(2) /* NSLiteralSearch*/
return o.compare(other, options: options, range: range, locale: nil)
}
@_effects(readonly)
internal func _cocoaStringCompare(
_ string: _CocoaString, _ other: _CocoaString
) -> Int {
return _NSStringCompare(_objc(string), other)
}
@_effects(readonly)
internal func _cocoaHashString(
_ string: _CocoaString
) -> UInt {
return _swift_stdlib_CFStringHashNSString(string)
}
@_effects(readonly)
internal func _cocoaHashASCIIBytes(
_ bytes: UnsafePointer<UInt8>, length: Int
) -> UInt {
return _swift_stdlib_CFStringHashCString(bytes, length)
}
// These "trampolines" are effectively objc_msgSend_super.
// They bypass our implementations to use NSString's.
@_effects(readonly)
internal func _cocoaCStringUsingEncodingTrampoline(
_ string: _CocoaString, _ encoding: UInt
) -> UnsafePointer<UInt8>? {
return _swift_stdlib_NSStringCStringUsingEncodingTrampoline(string, encoding)
}
@_effects(releasenone)
internal func _cocoaGetCStringTrampoline(
_ string: _CocoaString,
_ buffer: UnsafeMutablePointer<UInt8>,
_ maxLength: Int,
_ encoding: UInt
) -> Int8 {
return Int8(_swift_stdlib_NSStringGetCStringTrampoline(
string, buffer, maxLength, encoding))
}
//
// Conversion from NSString to Swift's native representation.
//
private var kCFStringEncodingASCII: _swift_shims_CFStringEncoding {
@inline(__always) get { return 0x0600 }
}
private var kCFStringEncodingUTF8: _swift_shims_CFStringEncoding {
@inline(__always) get { return 0x8000100 }
}
internal enum _KnownCocoaString {
case storage
case shared
case cocoa
#if !(arch(i386) || arch(arm) || arch(wasm32))
case tagged
#endif
#if arch(arm64)
case constantTagged
#endif
@inline(__always)
init(_ str: _CocoaString) {
#if !(arch(i386) || arch(arm))
if _isObjCTaggedPointer(str) {
#if arch(arm64)
if let _ = getConstantTaggedCocoaContents(str) {
self = .constantTagged
} else {
self = .tagged
}
#else
self = .tagged
#endif
return
}
#endif
switch unsafeBitCast(_swift_classOfObjCHeapObject(str), to: UInt.self) {
case unsafeBitCast(__StringStorage.self, to: UInt.self):
self = .storage
case unsafeBitCast(__SharedStringStorage.self, to: UInt.self):
self = .shared
default:
self = .cocoa
}
}
}
#if !(arch(i386) || arch(arm))
// Resiliently write a tagged _CocoaString's contents into a buffer.
// TODO: move this to the Foundation overlay and reimplement it with
// _NSTaggedPointerStringGetBytes
@_effects(releasenone) // @opaque
internal func _bridgeTagged(
_ cocoa: _CocoaString,
intoUTF8 bufPtr: UnsafeMutableRawBufferPointer
) -> Int? {
_internalInvariant(_isObjCTaggedPointer(cocoa))
return _cocoaStringCopyUTF8(cocoa, into: bufPtr)
}
#endif
@_effects(readonly)
private func _NSStringASCIIPointer(_ str: _StringSelectorHolder) -> UnsafePointer<UInt8>? {
// TODO(String bridging): Is there a better interface here? Ideally we'd be
// able to ask for UTF8 rather than just ASCII
return str._fastCStringContents(0)?._asUInt8
}
@_effects(readonly) // @opaque
private func _withCocoaASCIIPointer<R>(
_ str: _CocoaString,
requireStableAddress: Bool,
work: (UnsafePointer<UInt8>) -> R?
) -> R? {
#if !(arch(i386) || arch(arm))
if _isObjCTaggedPointer(str) {
if let ptr = getConstantTaggedCocoaContents(str)?.asciiContentsPointer {
return work(ptr)
}
if requireStableAddress {
return nil // tagged pointer strings don't support _fastCStringContents
}
let tmp = _StringGuts(_SmallString(taggedCocoa: str))
return tmp.withFastUTF8 { work($0.baseAddress._unsafelyUnwrappedUnchecked) }
}
#endif
defer { _fixLifetime(str) }
if let ptr = _NSStringASCIIPointer(_objc(str)) {
return work(ptr)
}
return nil
}
@_effects(readonly) // @opaque
internal func withCocoaASCIIPointer<R>(
_ str: _CocoaString,
work: (UnsafePointer<UInt8>) -> R?
) -> R? {
return _withCocoaASCIIPointer(str, requireStableAddress: false, work: work)
}
@_effects(readonly)
internal func stableCocoaASCIIPointer(_ str: _CocoaString)
-> UnsafePointer<UInt8>? {
return _withCocoaASCIIPointer(str, requireStableAddress: true, work: { $0 })
}
private enum CocoaStringPointer {
case ascii(UnsafePointer<UInt8>)
case utf8(UnsafePointer<UInt8>)
case utf16(UnsafePointer<UInt16>)
case none
}
@_effects(readonly)
private func _getCocoaStringPointer(
_ cfImmutableValue: _CocoaString
) -> CocoaStringPointer {
if let ascii = stableCocoaASCIIPointer(cfImmutableValue) {
return .ascii(ascii)
}
if let utf16Ptr = _stdlib_binary_CFStringGetCharactersPtr(cfImmutableValue) {
return .utf16(utf16Ptr)
}
return .none
}
#if arch(arm64)
//11000000..payload..111
private var constantTagMask:UInt {
0b1111_1111_1000_0000_0000_0000_0000_0000_0000_0000_0000_0000_0000_0000_0000_0111
}
private var expectedConstantTagValue:UInt {
0b1100_0000_0000_0000_0000_0000_0000_0000_0000_0000_0000_0000_0000_0000_0000_0111
}
#endif
@inline(__always)
private func formConstantTaggedCocoaString(
untaggedCocoa: _CocoaString
) -> AnyObject? {
#if !arch(arm64)
return nil
#else
let constantPtr:UnsafeRawPointer = Builtin.reinterpretCast(untaggedCocoa)
// Check if what we're pointing to is actually a valid tagged constant
guard _swift_stdlib_dyld_is_objc_constant_string(constantPtr) == 1 else {
return nil
}
let retaggedPointer = UInt(bitPattern: constantPtr) | expectedConstantTagValue
return unsafeBitCast(retaggedPointer, to: AnyObject.self)
#endif
}
@inline(__always)
private func getConstantTaggedCocoaContents(_ cocoaString: _CocoaString) ->
(utf16Length: Int,
asciiContentsPointer: UnsafePointer<UInt8>,
untaggedCocoa: _CocoaString)? {
#if !arch(arm64)
return nil
#else
guard _isObjCTaggedPointer(cocoaString) else {
return nil
}
let taggedValue = unsafeBitCast(cocoaString, to: UInt.self)
guard taggedValue & constantTagMask == expectedConstantTagValue else {
return nil
}
let payloadMask = ~constantTagMask
let payload = taggedValue & payloadMask
let ivarPointer = UnsafePointer<_swift_shims_builtin_CFString>(
bitPattern: payload
)!
guard _swift_stdlib_dyld_is_objc_constant_string(
UnsafeRawPointer(ivarPointer)
) == 1 else {
return nil
}
let length = ivarPointer.pointee.length
let isUTF16Mask:UInt = 0x0000_0000_0000_0004 //CFStringFlags bit 4: isUnicode
let isASCII = ivarPointer.pointee.flags & isUTF16Mask == 0
precondition(isASCII) // we don't currently support non-ASCII here
let contentsPtr = ivarPointer.pointee.str
return (
utf16Length: Int(length),
asciiContentsPointer: contentsPtr,
untaggedCocoa: Builtin.reinterpretCast(ivarPointer)
)
#endif
}
@usableFromInline
@_effects(releasenone) // @opaque
internal func _bridgeCocoaString(_ cocoaString: _CocoaString) -> _StringGuts {
switch _KnownCocoaString(cocoaString) {
case .storage:
return _unsafeUncheckedDowncast(
cocoaString, to: __StringStorage.self).asString._guts
case .shared:
return _unsafeUncheckedDowncast(
cocoaString, to: __SharedStringStorage.self).asString._guts
#if !(arch(i386) || arch(arm))
case .tagged:
return _StringGuts(_SmallString(taggedCocoa: cocoaString))
#if arch(arm64)
case .constantTagged:
let taggedContents = getConstantTaggedCocoaContents(cocoaString)!
return _StringGuts(
cocoa: taggedContents.untaggedCocoa,
providesFastUTF8: false, //TODO: if contentsPtr is UTF8 compatible, use it
isASCII: true,
length: taggedContents.utf16Length
)
#endif
#endif
case .cocoa:
// "Copy" it into a value to be sure nobody will modify behind
// our backs. In practice, when value is already immutable, this
// just does a retain.
//
// TODO: Only in certain circumstances should we emit this call:
// 1) If it's immutable, just retain it.
// 2) If it's mutable with no associated information, then a copy must
// happen; might as well eagerly bridge it in.
// 3) If it's mutable with associated information, must make the call
let immutableCopy
= _stdlib_binary_CFStringCreateCopy(cocoaString)
#if !(arch(i386) || arch(arm))
if _isObjCTaggedPointer(immutableCopy) {
return _StringGuts(_SmallString(taggedCocoa: immutableCopy))
}
#endif
let (fastUTF8, isASCII): (Bool, Bool)
switch _getCocoaStringPointer(immutableCopy) {
case .ascii(_): (fastUTF8, isASCII) = (true, true)
case .utf8(_): (fastUTF8, isASCII) = (true, false)
default: (fastUTF8, isASCII) = (false, false)
}
let length = _stdlib_binary_CFStringGetLength(immutableCopy)
return _StringGuts(
cocoa: immutableCopy,
providesFastUTF8: fastUTF8,
isASCII: isASCII,
length: length)
}
}
extension String {
@_spi(Foundation)
public init(_cocoaString: AnyObject) {
self._guts = _bridgeCocoaString(_cocoaString)
}
}
@_effects(releasenone)
private func _createNSString(
_ receiver: _StringSelectorHolder,
_ ptr: UnsafePointer<UInt8>,
_ count: Int,
_ encoding: UInt32
) -> AnyObject? {
return receiver.createTaggedString(bytes: ptr, count: count)
}
@_effects(releasenone)
private func _createCFString(
_ ptr: UnsafePointer<UInt8>,
_ count: Int,
_ encoding: UInt32
) -> AnyObject? {
return _createNSString(
unsafeBitCast(__StringStorage.self as AnyClass, to: _StringSelectorHolder.self),
ptr,
count,
encoding
)
}
extension String {
@_effects(releasenone)
public // SPI(Foundation)
func _bridgeToObjectiveCImpl() -> AnyObject {
_connectOrphanedFoundationSubclassesIfNeeded()
// Smol ASCII a) may bridge to tagged pointers, b) can't contain a BOM
if _guts.isSmallASCII {
let maybeTagged = _guts.asSmall.withUTF8 { bufPtr in
return _createCFString(
bufPtr.baseAddress._unsafelyUnwrappedUnchecked,
bufPtr.count,
kCFStringEncodingUTF8
)
}
if let tagged = maybeTagged { return tagged }
}
if _guts.isSmall {
// We can't form a tagged pointer String, so grow to a non-small String,
// and bridge that instead. Also avoids CF deleting any BOM that may be
// present
var copy = self
// TODO: small capacity minimum is lifted, just need to make native
copy._guts.grow(_SmallString.capacity + 1)
_internalInvariant(!copy._guts.isSmall)
return copy._bridgeToObjectiveCImpl()
}
if _guts._object.isImmortal {
// TODO: We'd rather emit a valid ObjC object statically than create a
// shared string class instance.
let gutsCountAndFlags = _guts._object._countAndFlags
return __SharedStringStorage(
immortal: _guts._object.fastUTF8.baseAddress!,
countAndFlags: _StringObject.CountAndFlags(
sharedCount: _guts.count, isASCII: gutsCountAndFlags.isASCII))
}
_internalInvariant(_guts._object.hasObjCBridgeableObject,
"Unknown non-bridgeable object case")
let result = _guts._object.objCBridgeableObject
return formConstantTaggedCocoaString(untaggedCocoa: result) ?? result
}
}
// Note: This function is not intended to be called from Swift. The
// availability information here is perfunctory; this function isn't considered
// part of the Stdlib's Swift ABI.
@available(macOS 10.15.4, iOS 13.4, watchOS 6.2, tvOS 13.4, *)
@_cdecl("_SwiftCreateBridgedString")
@usableFromInline
internal func _SwiftCreateBridgedString_DoNotCall(
bytes: UnsafePointer<UInt8>,
length: Int,
encoding: _swift_shims_CFStringEncoding
) -> Unmanaged<AnyObject> {
let bufPtr = UnsafeBufferPointer(start: bytes, count: length)
let str:String
switch encoding {
case kCFStringEncodingUTF8:
str = String(decoding: bufPtr, as: Unicode.UTF8.self)
case kCFStringEncodingASCII:
str = String(decoding: bufPtr, as: Unicode.ASCII.self)
default:
fatalError("Unsupported encoding in shim")
}
return Unmanaged<AnyObject>.passRetained(str._bridgeToObjectiveCImpl())
}
// At runtime, this class is derived from `__SwiftNativeNSStringBase`,
// which is derived from `NSString`.
//
// The @_swift_native_objc_runtime_base attribute
// This allows us to subclass an Objective-C class and use the fast Swift
// memory allocator.
@objc @_swift_native_objc_runtime_base(__SwiftNativeNSStringBase)
class __SwiftNativeNSString {
@objc internal init() {}
deinit {}
}
// Called by the SwiftObject implementation to get the description of a value
// as an NSString.
@_silgen_name("swift_stdlib_getDescription")
public func _getDescription<T>(_ x: T) -> AnyObject {
return String(reflecting: x)._bridgeToObjectiveCImpl()
}
@_silgen_name("swift_stdlib_NSStringFromUTF8")
@usableFromInline //this makes the symbol available to the runtime :(
@available(macOS 10.15.4, iOS 13.4, watchOS 6.2, tvOS 13.4, *)
internal func _NSStringFromUTF8(_ s: UnsafePointer<UInt8>, _ len: Int)
-> AnyObject {
return String(
decoding: UnsafeBufferPointer(start: s, count: len),
as: UTF8.self
)._bridgeToObjectiveCImpl()
}
#else // !_runtime(_ObjC)
internal class __SwiftNativeNSString {
internal init() {}
deinit {}
}
#endif
// Special-case Index <-> Offset converters for bridging and use in accelerating
// the UTF16View in general.
extension StringProtocol {
@_specialize(where Self == String)
@_specialize(where Self == Substring)
public // SPI(Foundation)
func _toUTF16Offset(_ idx: Index) -> Int {
return self.utf16.distance(from: self.utf16.startIndex, to: idx)
}
@_specialize(where Self == String)
@_specialize(where Self == Substring)
public // SPI(Foundation)
func _toUTF16Index(_ offset: Int) -> Index {
return self.utf16.index(self.utf16.startIndex, offsetBy: offset)
}
@_specialize(where Self == String)
@_specialize(where Self == Substring)
public // SPI(Foundation)
func _toUTF16Offsets(_ indices: Range<Index>) -> Range<Int> {
let lowerbound = _toUTF16Offset(indices.lowerBound)
let length = self.utf16.distance(
from: indices.lowerBound, to: indices.upperBound)
return Range(
uncheckedBounds: (lower: lowerbound, upper: lowerbound + length))
}
@_specialize(where Self == String)
@_specialize(where Self == Substring)
public // SPI(Foundation)
func _toUTF16Indices(_ range: Range<Int>) -> Range<Index> {
let lowerbound = _toUTF16Index(range.lowerBound)
let upperbound = _toUTF16Index(range.lowerBound + range.count)
return Range(uncheckedBounds: (lower: lowerbound, upper: upperbound))
}
}
extension String {
public // @testable / @benchmarkable
func _copyUTF16CodeUnits(
into buffer: UnsafeMutableBufferPointer<UInt16>,
range: Range<Int>
) {
_internalInvariant(buffer.count >= range.count)
let indexRange = self._toUTF16Indices(range)
self.utf16._nativeCopy(into: buffer, alignedRange: indexRange)
}
}
| 3a595b680d147ee635277bc704039709 | 28.305405 | 108 | 0.708983 | false | false | false | false |
GTennis/SuccessFramework | refs/heads/master | Templates/_BusinessAppSwift_/_BusinessAppSwift_/Modules/Home/HomeViewController.swift | mit | 2 | //
// HomeViewController.swift
// _BusinessAppSwift_
//
// Created by Gytenis Mikulenas on 24/10/2016.
// Copyright © 2016 Gytenis Mikulėnas
// https://github.com/GitTennis/SuccessFramework
//
// 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. All rights reserved.
//
import UIKit
let kHomeViewControllerTitleKey = "HomeTitle"
let kHomeViewControllerDataLoadingProgressLabelKey = "HomeProgressLabel"
class HomeViewController: BaseViewController, UICollectionViewDataSource, UICollectionViewDelegate, HomeCellDelegate {
var model: HomeModel?
@IBOutlet weak var collectionView: UICollectionView!
override func viewDidLoad() {
super.viewDidLoad();
self.collectionView.scrollsToTop = true
self.prepareUI()
self.loadModel()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
// Log user behaviour
self.analyticsManager?.log(screenName: kAnalyticsScreen.home)
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
}
// MARK: GenericViewControllerProtocol
override func prepareUI() {
super.prepareUI()
// ...
//self.collectionView.register(HomeCell.self, forCellWithReuseIdentifier: HomeCell.reuseIdentifier)
self.viewLoader?.addRefreshControl(containerView: self.collectionView, callback: { [weak self] in
self?.loadModel()
})
// Set title
self.viewLoader?.setTitle(viewController: self, title: localizedString(key: kHomeViewControllerTitleKey))
}
override func renderUI() {
super.renderUI()
// Reload
self.collectionView.reloadData()
}
override func loadModel() {
self.renderUI()
self.viewLoader?.showScreenActivityIndicator(containerView: self.view)
self.model?.loadData(callback: {[weak self] (success, result, context, error) in
self?.viewLoader?.hideScreenActivityIndicator(containerView: (self?.view)!)
if (success) {
// Render UI
self?.renderUI()
} else {
// Show refresh button when error happens
// ...
}
})
}
// MARK: UICollectionViewDataSource
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
if let list = self.model?.images?.list {
return list.count
} else {
return 0
}
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(
withReuseIdentifier: HomeCell.reuseIdentifier,
for: indexPath
) as! HomeCell
cell.delegate = self
let image = self.model?.images?.list?[(indexPath as NSIndexPath).row]
cell.render(withEntity: image!)
return cell
}
/*- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
return self.collectionViewCellSize;
}*/
/*- (CGSize)collectionViewCellSize {
// Override in child classes
return CGSizeZero;
}*/
// MARK: HomeCellDelegate
func didPressedWithImage(image: ImageEntityProtocol) {
/*UIViewController *viewController = (UIViewController *)[self.viewControllerFactory photoDetailsViewControllerWithContext:image];
[self.navigationController pushViewController:viewController animated:YES];*/
}
}
| 1410993db0c04fedad61e0e0497f9d72 | 30.75 | 169 | 0.631842 | false | false | false | false |
MaddTheSane/Nuke | refs/heads/master | Nuke/Source/UI/ImagePreheatingController.swift | mit | 3 | // The MIT License (MIT)
//
// Copyright (c) 2015 Alexander Grebenyuk (github.com/kean).
import Foundation
import UIKit
/** Signals the delegate that the preheat window changed.
*/
public protocol ImagePreheatingControllerDelegate: class {
func preheatingController(controller: ImagePreheatingController, didUpdateWithAddedIndexPaths addedIndexPaths: [NSIndexPath], removedIndexPaths: [NSIndexPath])
}
/** Automates image preheating. Abstract class.
*/
public class ImagePreheatingController: NSObject {
public weak var delegate: ImagePreheatingControllerDelegate?
public let scrollView: UIScrollView
public private(set) var preheatIndexPath = [NSIndexPath]()
public var enabled = false
deinit {
self.scrollView.removeObserver(self, forKeyPath: "contentOffset", context: nil)
}
public init(scrollView: UIScrollView) {
self.scrollView = scrollView
super.init()
self.scrollView.addObserver(self, forKeyPath: "contentOffset", options: [.New], context: nil)
}
public override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
if object === self.scrollView {
self.scrollViewDidScroll()
} else {
super.observeValueForKeyPath(keyPath, ofObject: object, change: change, context: nil)
}
}
// MARK: Subclassing Hooks
public func scrollViewDidScroll() {
assert(false)
}
public func updatePreheatIndexPaths(indexPaths: [NSIndexPath]) {
let addedIndexPaths = indexPaths.filter { return !self.preheatIndexPath.contains($0) }
let removedIndexPaths = Set(self.preheatIndexPath).subtract(indexPaths)
self.preheatIndexPath = indexPaths
self.delegate?.preheatingController(self, didUpdateWithAddedIndexPaths: addedIndexPaths, removedIndexPaths: Array(removedIndexPaths))
}
}
internal func distanceBetweenPoints(p1: CGPoint, _ p2: CGPoint) -> CGFloat {
let dx = p2.x - p1.x, dy = p2.y - p1.y
return sqrt((dx * dx) + (dy * dy))
}
| 2d02d3d8bb478afb7f523c7569b3dc01 | 36.438596 | 164 | 0.703374 | false | false | false | false |
jekahy/Adoreavatars | refs/heads/master | Adoravatars/DownloadsVC.swift | mit | 1 | //
// DownloadsVC.swift
// Adoravatars
//
// Created by Eugene on 21.06.17.
// Copyright © 2017 Eugene. All rights reserved.
//
import Foundation
import UIKit
import RxSwift
import RxCocoa
import Then
class DownloadsVC: UIViewController {
let cellIdentifier = "downloadCell"
@IBOutlet weak var tableView: UITableView!
private let disposeBag = DisposeBag()
private var viewModel:DownloadsVMType!
private var navigator:Navigator!
override func viewDidLoad()
{
super.viewDidLoad()
automaticallyAdjustsScrollViewInsets = false
viewModel.downloadTasks.drive(tableView.rx.items(cellIdentifier: cellIdentifier, cellType: DownloadCell.self))
{ (index, downloadTask: DownloadTaskType, cell) in
let downloadVM = DownloadVM(downloadTask)
cell.configureWith(downloadVM)
}.addDisposableTo(disposeBag)
}
static func createWith(navigator: Navigator, storyboard: UIStoryboard, viewModel: DownloadsVMType) -> DownloadsVC {
return storyboard.instantiateViewController(ofType: DownloadsVC.self).then { vc in
vc.navigator = navigator
vc.viewModel = viewModel
}
}
}
| 6ae9bf57d6a0412e6634adc7c9698834 | 23.803922 | 119 | 0.666403 | false | false | false | false |
te-th/xID3 | refs/heads/master | Source/ID3Tag.swift | apache-2.0 | 1 | /*
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
*/
import Foundation
/// Represents the ID3 Tag
public final class ID3Identifier {
private let lenId = 3
private let lenVersion = 2
private let lenFlags = 1
private let lenSize = 4
private let lenExtendedHeader = 4
public static let V3 = UInt8(3)
static let id = "ID3"
public let version: ID3Version
public let size: UInt32
/// Indicates that ID3 Tag has an extended header
public let extendedHeader: Bool
private let a_flag_comparator = UInt8(1) << 7
private let b_flag_comparator = UInt8(1) << 6
private let c_flag_comparator = UInt8(1) << 5
/// Create an optional ID3Identifier instance from the given InputStream. Ignores Extended Header.
///
/// - parameters:
/// - stream: An InputStream that may contain an ID3 Tag
///
init? (_ stream: InputStream) {
var identifier = [UInt8](repeating: 0, count: lenId)
stream.read(&identifier, maxLength: lenId)
if ID3Identifier.id != ID3Utils.toString(identifier) {
return nil
}
var version = [UInt8](repeating: 0, count: lenVersion)
stream.read(&version, maxLength: lenVersion)
self.version = ID3Version(version[0], version[1])
if self.version.major != ID3Identifier.V3 {
return nil
}
var flag = [UInt8](repeating: 0, count: lenFlags)
stream.read(&flag, maxLength: lenFlags)
self.extendedHeader = (flag[0] & b_flag_comparator) == UInt8(1)
var size = [UInt8](repeating: 0, count: lenSize)
stream.read(&size, maxLength: lenSize)
self.size = ID3Utils.tagSize(size[0], size[1], size[2], size[3])
if extendedHeader {
var extendedHeaderSizeBuffer = [UInt8](repeating: 0, count: lenExtendedHeader)
stream.read(&extendedHeaderSizeBuffer, maxLength: lenExtendedHeader)
let extendedHeaderSize = ID3Utils.tagSize(size[0], size[1], size[2], size[3])
var dump = [UInt8](repeating: 0, count: Int(extendedHeaderSize) - lenExtendedHeader)
stream.read(&dump, maxLength: dump.count)
}
}
}
/// Represents the content of an ID3 Tag
final class ID3Content {
private let lenId = 4
private let lenSize = 4
private let lenFlag = 2
private var availableFrames = [ID3TagFrame]()
/// Read ID3 Frames from the given InputStream.
///
/// - parameters:
/// - stream: The InputStream containing ID3 Information.
/// - size: Size of the ID3 Tag.
init(_ stream: InputStream, _ size: UInt32) {
var i = UInt32(0)
while i < size {
var frameIdBuffer = [UInt8](repeating: 0, count: lenId)
stream.read(&frameIdBuffer, maxLength: lenId)
let frameId = ID3Utils.toString(frameIdBuffer)
var sizeBuffer = [UInt8](repeating: 0, count: lenSize)
stream.read(&sizeBuffer, maxLength: lenSize)
let frameSize = ID3Utils.frameSize(sizeBuffer[0], sizeBuffer[1], sizeBuffer[2], sizeBuffer[3])
if frameSize == 0 {
break
}
var flagBuffer = [UInt8](repeating: 0, count: lenFlag)
stream.read(&flagBuffer, maxLength: lenFlag)
var contentBuffer = [UInt8](repeating: 0, count: Int(frameSize))
stream.read(&contentBuffer, maxLength: contentBuffer.count)
let frame = ID3TagFrame(id: frameId, size: frameSize, content: contentBuffer, flags: flagBuffer)
availableFrames.append(frame)
i += UInt32(lenId + lenSize + lenFlag) + frameSize
}
}
/// Get the available ID3 Frames.
///
/// - returns: The available ID3 Frames.
public func rawFrames() -> [ID3TagFrame] {
return self.availableFrames
}
}
/// Represents a ID3 Frame.
public struct ID3TagFrame {
let id: String
let size: UInt32
let content: [UInt8]
let flags: [UInt8]
}
/// Represents the ID3 Version.
public final class ID3Version {
let major: UInt8
let minor: UInt8
init(_ major: UInt8, _ minor: UInt8) {
self.major = major
self.minor = minor
}
}
/// An ID3 Tag consisting of an ID3Identifier and the avaikable Frames.
public struct ID3Tag {
let identifier: ID3Identifier
private let content: ID3Content
init(_ identifier: ID3Identifier, _ content: ID3Content) {
self.identifier = identifier
self.content = content
}
/// Return the available ID3 Frames.
///
/// - returns: The available ID3 Frames.
public func rawFrames() -> [ID3TagFrame] {
return content.rawFrames()
}
}
/// Utility type extracting an ID3Tag from a given InputStream. Right not ID3v3 is supported.
public final class ID3Reader {
/// Extracts an ID3Tag from a given InputStream.
///
/// - parameters:
/// - stream An InputStream that may contain ID3 information.
///
/// - return: An optional ID3Tag
public static func read(_ stream: InputStream) -> ID3Tag? {
let id = ID3Identifier(stream)
guard let identifier = id else {
return nil
}
let content = ID3Content(stream, identifier.size)
return ID3Tag(identifier, content)
}
}
| 6ed424bb69a32dd692def193459ada84 | 30.395833 | 108 | 0.644161 | false | false | false | false |
sedler/AlamofireRSSParser | refs/heads/master | Pod/Classes/RSSFeed.swift | mit | 1 | //
// RSSFeed.swift
// AlamofireRSSParser
//
// Created by Donald Angelillo on 3/1/16.
// Copyright © 2016 Donald Angelillo. All rights reserved.
//
import Foundation
/**
RSS gets deserialized into an instance of `RSSFeed`. Top-level RSS elements are housed here.
Item-level elements are deserialized into `RSSItem` objects and stored in the `items` property.
*/
open class RSSFeed: CustomStringConvertible {
open var title: String? = nil
open var link: String? = nil
open var feedDescription: String? = nil
open var pubDate: Date? = nil
open var lastBuildDate: Date? = nil
open var language: String? = nil
open var copyright: String? = nil
open var managingEditor: String? = nil
open var webMaster: String? = nil
open var generator: String? = nil
open var docs: String? = nil
open var ttl: NSNumber? = nil
open var items: [RSSItem] = Array()
open var description: String {
return "title: \(self.title)\nfeedDescription: \(self.feedDescription)\nlink: \(self.link)\npubDate: \(self.pubDate)\nlastBuildDate: \(self.lastBuildDate)\nlanguage: \(self.language)\ncopyright: \(self.copyright)\nmanagingEditor: \(self.managingEditor)\nwebMaster: \(self.webMaster)\ngenerator: \(self.generator)\ndocs: \(self.docs)\nttl: \(self.ttl)\nitems: \n\(self.items)"
}
}
| 4fa861cda8b0362985a8366a3bf9ced8 | 36.694444 | 383 | 0.685335 | false | false | false | false |
anthonypuppo/GDAXSwift | refs/heads/master | GDAXSwift/Classes/GDAXCurrency.swift | mit | 1 | //
// GDAXCurrency.swift
// GDAXSwift
//
// Created by Anthony on 6/4/17.
// Copyright © 2017 Anthony Puppo. All rights reserved.
//
public struct GDAXCurrency: JSONInitializable {
public let id: String
public let name: String
public let minSize: Double
internal init(json: Any) throws {
var jsonData: Data?
if let json = json as? Data {
jsonData = json
} else {
jsonData = try JSONSerialization.data(withJSONObject: json, options: [])
}
guard let json = jsonData?.json else {
throw GDAXError.invalidResponseData
}
guard let id = json["id"] as? String else {
throw GDAXError.responseParsingFailure("id")
}
guard let name = json["name"] as? String else {
throw GDAXError.responseParsingFailure("name")
}
guard let minSize = Double(json["min_size"] as? String ?? "") else {
throw GDAXError.responseParsingFailure("min_size")
}
self.id = id
self.name = name
self.minSize = minSize
}
}
| ccffac48e53b0317962a43f8c633ab49 | 20.422222 | 75 | 0.669087 | false | false | false | false |
Chuck8080/ios-swift-swiftyjson | refs/heads/master | DongerListKeyboard/vendors/SwiftyJSON-master/Tests/NumberTests.swift | mit | 18 | // NumberTests.swift
//
// Copyright (c) 2014 Pinglin Tang
//
// 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 XCTest
import SwiftyJSON
class NumberTests: XCTestCase {
func testNumber() {
//getter
var json = JSON(NSNumber(double: 9876543210.123456789))
XCTAssertEqual(json.number!, 9876543210.123456789)
XCTAssertEqual(json.numberValue, 9876543210.123456789)
XCTAssertEqual(json.stringValue, "9876543210.123457")
//setter
json.number = NSNumber(double: 123456789.0987654321)
XCTAssertEqual(json.number!, 123456789.0987654321)
XCTAssertEqual(json.numberValue, 123456789.0987654321)
json.number = nil
XCTAssertEqual(json.numberValue, 0)
XCTAssertEqual(json.object as NSNull, NSNull())
XCTAssertTrue(json.number == nil)
json.numberValue = 2.9876
XCTAssertEqual(json.number!, 2.9876)
}
func testBool() {
var json = JSON(true)
XCTAssertEqual(json.bool!, true)
XCTAssertEqual(json.boolValue, true)
XCTAssertEqual(json.numberValue, true as NSNumber)
XCTAssertEqual(json.stringValue, "true")
json.bool = false
XCTAssertEqual(json.bool!, false)
XCTAssertEqual(json.boolValue, false)
XCTAssertEqual(json.numberValue, false as NSNumber)
json.bool = nil
XCTAssertTrue(json.bool == nil)
XCTAssertEqual(json.boolValue, false)
XCTAssertEqual(json.numberValue, 0)
json.boolValue = true
XCTAssertEqual(json.bool!, true)
XCTAssertEqual(json.boolValue, true)
XCTAssertEqual(json.numberValue, true as NSNumber)
}
func testDouble() {
var json = JSON(9876543210.123456789)
XCTAssertEqual(json.double!, 9876543210.123456789)
XCTAssertEqual(json.doubleValue, 9876543210.123456789)
XCTAssertEqual(json.numberValue, 9876543210.123456789)
XCTAssertEqual(json.stringValue, "9876543210.123457")
json.double = 2.8765432
XCTAssertEqual(json.double!, 2.8765432)
XCTAssertEqual(json.doubleValue, 2.8765432)
XCTAssertEqual(json.numberValue, 2.8765432)
json.doubleValue = 89.0987654
XCTAssertEqual(json.double!, 89.0987654)
XCTAssertEqual(json.doubleValue, 89.0987654)
XCTAssertEqual(json.numberValue, 89.0987654)
json.double = nil
XCTAssertEqual(json.boolValue, false)
XCTAssertEqual(json.doubleValue, 0.0)
XCTAssertEqual(json.numberValue, 0)
}
func testFloat() {
var json = JSON(54321.12345)
XCTAssertTrue(json.float! == 54321.12345)
XCTAssertTrue(json.floatValue == 54321.12345)
println(json.numberValue.doubleValue)
XCTAssertEqual(json.numberValue, 54321.12345)
XCTAssertEqual(json.stringValue, "54321.12345")
json.float = 23231.65
XCTAssertTrue(json.float! == 23231.65)
XCTAssertTrue(json.floatValue == 23231.65)
XCTAssertEqual(json.numberValue, NSNumber(float:23231.65))
json.floatValue = -98766.23
XCTAssertEqual(json.float!, -98766.23)
XCTAssertEqual(json.floatValue, -98766.23)
XCTAssertEqual(json.numberValue, NSNumber(float:-98766.23))
}
func testInt() {
var json = JSON(123456789)
XCTAssertEqual(json.int!, 123456789)
XCTAssertEqual(json.intValue, 123456789)
XCTAssertEqual(json.numberValue, NSNumber(integer: 123456789))
XCTAssertEqual(json.stringValue, "123456789")
json.int = nil
XCTAssertTrue(json.boolValue == false)
XCTAssertTrue(json.intValue == 0)
XCTAssertEqual(json.numberValue, 0)
XCTAssertEqual(json.object as NSNull, NSNull())
XCTAssertTrue(json.int == nil)
json.intValue = 76543
XCTAssertEqual(json.int!, 76543)
XCTAssertEqual(json.intValue, 76543)
XCTAssertEqual(json.numberValue, NSNumber(integer: 76543))
json.intValue = 98765421
XCTAssertEqual(json.int!, 98765421)
XCTAssertEqual(json.intValue, 98765421)
XCTAssertEqual(json.numberValue, NSNumber(integer: 98765421))
}
func testUInt() {
var json = JSON(123456789)
XCTAssertTrue(json.uInt! == 123456789)
XCTAssertTrue(json.uIntValue == 123456789)
XCTAssertEqual(json.numberValue, NSNumber(unsignedInteger: 123456789))
XCTAssertEqual(json.stringValue, "123456789")
json.uInt = nil
XCTAssertTrue(json.boolValue == false)
XCTAssertTrue(json.uIntValue == 0)
XCTAssertEqual(json.numberValue, 0)
XCTAssertEqual(json.object as NSNull, NSNull())
XCTAssertTrue(json.uInt == nil)
json.uIntValue = 76543
XCTAssertTrue(json.uInt! == 76543)
XCTAssertTrue(json.uIntValue == 76543)
XCTAssertEqual(json.numberValue, NSNumber(unsignedInteger: 76543))
json.uIntValue = 98765421
XCTAssertTrue(json.uInt! == 98765421)
XCTAssertTrue(json.uIntValue == 98765421)
XCTAssertEqual(json.numberValue, NSNumber(unsignedInteger: 98765421))
}
func testInt8() {
let n127 = NSNumber(char: 127)
var json = JSON(n127)
XCTAssertTrue(json.int8! == n127.charValue)
XCTAssertTrue(json.int8Value == n127.charValue)
XCTAssertTrue(json.number! == n127)
XCTAssertEqual(json.numberValue, n127)
XCTAssertEqual(json.stringValue, "127")
let nm128 = NSNumber(char: -128)
json.int8Value = nm128.charValue
XCTAssertTrue(json.int8! == nm128.charValue)
XCTAssertTrue(json.int8Value == nm128.charValue)
XCTAssertTrue(json.number! == nm128)
XCTAssertEqual(json.numberValue, nm128)
XCTAssertEqual(json.stringValue, "-128")
let n0 = NSNumber(char: 0 as Int8)
json.int8Value = n0.charValue
XCTAssertTrue(json.int8! == n0.charValue)
XCTAssertTrue(json.int8Value == n0.charValue)
println(json.number)
XCTAssertTrue(json.number! == n0)
XCTAssertEqual(json.numberValue, n0)
#if (arch(x86_64) || arch(arm64))
XCTAssertEqual(json.stringValue, "false")
#elseif (arch(i386) || arch(arm))
XCTAssertEqual(json.stringValue, "0")
#endif
let n1 = NSNumber(char: 1 as Int8)
json.int8Value = n1.charValue
XCTAssertTrue(json.int8! == n1.charValue)
XCTAssertTrue(json.int8Value == n1.charValue)
XCTAssertTrue(json.number! == n1)
XCTAssertEqual(json.numberValue, n1)
#if (arch(x86_64) || arch(arm64))
XCTAssertEqual(json.stringValue, "true")
#elseif (arch(i386) || arch(arm))
XCTAssertEqual(json.stringValue, "1")
#endif
}
func testUInt8() {
let n255 = NSNumber(unsignedChar: 255)
var json = JSON(n255)
XCTAssertTrue(json.uInt8! == n255.unsignedCharValue)
XCTAssertTrue(json.uInt8Value == n255.unsignedCharValue)
XCTAssertTrue(json.number! == n255)
XCTAssertEqual(json.numberValue, n255)
XCTAssertEqual(json.stringValue, "255")
let nm2 = NSNumber(unsignedChar: 2)
json.uInt8Value = nm2.unsignedCharValue
XCTAssertTrue(json.uInt8! == nm2.unsignedCharValue)
XCTAssertTrue(json.uInt8Value == nm2.unsignedCharValue)
XCTAssertTrue(json.number! == nm2)
XCTAssertEqual(json.numberValue, nm2)
XCTAssertEqual(json.stringValue, "2")
let nm0 = NSNumber(unsignedChar: 0)
json.uInt8Value = nm0.unsignedCharValue
XCTAssertTrue(json.uInt8! == nm0.unsignedCharValue)
XCTAssertTrue(json.uInt8Value == nm0.unsignedCharValue)
XCTAssertTrue(json.number! == nm0)
XCTAssertEqual(json.numberValue, nm0)
XCTAssertEqual(json.stringValue, "0")
let nm1 = NSNumber(unsignedChar: 1)
json.uInt8 = nm1.unsignedCharValue
XCTAssertTrue(json.uInt8! == nm1.unsignedCharValue)
XCTAssertTrue(json.uInt8Value == nm1.unsignedCharValue)
XCTAssertTrue(json.number! == nm1)
XCTAssertEqual(json.numberValue, nm1)
XCTAssertEqual(json.stringValue, "1")
}
func testInt16() {
let n32767 = NSNumber(short: 32767)
var json = JSON(n32767)
XCTAssertTrue(json.int16! == n32767.shortValue)
XCTAssertTrue(json.int16Value == n32767.shortValue)
XCTAssertTrue(json.number! == n32767)
XCTAssertEqual(json.numberValue, n32767)
XCTAssertEqual(json.stringValue, "32767")
let nm32768 = NSNumber(short: -32768)
json.int16Value = nm32768.shortValue
XCTAssertTrue(json.int16! == nm32768.shortValue)
XCTAssertTrue(json.int16Value == nm32768.shortValue)
XCTAssertTrue(json.number! == nm32768)
XCTAssertEqual(json.numberValue, nm32768)
XCTAssertEqual(json.stringValue, "-32768")
let n0 = NSNumber(short: 0)
json.int16Value = n0.shortValue
XCTAssertTrue(json.int16! == n0.shortValue)
XCTAssertTrue(json.int16Value == n0.shortValue)
println(json.number)
XCTAssertTrue(json.number! == n0)
XCTAssertEqual(json.numberValue, n0)
XCTAssertEqual(json.stringValue, "0")
let n1 = NSNumber(short: 1)
json.int16 = n1.shortValue
XCTAssertTrue(json.int16! == n1.shortValue)
XCTAssertTrue(json.int16Value == n1.shortValue)
XCTAssertTrue(json.number! == n1)
XCTAssertEqual(json.numberValue, n1)
XCTAssertEqual(json.stringValue, "1")
}
func testUInt16() {
let n65535 = NSNumber(unsignedInteger: 65535)
var json = JSON(n65535)
XCTAssertTrue(json.uInt16! == n65535.unsignedShortValue)
XCTAssertTrue(json.uInt16Value == n65535.unsignedShortValue)
XCTAssertTrue(json.number! == n65535)
XCTAssertEqual(json.numberValue, n65535)
XCTAssertEqual(json.stringValue, "65535")
let n32767 = NSNumber(unsignedInteger: 32767)
json.uInt16 = n32767.unsignedShortValue
XCTAssertTrue(json.uInt16! == n32767.unsignedShortValue)
XCTAssertTrue(json.uInt16Value == n32767.unsignedShortValue)
XCTAssertTrue(json.number! == n32767)
XCTAssertEqual(json.numberValue, n32767)
XCTAssertEqual(json.stringValue, "32767")
}
func testInt32() {
let n2147483647 = NSNumber(int: 2147483647)
var json = JSON(n2147483647)
XCTAssertTrue(json.int32! == n2147483647.intValue)
XCTAssertTrue(json.int32Value == n2147483647.intValue)
XCTAssertTrue(json.number! == n2147483647)
XCTAssertEqual(json.numberValue, n2147483647)
XCTAssertEqual(json.stringValue, "2147483647")
let n32767 = NSNumber(int: 32767)
json.int32 = n32767.intValue
XCTAssertTrue(json.int32! == n32767.intValue)
XCTAssertTrue(json.int32Value == n32767.intValue)
XCTAssertTrue(json.number! == n32767)
XCTAssertEqual(json.numberValue, n32767)
XCTAssertEqual(json.stringValue, "32767")
let nm2147483648 = NSNumber(int: -2147483648)
json.int32Value = nm2147483648.intValue
XCTAssertTrue(json.int32! == nm2147483648.intValue)
XCTAssertTrue(json.int32Value == nm2147483648.intValue)
XCTAssertTrue(json.number! == nm2147483648)
XCTAssertEqual(json.numberValue, nm2147483648)
XCTAssertEqual(json.stringValue, "-2147483648")
}
func testUInt32() {
let n2147483648 = NSNumber(unsignedInt: 2147483648)
var json = JSON(n2147483648)
XCTAssertTrue(json.uInt32! == n2147483648.unsignedIntValue)
XCTAssertTrue(json.uInt32Value == n2147483648.unsignedIntValue)
XCTAssertTrue(json.number! == n2147483648)
XCTAssertEqual(json.numberValue, n2147483648)
XCTAssertEqual(json.stringValue, "2147483648")
let n32767 = NSNumber(unsignedInt: 32767)
json.uInt32 = n32767.unsignedIntValue
XCTAssertTrue(json.uInt32! == n32767.unsignedIntValue)
XCTAssertTrue(json.uInt32Value == n32767.unsignedIntValue)
XCTAssertTrue(json.number! == n32767)
XCTAssertEqual(json.numberValue, n32767)
XCTAssertEqual(json.stringValue, "32767")
let n0 = NSNumber(unsignedInt: 0)
json.uInt32Value = n0.unsignedIntValue
XCTAssertTrue(json.uInt32! == n0.unsignedIntValue)
XCTAssertTrue(json.uInt32Value == n0.unsignedIntValue)
XCTAssertTrue(json.number! == n0)
XCTAssertEqual(json.numberValue, n0)
XCTAssertEqual(json.stringValue, "0")
}
func testInt64() {
let int64Max = NSNumber(longLong: INT64_MAX)
var json = JSON(int64Max)
XCTAssertTrue(json.int64! == int64Max.longLongValue)
XCTAssertTrue(json.int64Value == int64Max.longLongValue)
XCTAssertTrue(json.number! == int64Max)
XCTAssertEqual(json.numberValue, int64Max)
XCTAssertEqual(json.stringValue, int64Max.stringValue)
let n32767 = NSNumber(longLong: 32767)
json.int64 = n32767.longLongValue
XCTAssertTrue(json.int64! == n32767.longLongValue)
XCTAssertTrue(json.int64Value == n32767.longLongValue)
XCTAssertTrue(json.number! == n32767)
XCTAssertEqual(json.numberValue, n32767)
XCTAssertEqual(json.stringValue, "32767")
let int64Min = NSNumber(longLong: (INT64_MAX-1) * -1)
json.int64Value = int64Min.longLongValue
XCTAssertTrue(json.int64! == int64Min.longLongValue)
XCTAssertTrue(json.int64Value == int64Min.longLongValue)
XCTAssertTrue(json.number! == int64Min)
XCTAssertEqual(json.numberValue, int64Min)
XCTAssertEqual(json.stringValue, int64Min.stringValue)
}
func testUInt64() {
let uInt64Max = NSNumber(unsignedLongLong: UINT64_MAX)
var json = JSON(uInt64Max)
XCTAssertTrue(json.uInt64! == uInt64Max.unsignedLongLongValue)
XCTAssertTrue(json.uInt64Value == uInt64Max.unsignedLongLongValue)
XCTAssertTrue(json.number! == uInt64Max)
XCTAssertEqual(json.numberValue, uInt64Max)
XCTAssertEqual(json.stringValue, uInt64Max.stringValue)
let n32767 = NSNumber(longLong: 32767)
json.int64 = n32767.longLongValue
XCTAssertTrue(json.int64! == n32767.longLongValue)
XCTAssertTrue(json.int64Value == n32767.longLongValue)
XCTAssertTrue(json.number! == n32767)
XCTAssertEqual(json.numberValue, n32767)
XCTAssertEqual(json.stringValue, "32767")
}
}
| 3f4842fdea26540265dcadcbfa100e0f | 40.005141 | 81 | 0.658767 | false | false | false | false |
warrenm/slug-swift-metal | refs/heads/master | SwiftMetalDemo/MBEDemoThree.swift | mit | 1 | //
// MBEDemoThree.swift
// SwiftMetalDemo
//
// Created by Warren Moore on 11/4/14.
// Copyright (c) 2014 Warren Moore. All rights reserved.
//
import UIKit
import Metal
class MBEDemoThreeViewController : MBEDemoViewController {
var depthStencilState: MTLDepthStencilState! = nil
var vertexBuffer: MTLBuffer! = nil
var indexBuffer: MTLBuffer! = nil
var uniformBuffer: MTLBuffer! = nil
var depthTexture: MTLTexture! = nil
var diffuseTexture: MTLTexture! = nil
var samplerState: MTLSamplerState! = nil
var rotationAngle: Float = 0
func textureForImage(_ image:UIImage, device:MTLDevice) -> MTLTexture?
{
let imageRef = image.cgImage!
let width = imageRef.width
let height = imageRef.height
let colorSpace = CGColorSpaceCreateDeviceRGB()
let rawData = calloc(height * width * 4, MemoryLayout<UInt8>.stride)
let bytesPerPixel = 4
let bytesPerRow = bytesPerPixel * width
let bitsPerComponent = 8
let options = CGImageAlphaInfo.premultipliedLast.rawValue | CGBitmapInfo.byteOrder32Big.rawValue
let context = CGContext(data: rawData,
width: width,
height: height,
bitsPerComponent: bitsPerComponent,
bytesPerRow: bytesPerRow,
space: colorSpace,
bitmapInfo: options)
context?.draw(imageRef, in: CGRect(x: 0, y: 0, width: CGFloat(width), height: CGFloat(height)))
let textureDescriptor = MTLTextureDescriptor.texture2DDescriptor(pixelFormat: .rgba8Unorm,
width: Int(width),
height: Int(height),
mipmapped: true)
let texture = device.makeTexture(descriptor: textureDescriptor)
let region = MTLRegionMake2D(0, 0, Int(width), Int(height))
texture?.replace(region: region,
mipmapLevel: 0,
slice: 0,
withBytes: rawData!,
bytesPerRow: bytesPerRow,
bytesPerImage: bytesPerRow * height)
free(rawData)
return texture
}
override func buildPipeline() {
let library = device.makeDefaultLibrary()!
let vertexFunction = library.makeFunction(name: "vertex_demo_three")
let fragmentFunction = library.makeFunction(name: "fragment_demo_three")
let vertexDescriptor = MTLVertexDescriptor()
vertexDescriptor.attributes[0].offset = 0
vertexDescriptor.attributes[0].format = .float4
vertexDescriptor.attributes[0].bufferIndex = 0
vertexDescriptor.attributes[1].offset = MemoryLayout<Float>.stride * 4
vertexDescriptor.attributes[1].format = .float4
vertexDescriptor.attributes[1].bufferIndex = 0
vertexDescriptor.attributes[2].offset = MemoryLayout<Float>.stride * 8
vertexDescriptor.attributes[2].format = .float2
vertexDescriptor.attributes[2].bufferIndex = 0
vertexDescriptor.layouts[0].stepFunction = .perVertex
vertexDescriptor.layouts[0].stride = MemoryLayout<Vertex>.stride
let pipelineDescriptor = MTLRenderPipelineDescriptor()
pipelineDescriptor.vertexFunction = vertexFunction
pipelineDescriptor.vertexDescriptor = vertexDescriptor
pipelineDescriptor.fragmentFunction = fragmentFunction
pipelineDescriptor.colorAttachments[0].pixelFormat = .bgra8Unorm
pipelineDescriptor.depthAttachmentPixelFormat = .depth32Float
let error: NSErrorPointer? = nil
pipeline = try? device.makeRenderPipelineState(descriptor: pipelineDescriptor)
if (pipeline == nil) {
print("Error occurred when creating pipeline \(String(describing: error))")
}
let depthStencilDescriptor = MTLDepthStencilDescriptor()
depthStencilDescriptor.depthCompareFunction = .less
depthStencilDescriptor.isDepthWriteEnabled = true
depthStencilState = device.makeDepthStencilState(descriptor: depthStencilDescriptor)
commandQueue = device.makeCommandQueue()
let samplerDescriptor = MTLSamplerDescriptor()
samplerDescriptor.minFilter = .nearest
samplerDescriptor.magFilter = .linear
samplerState = device.makeSamplerState(descriptor: samplerDescriptor)
}
override func buildResources() {
let (vertexBuffer, indexBuffer) = SphereGenerator.sphereWithRadius(1, stacks: 30, slices: 30, device: device)
self.vertexBuffer = vertexBuffer
self.indexBuffer = indexBuffer
uniformBuffer = device.makeBuffer(length: MemoryLayout<Matrix4x4>.stride * 2, options: [])
diffuseTexture = self.textureForImage(UIImage(named: "bluemarble")!, device: device)
}
override func resize() {
super.resize()
let layerSize = metalLayer.drawableSize
let depthTextureDescriptor = MTLTextureDescriptor.texture2DDescriptor(pixelFormat: .depth32Float,
width: Int(layerSize.width),
height: Int(layerSize.height),
mipmapped: false)
depthTextureDescriptor.storageMode = .private
depthTextureDescriptor.usage = .renderTarget
depthTexture = device.makeTexture(descriptor: depthTextureDescriptor)
}
override func draw() {
if let drawable = metalLayer.nextDrawable()
{
let yAxis = Vector4(x: 0, y: -1, z: 0, w: 0)
var modelViewMatrix = Matrix4x4.rotationAboutAxis(yAxis, byAngle: rotationAngle)
modelViewMatrix.W.z = -2.5
let aspect = Float(metalLayer.drawableSize.width) / Float(metalLayer.drawableSize.height)
let projectionMatrix = Matrix4x4.perspectiveProjection(aspect, fieldOfViewY: 60, near: 0.1, far: 100.0)
let matrices = [projectionMatrix, modelViewMatrix]
memcpy(uniformBuffer.contents(), matrices, Int(MemoryLayout<Matrix4x4>.stride * 2))
let commandBuffer = commandQueue.makeCommandBuffer()
let passDescriptor = MTLRenderPassDescriptor()
passDescriptor.colorAttachments[0].texture = drawable.texture
passDescriptor.colorAttachments[0].clearColor = MTLClearColorMake(0.05, 0.05, 0.05, 1)
passDescriptor.colorAttachments[0].loadAction = .clear
passDescriptor.colorAttachments[0].storeAction = .store
passDescriptor.depthAttachment.texture = depthTexture
passDescriptor.depthAttachment.clearDepth = 1
passDescriptor.depthAttachment.loadAction = .clear
passDescriptor.depthAttachment.storeAction = .dontCare
let indexCount = indexBuffer.length / MemoryLayout<UInt16>.stride
let commandEncoder = commandBuffer?.makeRenderCommandEncoder(descriptor: passDescriptor)
if userToggle {
commandEncoder?.setTriangleFillMode(.lines)
}
commandEncoder?.setRenderPipelineState(pipeline)
commandEncoder?.setDepthStencilState(depthStencilState)
commandEncoder?.setCullMode(.back)
commandEncoder?.setVertexBuffer(vertexBuffer, offset:0, index:0)
commandEncoder?.setVertexBuffer(uniformBuffer, offset:0, index:1)
commandEncoder?.setFragmentTexture(diffuseTexture, index: 0)
commandEncoder?.setFragmentSamplerState(samplerState, index: 0)
commandEncoder?.drawIndexedPrimitives(type: .triangle,
indexCount:indexCount,
indexType:.uint16,
indexBuffer:indexBuffer,
indexBufferOffset: 0)
commandEncoder?.endEncoding()
commandBuffer?.present(drawable)
commandBuffer?.commit()
rotationAngle += 0.01
}
}
}
| 683f3d70af521b68e18236cea6bc3f65 | 43.841026 | 117 | 0.595608 | false | false | false | false |
tudou152/QQZone | refs/heads/master | QQZone/QQZone/Classes/Home/HomeViewController.swift | mit | 1 | //
// HomeViewController.swift
// QQZone
//
// Created by 君哥 on 2016/11/22.
// Copyright © 2016年 fistBlood. All rights reserved.
//
import UIKit
extension Selector {
static let iconBtnClick = #selector(HomeViewController().iconBtnClick)
}
class HomeViewController: UIViewController {
// MARK: 属性
/// 当前选中的索引
var currrentIndex: Int = 0
/// 容器视图
lazy var containerView: UIView = {
// 设置尺寸
let width = min(self.view.frame.width, self.view.frame.height) - kDockItemWH
let y: CGFloat = 20
let height: CGFloat = self.view.frame.height - y
let x = self.dockView.frame.maxX
let containerView = UIView(frame: CGRect(x: x, y: y, width: width, height: height))
return containerView
}()
/// 导航栏
lazy var dockView: DockView = {
// 设置尺寸
let isLandscape = self.view.frame.width > self.view.frame.height
let w = isLandscape ? kDockLandscapeWidth : kDockPortraitWidth
let dockView = DockView(frame: CGRect(x: 0, y: 0, width: w, height: self.view.bounds.height))
dockView.iconView.addTarget(self, action: .iconBtnClick, for: .touchUpInside)
// 设置代理
dockView.tabBarView.delegate = self
return dockView
}()
override func viewDidLoad() {
super.viewDidLoad()
// 初始化设置
setup()
}
// 设置状态栏的颜色
override var preferredStatusBarStyle: UIStatusBarStyle {
return .lightContent
}
}
// MARK: 设置子控件
extension HomeViewController {
fileprivate func setup() {
view.backgroundColor = UIColor(r: 55, g: 55, b: 55)
// 添加Dock
view.addSubview(dockView)
// 添加containerView
view.addSubview(containerView)
// 添加所有的子控制器
setupChildViewControllers()
// 底部菜单栏的点击的回调
dockView.bottomMenuView.didClickBtn = {
[weak self] type in
switch type {
case .mood:
let moodVC = MoodViewController()
let nav = UINavigationController(rootViewController: moodVC)
nav.modalPresentationStyle = .formSheet
self?.present(nav, animated: true, completion: nil)
case .photo:
print("发表图片")
case .blog:
print("发表日志")
}
}
}
/// 添加所有子控制器
fileprivate func setupChildViewControllers() {
addOneViewController(AllStatusViewController() , "全部动态", .red)
addOneViewController(UIViewController() , "与我相关", .blue)
addOneViewController(UIViewController(), "照片墙", .darkGray)
addOneViewController(UIViewController(), "电子相框", .yellow)
addOneViewController(UIViewController(), "好友", .orange)
addOneViewController(UIViewController(), "更多", .white)
addOneViewController(CenterViewController(), "个人中心", .gray)
}
private func addOneViewController(_ viewController: UIViewController, _ title: String,_ bgColor: UIColor) {
// 设置控制器属性
viewController.view.backgroundColor = bgColor
viewController.title = title
// 设置导航控制器属性
let nav = UINavigationController(rootViewController: viewController)
nav.navigationBar.isTranslucent = false // 设置导航栏不透明
addChildViewController(nav)
}
}
// MARK: 监听屏幕的旋转
extension HomeViewController {
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
// 将屏幕旋转的时间传递给子控件
self.dockView.viewWillTransiton(to: size, with: coordinator)
// 设置子控件的尺寸
let width = min(size.width, size.height) - kDockItemWH
let y: CGFloat = 20
let height: CGFloat = size.height - y
let x = dockView.frame.maxX
containerView.frame = CGRect(x: x, y: y, width: width, height: height)
}
}
// MARK: TabBarViewDelegate
extension HomeViewController: TabBarViewDelegate {
func tabBarViewSelectIndex(_ tabBarView: TabBarView, from: NSInteger, to: NSInteger) {
// 移除旧的View
let oldVC = childViewControllers[from]
oldVC.view.removeFromSuperview()
// 添加新的View
let newVC = childViewControllers[to]
containerView.addSubview(newVC.view)
newVC.view.frame = containerView.bounds
// 记录当前选中的索引
currrentIndex = to
}
}
// MARK: 监听按钮点击
extension HomeViewController {
/// 取消正在选中的按钮
func iconBtnClick() {
// 取消中间菜单栏的选中状态
dockView.tabBarView.selectBtn?.isSelected = false
tabBarViewSelectIndex(dockView.tabBarView, from: currrentIndex, to: childViewControllers.count - 1)
}
}
| 36f8259259c15c6f6ae287fcd3c7ec07 | 27.467836 | 112 | 0.603328 | false | false | false | false |
Esri/arcgis-runtime-samples-ios | refs/heads/main | arcgis-ios-sdk-samples/Scenes/Animate 3D graphic/CameraSettingsViewController.swift | apache-2.0 | 1 | //
// Copyright 2017 Esri.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import UIKit
import ArcGIS
class CameraSettingsViewController: UITableViewController {
weak var orbitGeoElementCameraController: AGSOrbitGeoElementCameraController?
@IBOutlet var headingOffsetSlider: UISlider!
@IBOutlet var pitchOffsetSlider: UISlider!
@IBOutlet var distanceSlider: UISlider!
@IBOutlet var distanceLabel: UILabel!
@IBOutlet var headingOffsetLabel: UILabel!
@IBOutlet var pitchOffsetLabel: UILabel!
@IBOutlet var autoHeadingEnabledSwitch: UISwitch!
@IBOutlet var autoPitchEnabledSwitch: UISwitch!
@IBOutlet var autoRollEnabledSwitch: UISwitch!
private var distanceObservation: NSKeyValueObservation?
private var headingObservation: NSKeyValueObservation?
private var pitchObservation: NSKeyValueObservation?
let measurementFormatter: MeasurementFormatter = {
let formatter = MeasurementFormatter()
formatter.numberFormatter.maximumFractionDigits = 0
formatter.unitOptions = .providedUnit
return formatter
}()
override func viewDidLoad() {
super.viewDidLoad()
guard let cameraController = orbitGeoElementCameraController else {
return
}
// apply initial values to controls
updateUIForDistance()
updateUIForHeadingOffset()
updateUIForPitchOffset()
autoHeadingEnabledSwitch.isOn = cameraController.isAutoHeadingEnabled
autoPitchEnabledSwitch.isOn = cameraController.isAutoPitchEnabled
autoRollEnabledSwitch.isOn = cameraController.isAutoRollEnabled
// add observers to the values we want to show in the UI
distanceObservation = cameraController.observe(\.cameraDistance) { [weak self] (_, _) in
DispatchQueue.main.async {
self?.updateUIForDistance()
}
}
headingObservation = cameraController.observe(\.cameraHeadingOffset) { [weak self] (_, _) in
DispatchQueue.main.async {
self?.updateUIForHeadingOffset()
}
}
pitchObservation = cameraController.observe(\.cameraPitchOffset) { [weak self] (_, _) in
DispatchQueue.main.async {
self?.updateUIForPitchOffset()
}
}
}
private func updateUIForDistance() {
guard let cameraController = orbitGeoElementCameraController else {
return
}
distanceSlider.value = Float(cameraController.cameraDistance)
let measurement = Measurement(value: cameraController.cameraDistance, unit: UnitLength.meters)
measurementFormatter.unitStyle = .medium
distanceLabel.text = measurementFormatter.string(from: measurement)
}
private func updateUIForHeadingOffset() {
guard let cameraController = orbitGeoElementCameraController else {
return
}
headingOffsetSlider.value = Float(cameraController.cameraHeadingOffset)
let measurement = Measurement(value: cameraController.cameraHeadingOffset, unit: UnitAngle.degrees)
measurementFormatter.unitStyle = .short
headingOffsetLabel.text = measurementFormatter.string(from: measurement)
}
private func updateUIForPitchOffset() {
guard let cameraController = orbitGeoElementCameraController else {
return
}
pitchOffsetSlider.value = Float(cameraController.cameraPitchOffset)
let measurement = Measurement(value: cameraController.cameraPitchOffset, unit: UnitAngle.degrees)
measurementFormatter.unitStyle = .short
pitchOffsetLabel.text = measurementFormatter.string(from: measurement)
}
// MARK: - Actions
@IBAction private func distanceValueChanged(sender: UISlider) {
// update property
orbitGeoElementCameraController?.cameraDistance = Double(sender.value)
// update label
updateUIForDistance()
}
@IBAction private func headingOffsetValueChanged(sender: UISlider) {
// update property
orbitGeoElementCameraController?.cameraHeadingOffset = Double(sender.value)
// update label
updateUIForHeadingOffset()
}
@IBAction private func pitchOffsetValueChanged(sender: UISlider) {
// update property
orbitGeoElementCameraController?.cameraPitchOffset = Double(sender.value)
// update label
updateUIForPitchOffset()
}
@IBAction private func autoHeadingEnabledValueChanged(sender: UISwitch) {
// update property
orbitGeoElementCameraController?.isAutoHeadingEnabled = sender.isOn
}
@IBAction private func autoPitchEnabledValueChanged(sender: UISwitch) {
// update property
orbitGeoElementCameraController?.isAutoPitchEnabled = sender.isOn
}
@IBAction private func autoRollEnabledValueChanged(sender: UISwitch) {
// update property
orbitGeoElementCameraController?.isAutoRollEnabled = sender.isOn
}
}
| 2028bdb89bab39c2f2304fc728ad9a8c | 37.910345 | 107 | 0.693726 | false | false | false | false |
biohazardlover/NintendoEverything | refs/heads/master | Pods/SwiftSoup/Sources/Whitelist.swift | mit | 1 | //
// Whitelist.swift
// SwiftSoup
//
// Created by Nabil Chatbi on 14/10/16.
// Copyright © 2016 Nabil Chatbi.. All rights reserved.
//
/*
Thank you to Ryan Grove (wonko.com) for the Ruby HTML cleaner http://github.com/rgrove/sanitize/, which inspired
this whitelist configuration, and the initial defaults.
*/
/**
Whitelists define what HTML (elements and attributes) to allow through the cleaner. Everything else is removed.
<p>
Start with one of the defaults:
</p>
<ul>
<li>{@link #none}
<li>{@link #simpleText}
<li>{@link #basic}
<li>{@link #basicWithImages}
<li>{@link #relaxed}
</ul>
<p>
If you need to allow more through (please be careful!), tweak a base whitelist with:
</p>
<ul>
<li>{@link #addTags}
<li>{@link #addAttributes}
<li>{@link #addEnforcedAttribute}
<li>{@link #addProtocols}
</ul>
<p>
You can remove any setting from an existing whitelist with:
</p>
<ul>
<li>{@link #removeTags}
<li>{@link #removeAttributes}
<li>{@link #removeEnforcedAttribute}
<li>{@link #removeProtocols}
</ul>
<p>
The cleaner and these whitelists assume that you want to clean a <code>body</code> fragment of HTML (to add user
supplied HTML into a templated page), and not to clean a full HTML document. If the latter is the case, either wrap the
document HTML around the cleaned body HTML, or create a whitelist that allows <code>html</code> and <code>head</code>
elements as appropriate.
</p>
<p>
If you are going to extend a whitelist, please be very careful. Make sure you understand what attributes may lead to
XSS attack vectors. URL attributes are particularly vulnerable and require careful validation. See
http://ha.ckers.org/xss.html for some XSS attack examples.
</p>
*/
import Foundation
public class Whitelist {
private var tagNames: Set<TagName> // tags allowed, lower case. e.g. [p, br, span]
private var attributes: Dictionary<TagName, Set<AttributeKey>> // tag -> attribute[]. allowed attributes [href] for a tag.
private var enforcedAttributes: Dictionary<TagName, Dictionary<AttributeKey, AttributeValue>> // always set these attribute values
private var protocols: Dictionary<TagName, Dictionary<AttributeKey, Set<Protocol>>> // allowed URL protocols for attributes
private var preserveRelativeLinks: Bool // option to preserve relative links
/**
This whitelist allows only text nodes: all HTML will be stripped.
@return whitelist
*/
public static func none() -> Whitelist {
return Whitelist()
}
/**
This whitelist allows only simple text formatting: <code>b, em, i, strong, u</code>. All other HTML (tags and
attributes) will be removed.
@return whitelist
*/
public static func simpleText()throws ->Whitelist {
return try Whitelist().addTags("b", "em", "i", "strong", "u")
}
/**
<p>
This whitelist allows a fuller range of text nodes: <code>a, b, blockquote, br, cite, code, dd, dl, dt, em, i, li,
ol, p, pre, q, small, span, strike, strong, sub, sup, u, ul</code>, and appropriate attributes.
</p>
<p>
Links (<code>a</code> elements) can point to <code>http, https, ftp, mailto</code>, and have an enforced
<code>rel=nofollow</code> attribute.
</p>
<p>
Does not allow images.
</p>
@return whitelist
*/
public static func basic()throws->Whitelist {
return try Whitelist()
.addTags(
"a", "b", "blockquote", "br", "cite", "code", "dd", "dl", "dt", "em",
"i", "li", "ol", "p", "pre", "q", "small", "span", "strike", "strong", "sub",
"sup", "u", "ul")
.addAttributes("a", "href")
.addAttributes("blockquote", "cite")
.addAttributes("q", "cite")
.addProtocols("a", "href", "ftp", "http", "https", "mailto")
.addProtocols("blockquote", "cite", "http", "https")
.addProtocols("cite", "cite", "http", "https")
.addEnforcedAttribute("a", "rel", "nofollow")
}
/**
This whitelist allows the same text tags as {@link #basic}, and also allows <code>img</code> tags, with appropriate
attributes, with <code>src</code> pointing to <code>http</code> or <code>https</code>.
@return whitelist
*/
public static func basicWithImages()throws->Whitelist {
return try basic()
.addTags("img")
.addAttributes("img", "align", "alt", "height", "src", "title", "width")
.addProtocols("img", "src", "http", "https")
}
/**
This whitelist allows a full range of text and structural body HTML: <code>a, b, blockquote, br, caption, cite,
code, col, colgroup, dd, div, dl, dt, em, h1, h2, h3, h4, h5, h6, i, img, li, ol, p, pre, q, small, span, strike, strong, sub,
sup, table, tbody, td, tfoot, th, thead, tr, u, ul</code>
<p>
Links do not have an enforced <code>rel=nofollow</code> attribute, but you can add that if desired.
</p>
@return whitelist
*/
public static func relaxed()throws->Whitelist {
return try Whitelist()
.addTags(
"a", "b", "blockquote", "br", "caption", "cite", "code", "col",
"colgroup", "dd", "div", "dl", "dt", "em", "h1", "h2", "h3", "h4", "h5", "h6",
"i", "img", "li", "ol", "p", "pre", "q", "small", "span", "strike", "strong",
"sub", "sup", "table", "tbody", "td", "tfoot", "th", "thead", "tr", "u",
"ul")
.addAttributes("a", "href", "title")
.addAttributes("blockquote", "cite")
.addAttributes("col", "span", "width")
.addAttributes("colgroup", "span", "width")
.addAttributes("img", "align", "alt", "height", "src", "title", "width")
.addAttributes("ol", "start", "type")
.addAttributes("q", "cite")
.addAttributes("table", "summary", "width")
.addAttributes("td", "abbr", "axis", "colspan", "rowspan", "width")
.addAttributes(
"th", "abbr", "axis", "colspan", "rowspan", "scope",
"width")
.addAttributes("ul", "type")
.addProtocols("a", "href", "ftp", "http", "https", "mailto")
.addProtocols("blockquote", "cite", "http", "https")
.addProtocols("cite", "cite", "http", "https")
.addProtocols("img", "src", "http", "https")
.addProtocols("q", "cite", "http", "https")
}
/**
Create a new, empty whitelist. Generally it will be better to start with a default prepared whitelist instead.
@see #basic()
@see #basicWithImages()
@see #simpleText()
@see #relaxed()
*/
init() {
tagNames = Set<TagName>()
attributes = Dictionary<TagName, Set<AttributeKey>>()
enforcedAttributes = Dictionary<TagName, Dictionary<AttributeKey, AttributeValue>>()
protocols = Dictionary<TagName, Dictionary<AttributeKey, Set<Protocol>>>()
preserveRelativeLinks = false
}
/**
Add a list of allowed elements to a whitelist. (If a tag is not allowed, it will be removed from the HTML.)
@param tags tag names to allow
@return this (for chaining)
*/
@discardableResult
open func addTags(_ tags: String...)throws ->Whitelist {
for tagName in tags {
try Validate.notEmpty(string: tagName)
tagNames.insert(TagName.valueOf(tagName))
}
return self
}
/**
Remove a list of allowed elements from a whitelist. (If a tag is not allowed, it will be removed from the HTML.)
@param tags tag names to disallow
@return this (for chaining)
*/
@discardableResult
open func removeTags(_ tags: String...)throws ->Whitelist {
try Validate.notNull(obj:tags)
for tag in tags {
try Validate.notEmpty(string: tag)
let tagName: TagName = TagName.valueOf(tag)
if(tagNames.contains(tagName)) { // Only look in sub-maps if tag was allowed
tagNames.remove(tagName)
attributes.removeValue(forKey: tagName)
enforcedAttributes.removeValue(forKey: tagName)
protocols.removeValue(forKey: tagName)
}
}
return self
}
/**
Add a list of allowed attributes to a tag. (If an attribute is not allowed on an element, it will be removed.)
<p>
E.g.: <code>addAttributes("a", "href", "class")</code> allows <code>href</code> and <code>class</code> attributes
on <code>a</code> tags.
</p>
<p>
To make an attribute valid for <b>all tags</b>, use the pseudo tag <code>:all</code>, e.g.
<code>addAttributes(":all", "class")</code>.
</p>
@param tag The tag the attributes are for. The tag will be added to the allowed tag list if necessary.
@param keys List of valid attributes for the tag
@return this (for chaining)
*/
@discardableResult
open func addAttributes(_ tag: String, _ keys: String...)throws->Whitelist {
try Validate.notEmpty(string: tag)
try Validate.isTrue(val: keys.count > 0, msg: "No attributes supplied.")
let tagName = TagName.valueOf(tag)
if (!tagNames.contains(tagName)) {
tagNames.insert(tagName)
}
var attributeSet = Set<AttributeKey>()
for key in keys {
try Validate.notEmpty(string: key)
attributeSet.insert(AttributeKey.valueOf(key))
}
if var currentSet = attributes[tagName] {
for at in attributeSet {
currentSet.insert(at)
}
attributes[tagName] = currentSet
} else {
attributes[tagName] = attributeSet
}
return self
}
/**
Remove a list of allowed attributes from a tag. (If an attribute is not allowed on an element, it will be removed.)
<p>
E.g.: <code>removeAttributes("a", "href", "class")</code> disallows <code>href</code> and <code>class</code>
attributes on <code>a</code> tags.
</p>
<p>
To make an attribute invalid for <b>all tags</b>, use the pseudo tag <code>:all</code>, e.g.
<code>removeAttributes(":all", "class")</code>.
</p>
@param tag The tag the attributes are for.
@param keys List of invalid attributes for the tag
@return this (for chaining)
*/
@discardableResult
open func removeAttributes(_ tag: String, _ keys: String...)throws->Whitelist {
try Validate.notEmpty(string: tag)
try Validate.isTrue(val: keys.count > 0, msg: "No attributes supplied.")
let tagName: TagName = TagName.valueOf(tag)
var attributeSet = Set<AttributeKey>()
for key in keys {
try Validate.notEmpty(string: key)
attributeSet.insert(AttributeKey.valueOf(key))
}
if(tagNames.contains(tagName)) { // Only look in sub-maps if tag was allowed
if var currentSet = attributes[tagName] {
for l in attributeSet {
currentSet.remove(l)
}
attributes[tagName] = currentSet
if(currentSet.isEmpty) { // Remove tag from attribute map if no attributes are allowed for tag
attributes.removeValue(forKey: tagName)
}
}
}
if(tag == ":all") { // Attribute needs to be removed from all individually set tags
for name in attributes.keys {
var currentSet: Set<AttributeKey> = attributes[name]!
for l in attributeSet {
currentSet.remove(l)
}
attributes[name] = currentSet
if(currentSet.isEmpty) { // Remove tag from attribute map if no attributes are allowed for tag
attributes.removeValue(forKey: name)
}
}
}
return self
}
/**
Add an enforced attribute to a tag. An enforced attribute will always be added to the element. If the element
already has the attribute set, it will be overridden.
<p>
E.g.: <code>addEnforcedAttribute("a", "rel", "nofollow")</code> will make all <code>a</code> tags output as
<code><a href="..." rel="nofollow"></code>
</p>
@param tag The tag the enforced attribute is for. The tag will be added to the allowed tag list if necessary.
@param key The attribute key
@param value The enforced attribute value
@return this (for chaining)
*/
@discardableResult
open func addEnforcedAttribute(_ tag: String, _ key: String, _ value: String)throws->Whitelist {
try Validate.notEmpty(string: tag)
try Validate.notEmpty(string: key)
try Validate.notEmpty(string: value)
let tagName: TagName = TagName.valueOf(tag)
if (!tagNames.contains(tagName)) {
tagNames.insert(tagName)
}
let attrKey: AttributeKey = AttributeKey.valueOf(key)
let attrVal: AttributeValue = AttributeValue.valueOf(value)
if (enforcedAttributes[tagName] != nil) {
enforcedAttributes[tagName]?[attrKey] = attrVal
} else {
var attrMap: Dictionary<AttributeKey, AttributeValue> = Dictionary<AttributeKey, AttributeValue>()
attrMap[attrKey] = attrVal
enforcedAttributes[tagName] = attrMap
}
return self
}
/**
Remove a previously configured enforced attribute from a tag.
@param tag The tag the enforced attribute is for.
@param key The attribute key
@return this (for chaining)
*/
@discardableResult
open func removeEnforcedAttribute(_ tag: String, _ key: String)throws->Whitelist {
try Validate.notEmpty(string: tag)
try Validate.notEmpty(string: key)
let tagName: TagName = TagName.valueOf(tag)
if(tagNames.contains(tagName) && (enforcedAttributes[tagName] != nil)) {
let attrKey: AttributeKey = AttributeKey.valueOf(key)
var attrMap: Dictionary<AttributeKey, AttributeValue> = enforcedAttributes[tagName]!
attrMap.removeValue(forKey: attrKey)
enforcedAttributes[tagName] = attrMap
if(attrMap.isEmpty) { // Remove tag from enforced attribute map if no enforced attributes are present
enforcedAttributes.removeValue(forKey: tagName)
}
}
return self
}
/**
* Configure this Whitelist to preserve relative links in an element's URL attribute, or convert them to absolute
* links. By default, this is <b>false</b>: URLs will be made absolute (e.g. start with an allowed protocol, like
* e.g. {@code http://}.
* <p>
* Note that when handling relative links, the input document must have an appropriate {@code base URI} set when
* parsing, so that the link's protocol can be confirmed. Regardless of the setting of the {@code preserve relative
* links} option, the link must be resolvable against the base URI to an allowed protocol; otherwise the attribute
* will be removed.
* </p>
*
* @param preserve {@code true} to allow relative links, {@code false} (default) to deny
* @return this Whitelist, for chaining.
* @see #addProtocols
*/
@discardableResult
open func preserveRelativeLinks(_ preserve: Bool) -> Whitelist {
preserveRelativeLinks = preserve
return self
}
/**
Add allowed URL protocols for an element's URL attribute. This restricts the possible values of the attribute to
URLs with the defined protocol.
<p>
E.g.: <code>addProtocols("a", "href", "ftp", "http", "https")</code>
</p>
<p>
To allow a link to an in-page URL anchor (i.e. <code><a href="#anchor"></code>, add a <code>#</code>:<br>
E.g.: <code>addProtocols("a", "href", "#")</code>
</p>
@param tag Tag the URL protocol is for
@param key Attribute key
@param protocols List of valid protocols
@return this, for chaining
*/
@discardableResult
open func addProtocols(_ tag: String, _ key: String, _ protocols: String...)throws->Whitelist {
try Validate.notEmpty(string: tag)
try Validate.notEmpty(string: key)
let tagName: TagName = TagName.valueOf(tag)
let attrKey: AttributeKey = AttributeKey.valueOf(key)
var attrMap: Dictionary<AttributeKey, Set<Protocol>>
var protSet: Set<Protocol>
if (self.protocols[tagName] != nil) {
attrMap = self.protocols[tagName]!
} else {
attrMap = Dictionary<AttributeKey, Set<Protocol>>()
self.protocols[tagName] = attrMap
}
if (attrMap[attrKey] != nil) {
protSet = attrMap[attrKey]!
} else {
protSet = Set<Protocol>()
attrMap[attrKey] = protSet
self.protocols[tagName] = attrMap
}
for ptl in protocols {
try Validate.notEmpty(string: ptl)
let prot: Protocol = Protocol.valueOf(ptl)
protSet.insert(prot)
}
attrMap[attrKey] = protSet
self.protocols[tagName] = attrMap
return self
}
/**
Remove allowed URL protocols for an element's URL attribute.
<p>
E.g.: <code>removeProtocols("a", "href", "ftp")</code>
</p>
@param tag Tag the URL protocol is for
@param key Attribute key
@param protocols List of invalid protocols
@return this, for chaining
*/
@discardableResult
open func removeProtocols(_ tag: String, _ key: String, _ protocols: String...)throws->Whitelist {
try Validate.notEmpty(string: tag)
try Validate.notEmpty(string: key)
let tagName: TagName = TagName.valueOf(tag)
let attrKey: AttributeKey = AttributeKey.valueOf(key)
if(self.protocols[tagName] != nil) {
var attrMap: Dictionary<AttributeKey, Set<Protocol>> = self.protocols[tagName]!
if(attrMap[attrKey] != nil) {
var protSet: Set<Protocol> = attrMap[attrKey]!
for ptl in protocols {
try Validate.notEmpty(string: ptl)
let prot: Protocol = Protocol.valueOf(ptl)
protSet.remove(prot)
}
attrMap[attrKey] = protSet
if(protSet.isEmpty) { // Remove protocol set if empty
attrMap.removeValue(forKey: attrKey)
if(attrMap.isEmpty) { // Remove entry for tag if empty
self.protocols.removeValue(forKey: tagName)
}
}
}
self.protocols[tagName] = attrMap
}
return self
}
/**
* Test if the supplied tag is allowed by this whitelist
* @param tag test tag
* @return true if allowed
*/
public func isSafeTag(_ tag: String) -> Bool {
return tagNames.contains(TagName.valueOf(tag))
}
/**
* Test if the supplied attribute is allowed by this whitelist for this tag
* @param tagName tag to consider allowing the attribute in
* @param el element under test, to confirm protocol
* @param attr attribute under test
* @return true if allowed
*/
public func isSafeAttribute(_ tagName: String, _ el: Element, _ attr: Attribute)throws -> Bool {
let tag: TagName = TagName.valueOf(tagName)
let key: AttributeKey = AttributeKey.valueOf(attr.getKey())
if (attributes[tag] != nil) {
if (attributes[tag]?.contains(key))! {
if (protocols[tag] != nil) {
let attrProts: Dictionary<AttributeKey, Set<Protocol>> = protocols[tag]!
// ok if not defined protocol; otherwise test
return try (attrProts[key] == nil) || testValidProtocol(el, attr, attrProts[key]!)
} else { // attribute found, no protocols defined, so OK
return true
}
}
}
// no attributes defined for tag, try :all tag
return try !(tagName == ":all") && isSafeAttribute(":all", el, attr)
}
private func testValidProtocol(_ el: Element, _ attr: Attribute, _ protocols: Set<Protocol>)throws->Bool {
// try to resolve relative urls to abs, and optionally update the attribute so output html has abs.
// rels without a baseuri get removed
var value: String = try el.absUrl(attr.getKey())
if (value.count == 0) {
value = attr.getValue()
}// if it could not be made abs, run as-is to allow custom unknown protocols
if (!preserveRelativeLinks) {
attr.setValue(value: value)
}
for ptl in protocols {
var prot: String = ptl.toString()
if (prot=="#") { // allows anchor links
if (isValidAnchor(value)) {
return true
} else {
continue
}
}
prot += ":"
if (value.lowercased().hasPrefix(prot)) {
return true
}
}
return false
}
private func isValidAnchor(_ value: String) -> Bool {
return value.startsWith("#") && !(Pattern(".*\\s.*").matcher(in: value).count > 0)
}
public func getEnforcedAttributes(_ tagName: String)throws->Attributes {
let attrs: Attributes = Attributes()
let tag: TagName = TagName.valueOf(tagName)
if let keyVals: Dictionary<AttributeKey, AttributeValue> = enforcedAttributes[tag] {
for entry in keyVals {
try attrs.put(entry.key.toString(), entry.value.toString())
}
}
return attrs
}
}
// named types for config. All just hold strings, but here for my sanity.
open class TagName: TypedValue {
override init(_ value: String) {
super.init(value)
}
static func valueOf(_ value: String) -> TagName {
return TagName(value)
}
}
open class AttributeKey: TypedValue {
override init(_ value: String) {
super.init(value)
}
static func valueOf(_ value: String) -> AttributeKey {
return AttributeKey(value)
}
}
open class AttributeValue: TypedValue {
override init(_ value: String) {
super.init(value)
}
static func valueOf(_ value: String) -> AttributeValue {
return AttributeValue(value)
}
}
open class Protocol: TypedValue {
override init(_ value: String) {
super.init(value)
}
static func valueOf(_ value: String) -> Protocol {
return Protocol(value)
}
}
open class TypedValue {
fileprivate let value: String
init(_ value: String) {
self.value = value
}
public func toString() -> String {
return value
}
}
extension TypedValue: Hashable {
public var hashValue: Int {
return value.hashValue
}
}
public func == (lhs: TypedValue, rhs: TypedValue) -> Bool {
if(lhs === rhs) {return true}
return lhs.value == rhs.value
}
| 3093caa1798b09f5f5a7ecfabcfc56a0 | 35.664615 | 134 | 0.581193 | false | false | false | false |
naokits/my-programming-marathon | refs/heads/master | IBDesignableDemo/IBDesignableDemo/CustomButton.swift | mit | 1 | //
// CustomButton.swift
// IBDesignableDemo
//
// Created by Naoki Tsutsui on 1/29/16.
// Copyright © 2016 Naoki Tsutsui. All rights reserved.
//
import UIKit
@IBDesignable
class CustomButton: UIButton {
@IBInspectable var textColor: UIColor?
@IBInspectable var cornerRadius: CGFloat = 0 {
didSet {
layer.cornerRadius = cornerRadius
}
}
@IBInspectable var borderWidth: CGFloat = 0 {
didSet {
layer.borderWidth = borderWidth
}
}
@IBInspectable var borderColor: UIColor = UIColor.clearColor() {
didSet {
layer.borderColor = borderColor.CGColor
}
}
}
| 96d1c028a5bfcacb833f317e5205e920 | 18.685714 | 68 | 0.599419 | false | false | false | false |
Avtolic/ACAlertController | refs/heads/master | ACAlertController/ACAlertControllerCore.swift | mit | 1 | //
// ACAlertControllerCore.swift
// ACAlertControllerDemo
//
// Created by Yury on 21/09/16.
// Copyright © 2016 Avtolic. All rights reserved.
//
import Foundation
import UIKit
public var alertLinesColor = UIColor(red:220/256, green:220/256, blue:224/256, alpha:1.0)
public protocol ACAlertListViewProtocol {
var contentHeight: CGFloat { get }
var view: UIView { get }
}
public protocol ACAlertListViewProvider {
func set(alertView: UIView, itemsView: UIView?, actionsView: UIView?, callBlock: @escaping (ACAlertActionProtocolBase) -> Void) -> Void
func alertView(items : [ACAlertItemProtocol], width: CGFloat) -> ACAlertListViewProtocol
func alertView(actions : [ACAlertActionProtocolBase], width: CGFloat) -> ACAlertListViewProtocol
}
open class StackViewProvider: NSObject, ACAlertListViewProvider, UIGestureRecognizerDelegate {
open func alertView(items: [ACAlertItemProtocol], width: CGFloat) -> ACAlertListViewProtocol {
let views = items.map { $0.alertItemView }
return ACStackAlertListView(views: views, width: width)
}
open func alertView(actions: [ACAlertActionProtocolBase], width: CGFloat) -> ACAlertListViewProtocol {
buttonsAndActions = actions.map { (buttonView(action: $0), $0) }
let views = buttonsAndActions.map { $0.0 }
if views.count == 2 {
let button1 = views[0]
let button2 = views[1]
button1.layoutIfNeeded()
button2.layoutIfNeeded()
let maxReducedWidth = (width - 1) / 2
if button1.bounds.width < maxReducedWidth && button2.bounds.width < maxReducedWidth
{
Layout.set(width: maxReducedWidth, view: button1)
Layout.set(width: maxReducedWidth, view: button2)
return ACStackAlertListView3(views: [button1, separatorView2(), button2], width: width)
}
}
let views2 = views.flatMap { [$0, separatorView()] }.dropLast()
return ACStackAlertListView2(views: Array(views2), width: width)
}
open var actionsView: UIView!
open var callBlock:((ACAlertActionProtocolBase) -> Void)!
open func set(alertView: UIView, itemsView: UIView?, actionsView: UIView?, callBlock:@escaping (ACAlertActionProtocolBase) -> Void) -> Void {
self.actionsView = actionsView
self.callBlock = callBlock
let recognizer = UILongPressGestureRecognizer(target: self, action: #selector(handleRecognizer))
recognizer.minimumPressDuration = 0.0
recognizer.allowableMovement = CGFloat.greatestFiniteMagnitude
recognizer.cancelsTouchesInView = false
recognizer.delegate = self
if let superRecognizers = actionsView?.gestureRecognizers {
for r in superRecognizers {
recognizer.require(toFail: r)
}
}
if let superRecognizers = itemsView?.gestureRecognizers {
for r in superRecognizers {
recognizer.require(toFail: r)
}
}
alertView.addGestureRecognizer(recognizer)
}
open var buttonsAndActions: [(UIView, ACAlertActionProtocolBase)] = []
open var buttonHighlightColor = UIColor(white: 0.9, alpha: 1)
// MARK: Touch recogniser
@objc open func handleRecognizer(_ recognizer: UILongPressGestureRecognizer) {
let point = recognizer.location(in: actionsView)
for (button, action) in buttonsAndActions
{
let isActive = button.frame.contains(point) && action.enabled
let isHighlighted = isActive && (recognizer.state == .began || recognizer.state == .changed)
button.backgroundColor = isHighlighted ? buttonHighlightColor : UIColor.clear
action.highlight(isHighlighted)
if isActive && recognizer.state == .ended {
callBlock(action)
}
}
}
open var buttonsMargins = UIEdgeInsets(top: 4, left: 8, bottom: 4, right: 8) // Applied to buttons
open var defaultButtonHeight: CGFloat = 45
open func buttonView(action: ACAlertActionProtocolBase) -> UIView {
let actionView = action.alertView
actionView.translatesAutoresizingMaskIntoConstraints = false
actionView.isUserInteractionEnabled = false
let button = UIView()
button.layoutMargins = buttonsMargins
button.addSubview(actionView)
button.translatesAutoresizingMaskIntoConstraints = false
Layout.setInCenter(view: button, subview: actionView, margins: true)
Layout.setOptional(height: defaultButtonHeight, view: button)
return button
}
open func separatorView() -> UIView {
let view = UIView()
view.backgroundColor = alertLinesColor
view.translatesAutoresizingMaskIntoConstraints = false
Layout.set(height: 0.5, view: view)
return view
}
open func separatorView2() -> UIView {
let view = UIView()
view.backgroundColor = alertLinesColor
view.translatesAutoresizingMaskIntoConstraints = false
Layout.set(width: 0.5, view: view)
return view
}
}
open class ACStackAlertListView: ACAlertListViewProtocol {
public var view: UIView { return scrollView }
public var contentHeight: CGFloat
open let stackView: UIStackView
open let scrollView = UIScrollView()
open var margins = UIEdgeInsets(top: 10, left: 5, bottom: 10, right: 5)
public init(views: [UIView], width: CGFloat) {
stackView = UIStackView(arrangedSubviews: views )
stackView.axis = .vertical
stackView.alignment = .center
stackView.distribution = .equalSpacing
stackView.spacing = 0
stackView.translatesAutoresizingMaskIntoConstraints = false
scrollView.translatesAutoresizingMaskIntoConstraints = false
scrollView.addSubview(stackView)
Layout.setEqual(view:scrollView, subview: stackView, margins: false)
Layout.set(width: width, view: stackView)
stackView.layoutMargins = margins
stackView.isLayoutMarginsRelativeArrangement = true
contentHeight = stackView.systemLayoutSizeFitting(UILayoutFittingCompressedSize).height
}
}
open class ACStackAlertListView2: ACAlertListViewProtocol {
open var view: UIView { return scrollView }
open var contentHeight: CGFloat
open let stackView: UIStackView
open let scrollView = UIScrollView()
open var margins = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
public init(views: [UIView], width: CGFloat) {
stackView = UIStackView(arrangedSubviews: views )
stackView.axis = .vertical
stackView.alignment = .fill
stackView.distribution = .equalSpacing
stackView.spacing = 0
stackView.translatesAutoresizingMaskIntoConstraints = false
scrollView.translatesAutoresizingMaskIntoConstraints = false
scrollView.addSubview(stackView)
Layout.setEqual(view:scrollView, subview: stackView, margins: false)
Layout.set(width: width, view: stackView)
stackView.layoutMargins = margins
stackView.isLayoutMarginsRelativeArrangement = true
contentHeight = stackView.systemLayoutSizeFitting(UILayoutFittingCompressedSize).height
}
}
open class ACStackAlertListView3: ACAlertListViewProtocol {
open var view: UIView { return scrollView }
open var contentHeight: CGFloat
open let stackView: UIStackView
open let scrollView = UIScrollView()
open var margins = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
public init(views: [UIView], width: CGFloat) {
stackView = UIStackView(arrangedSubviews: views )
stackView.axis = .horizontal
stackView.alignment = .fill
stackView.distribution = .equalSpacing
stackView.spacing = 0
stackView.translatesAutoresizingMaskIntoConstraints = false
scrollView.translatesAutoresizingMaskIntoConstraints = false
scrollView.addSubview(stackView)
Layout.setEqual(view:scrollView, subview: stackView, margins: false)
Layout.set(width: width, view: stackView)
stackView.layoutMargins = margins
stackView.isLayoutMarginsRelativeArrangement = true
contentHeight = stackView.systemLayoutSizeFitting(UILayoutFittingCompressedSize).height
}
}
open class ACAlertController : UIViewController{
fileprivate(set) open var items: [ACAlertItemProtocol] = []
fileprivate(set) open var actions: [ACAlertActionProtocolBase] = []
// open var items: [ACAlertItemProtocol] { return items.map{ $0.0 } }
// fileprivate(set) open var actions: [ACAlertActionProtocol] = []
open var backgroundColor = UIColor(white: 250/256, alpha: 1)
open var viewMargins = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)//UIEdgeInsets(top: 15, bottom: 15)
// open var defaultItemsMargins = UIEdgeInsets(top: 2, left: 0, bottom: 2, right: 0) // Applied to items
// open var itemsMargins = UIEdgeInsets(top: 4, bottom: 4)
// open var actionsMargins = UIEdgeInsets(top: 4, bottom: 4)
open var alertWidth: CGFloat = 270
open var cornerRadius: CGFloat = 16
open var separatorHeight: CGFloat = 0.5
open var alertListsProvider: ACAlertListViewProvider = StackViewProvider()
open var itemsAlertList: ACAlertListViewProtocol?
open var actionsAlertList: ACAlertListViewProtocol?
open var separatorView: UIView = {
let view = UIView()
view.backgroundColor = alertLinesColor
view.translatesAutoresizingMaskIntoConstraints = false
return view
}()
// MARK: Public methods
public init() {
super.init(nibName: nil, bundle: nil)
modalPresentationStyle = .overFullScreen
transitioningDelegate = self
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
open func addItem(_ item: ACAlertItemProtocol) {
guard isBeingPresented == false else {
print("ACAlertController could not be modified if it is already presented")
return
}
items.append(item)
}
open func addAction(_ action: ACAlertActionProtocolBase) {
guard isBeingPresented == false else {
print("ACAlertController could not be modified if it is already presented")
return
}
actions.append(action)
}
override open func loadView() {
view = UIView()
view.backgroundColor = backgroundColor
view.layer.cornerRadius = cornerRadius
view.translatesAutoresizingMaskIntoConstraints = false
view.layer.masksToBounds = true
Layout.set(width: alertWidth, view: view)
// Is needed because of layoutMargins http://stackoverflow.com/questions/27421469/setting-layoutmargins-of-uiview-doesnt-work
let contentView = UIView()
view.addSubview(contentView)
contentView.layoutMargins = viewMargins
contentView.translatesAutoresizingMaskIntoConstraints = false
Layout.setEqual(view: view, subview: contentView, margins: false)
setContentView(view: contentView)
}
open func setContentView(view: UIView) {
if hasItems {
itemsAlertList = alertListsProvider.alertView(items: items, width: alertWidth - viewMargins.leftPlusRight)
}
if hasActions {
actionsAlertList = alertListsProvider.alertView(actions: actions, width: alertWidth - viewMargins.leftPlusRight)
}
let (height1, height2) = elementsHeights()
if let h = height1, let v = itemsAlertList?.view {
Layout.set(height: h, view: v)
}
if let h = height2, let v = actionsAlertList?.view {
Layout.set(height: h, view: v)
}
if let topSubview = itemsAlertList?.view ?? actionsAlertList?.view {
view.addSubview(topSubview)
Layout.setEqualTop(view: view, subview: topSubview, margins: true)
Layout.setEqualLeftAndRight(view: view, subview: topSubview, margins: true)
if let bottomSubview = actionsAlertList?.view, bottomSubview !== topSubview {
view.addSubview(separatorView)
Layout.setBottomToTop(topView: topSubview, bottomView: separatorView)
Layout.setEqualLeftAndRight(view: view, subview: separatorView, margins: true)
Layout.set(height: separatorHeight, view: separatorView)
view.addSubview(bottomSubview)
Layout.setBottomToTop(topView: separatorView, bottomView: bottomSubview)
Layout.setEqualLeftAndRight(view: view, subview: bottomSubview, margins: true)
Layout.setEqualBottom(view: view, subview: bottomSubview, margins: true)
} else {
Layout.setEqualBottom(view: view, subview: topSubview, margins: true)
}
}
alertListsProvider.set(alertView: view, itemsView: itemsAlertList?.view, actionsView: actionsAlertList?.view) { (action) in
self.presentingViewController?.dismiss(animated: true, completion: {
DispatchQueue.main.async(execute: {
action.call()
})
})
}
}
open var hasItems: Bool { return items.count > 0 }
open var hasActions: Bool { return actions.count > 0 }
open var maxViewHeight: CGFloat { return UIScreen.main.bounds.height - 80 }
open func elementsHeights() -> (itemsHeight: CGFloat?, actionsHeight: CGFloat?) {
let max = maxViewHeight - viewMargins.topPlusBottom
switch (itemsAlertList?.contentHeight, actionsAlertList?.contentHeight) {
case (nil, nil):
return (nil, nil)
case (.some(let height1), nil):
return (min(height1, max), nil)
case (nil, .some(let height2)):
return (nil, min(height2, max))
case (.some(let height1), .some(let height2)):
let max2 = max - separatorHeight
if max2 >= height1 + height2 {
return (height1, height2)
} else if height1 < max2 * 0.75 {
return (height1, max2 - height1)
} else if height2 < max2 * 0.75 {
return (max2 - height2, height2)
}
return (max2 / 2, max2 / 2)
}
}
}
extension ACAlertController: UIViewControllerTransitioningDelegate {
public func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
return ACAlertControllerAnimatedTransitioningBase(appearing: true)
}
public func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
return ACAlertControllerAnimatedTransitioningBase(appearing: false)
}
}
open class Layout {
open static var nonMandatoryConstraintPriority: UILayoutPriority = 700 // Item's and action's constraints that could conflict with ACAlertController constraints should have priorities in [nonMandatoryConstraintPriority ..< 1000] range.
open class func set(width: CGFloat, view: UIView) {
NSLayoutConstraint(item: view, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: width).isActive = true
}
open class func set(height: CGFloat, view: UIView) {
NSLayoutConstraint(item: view, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: height).isActive = true
}
open class func setOptional(height: CGFloat, view: UIView) {
let constraint = NSLayoutConstraint(item: view, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: height)
constraint.priority = nonMandatoryConstraintPriority
constraint.isActive = true
}
open class func setOptional(width: CGFloat, view: UIView) {
let constraint = NSLayoutConstraint(item: view, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: width)
constraint.priority = nonMandatoryConstraintPriority
constraint.isActive = true
}
open class func setInCenter(view: UIView, subview: UIView, margins: Bool) {
NSLayoutConstraint(item: view, attribute: margins ? .leadingMargin : .leading, relatedBy: .lessThanOrEqual, toItem: subview, attribute: .leading, multiplier: 1, constant: 0).isActive = true
NSLayoutConstraint(item: view, attribute: margins ? .trailingMargin : .trailing, relatedBy: .greaterThanOrEqual, toItem: subview, attribute: .trailing, multiplier: 1, constant: 0).isActive = true
NSLayoutConstraint(item: view, attribute: margins ? .topMargin : .top, relatedBy: .lessThanOrEqual, toItem: subview, attribute: .top, multiplier: 1, constant: 0).isActive = true
NSLayoutConstraint(item: view, attribute: margins ? .bottomMargin : .bottom, relatedBy: .greaterThanOrEqual, toItem: subview, attribute: .bottom, multiplier: 1, constant: 0).isActive = true
let centerX = NSLayoutConstraint(item: view, attribute: margins ? .centerXWithinMargins : .centerX, relatedBy: .equal, toItem: subview, attribute: .centerX, multiplier: 1, constant: 0)
centerX.priority = nonMandatoryConstraintPriority
centerX.isActive = true
let centerY = NSLayoutConstraint(item: view, attribute: margins ? .centerYWithinMargins : .centerY, relatedBy: .equal, toItem: subview, attribute: .centerY, multiplier: 1, constant: 0)
centerY.priority = nonMandatoryConstraintPriority
centerY.isActive = true
}
open class func setEqual(view: UIView, subview: UIView, margins: Bool) {
NSLayoutConstraint(item: view, attribute: margins ? .leftMargin : .left, relatedBy: .equal, toItem: subview, attribute: .left, multiplier: 1, constant: 0).isActive = true
NSLayoutConstraint(item: view, attribute: margins ? .rightMargin : .right, relatedBy: .equal, toItem: subview, attribute: .right, multiplier: 1, constant: 0).isActive = true
NSLayoutConstraint(item: view, attribute: margins ? .topMargin : .top, relatedBy: .equal, toItem: subview, attribute: .top, multiplier: 1, constant: 0).isActive = true
NSLayoutConstraint(item: view, attribute: margins ? .bottomMargin: .bottom, relatedBy: .equal, toItem: subview, attribute: .bottom, multiplier: 1, constant: 0).isActive = true
}
open class func setEqualLeftAndRight(view: UIView, subview: UIView, margins: Bool) {
NSLayoutConstraint(item: view, attribute: margins ? .leftMargin : .left, relatedBy: .equal, toItem: subview, attribute: .left, multiplier: 1, constant: 0).isActive = true
NSLayoutConstraint(item: view, attribute: margins ? .rightMargin : .right, relatedBy: .equal, toItem: subview, attribute: .right, multiplier: 1, constant: 0).isActive = true
}
open class func setEqualTop(view: UIView, subview: UIView, margins: Bool) {
NSLayoutConstraint(item: view, attribute: margins ? .topMargin : .top, relatedBy: .equal, toItem: subview, attribute: .top, multiplier: 1, constant: 0).isActive = true
}
open class func setEqualBottom(view: UIView, subview: UIView, margins: Bool) {
NSLayoutConstraint(item: view, attribute: margins ? .bottomMargin : .bottom, relatedBy: .equal, toItem: subview, attribute: .bottom, multiplier: 1, constant: 0).isActive = true
}
open class func setBottomToTop(topView: UIView, bottomView: UIView) {
NSLayoutConstraint(item: topView, attribute: .bottom, relatedBy: .equal, toItem: bottomView, attribute: .top, multiplier: 1, constant: 0).isActive = true
}
}
public extension UIEdgeInsets {
public var topPlusBottom: CGFloat { return top + bottom }
public var leftPlusRight: CGFloat { return left + right }
public init(top: CGFloat, bottom: CGFloat) {
self.init(top: top, left: 0, bottom: bottom, right: 0)
}
}
| b862ddb198a9d421db50b7d5a0223eaf | 41.456212 | 239 | 0.659359 | false | false | false | false |
manavgabhawala/UberSDK | refs/heads/master | Shared/UberUserAuthenticator.swift | apache-2.0 | 1 | //
// UberUserAuthenticator.swift
// UberSDK
//
// Created by Manav Gabhawala on 24/07/15.
//
//
import Foundation
internal class UberUserAuthenticator : NSObject
{
private let refreshSemaphore = dispatch_semaphore_create(1)
private var accessToken : String?
private var refreshToken: String?
private var expiration : NSDate?
private var uberOAuthCredentialsLocation : String
private var clientID: String
private var clientSecret : String
internal var redirectURI : String
private var scopes : [UberScopes]
private var completionBlock : UberSuccessBlock?
internal var errorHandler : UberErrorHandler?
internal var viewController : AnyObject!
internal init(clientID: String, clientSecret: String, redirectURI: String, scopes: [UberScopes])
{
self.clientID = clientID
self.clientSecret = clientSecret
self.redirectURI = redirectURI
self.scopes = scopes
if let directory = NSSearchPathForDirectoriesInDomains(.ApplicationSupportDirectory, NSSearchPathDomainMask.UserDomainMask, true).first
{
uberOAuthCredentialsLocation = "\(directory)/Authentication.plist"
let fileManager = NSFileManager()
if !fileManager.fileExistsAtPath(directory)
{
try! fileManager.createDirectoryAtPath(directory, withIntermediateDirectories: true, attributes: nil)
}
if !fileManager.fileExistsAtPath(uberOAuthCredentialsLocation)
{
fileManager.createFileAtPath(uberOAuthCredentialsLocation, contents: nil, attributes: nil)
}
}
else
{
uberOAuthCredentialsLocation = ""
}
if let dictionary = NSDictionary(contentsOfFile: uberOAuthCredentialsLocation)
{
if let accessTok = dictionary.objectForKey("access_token") as? NSData, let encodedAccessToken = String(data: accessTok)
{
accessToken = String(data: NSData(base64EncodedString: encodedAccessToken, options: []))
}
if let refreshTok = dictionary.objectForKey("refresh_token") as? NSData, let encodedRefreshToken = String(data: refreshTok)
{
refreshToken = String(data: NSData(base64EncodedString: encodedRefreshToken, options: []))
}
expiration = dictionary.objectForKey("timeout") as? NSDate
}
}
/// Tests whether authentication has been performed or not.
///
/// - returns: `true` if authentication has been performed else `false`.
internal func authenticated() -> Bool
{
if let _ = accessToken
{
return true
}
return false
}
/// This function adds the bearer access_token to the authorization field if it is available.
///
/// - parameter request: A mutable URL Request which is modified to add the access token to the URL Request if one exists for the user.
///
/// - returns: `true` if the access token was successfully added to the request. `false` otherwise.
internal func addBearerAccessHeader(request: NSMutableURLRequest) -> Bool
{
if let accessToken = requestAccessToken()
{
request.addValue("Bearer \(accessToken)", forHTTPHeaderField: "Authorization")
return true
}
return false
}
private func requestAccessToken(allowsRefresh: Bool = true) -> String?
{
if (accessToken == nil || refreshToken == nil || expiration == nil)
{
return nil
}
if expiration! > NSDate(timeIntervalSinceNow: 0)
{
return accessToken
}
else if allowsRefresh
{
refreshAccessToken()
dispatch_semaphore_wait(refreshSemaphore, DISPATCH_TIME_FOREVER)
return requestAccessToken(false)
}
return nil
}
private func refreshAccessToken()
{
dispatch_semaphore_wait(refreshSemaphore, DISPATCH_TIME_NOW)
let data = "client_id=\(clientID)&client_secret=\(clientSecret)&redirect_uri=\(redirectURI)&grant_type=refresh_token&refresh_token=\(refreshToken)"
let URL = NSURL(string: "https://login.uber.com/oauth/token")!
let request = NSMutableURLRequest(URL: URL)
request.HTTPMethod = "POST"
request.HTTPBody = data.dataUsingEncoding(NSUTF8StringEncoding)
performFetchForAuthData(request.copy() as! NSURLRequest)
}
internal func getAuthTokenForCode(code: String)
{
let data = "code=\(code)&client_id=\(clientID)&client_secret=\(clientSecret)&redirect_uri=\(redirectURI)&grant_type=authorization_code"
let URL = NSURL(string: "https://login.uber.com/oauth/token")!
let request = NSMutableURLRequest(URL: URL)
request.HTTPMethod = HTTPMethod.Post.rawValue
request.HTTPBody = data.dataUsingEncoding(NSUTF8StringEncoding)
performFetchForAuthData(request.copy() as! NSURLRequest)
}
private func performFetchForAuthData(request: NSURLRequest)
{
let session = NSURLSession(configuration: NSURLSessionConfiguration.defaultSessionConfiguration())
let task = session.dataTaskWithRequest(request, completionHandler: {(data, response, error) in
if (error == nil)
{
self.parseAuthDataReceived(data!)
// If we can't acquire it, it returns imeediately and it means that someone is waiting and needs to be signalled.
// If we do acquire it we release it immediately because we don't actually want to hold it for anytime in the future.
dispatch_semaphore_wait(self.refreshSemaphore, DISPATCH_TIME_NOW)
dispatch_semaphore_signal(self.refreshSemaphore)
}
else
{
self.errorHandler?(UberError(JSONData: data, response: response) ?? UberError(error: error, response: response) ?? unknownError)
}
})
task.resume()
}
private func parseAuthDataReceived(authData: NSData)
{
do
{
guard let authDictionary = try NSJSONSerialization.JSONObjectWithData(authData, options: []) as? [NSObject : AnyObject]
else { return }
guard let access = authDictionary["access_token"] as? String,
let refresh = authDictionary["refresh_token"] as? String,
let timeout = authDictionary["expires_in"] as? NSTimeInterval
else { throw NSError(domain: "UberAuthenticationError", code: 1, userInfo: nil) }
accessToken = access
refreshToken = refresh
let time = NSDate(timeInterval: timeout, sinceDate: NSDate(timeIntervalSinceNow: 0))
let encodedAccessToken = accessToken!.dataUsingEncoding(NSUTF8StringEncoding)!.base64EncodedDataWithOptions([])
let encodedRefreshToken = refreshToken!.dataUsingEncoding(NSUTF8StringEncoding)!.base64EncodedDataWithOptions([])
let dictionary : NSDictionary = ["access_token" : encodedAccessToken, "refresh_token" : encodedRefreshToken, "timeout" : time];
dictionary.writeToFile(uberOAuthCredentialsLocation, atomically: true)
completionBlock?()
}
catch let error as NSError
{
errorHandler?(UberError(error: error))
}
catch
{
errorHandler?(UberError(JSONData: authData) ?? unknownError)
}
}
internal func setupOAuth2AccountStore<T: Viewable>(view: T)
{
if let _ = requestAccessToken()
{
completionBlock?()
return
}
var scopesString = scopes.reduce("", combine: { $0.0 + "%20" + $0.1.description })
scopesString = scopesString.substringFromIndex(advance(scopesString.startIndex, 3))
let redirectURL = redirectURI.stringByAddingPercentEncodingWithAllowedCharacters(.URLPasswordAllowedCharacterSet())!
let URL = NSURL(string: "https://login.uber.com/oauth/authorize?response_type=code&client_id=\(clientID)&redirect_uri=\(redirectURL)&scope=\(scopesString)")!
let request = NSURLRequest(URL: URL)
generateCodeForRequest(request, onView: view)
}
internal func setCallbackBlocks(successBlock successBlock: UberSuccessBlock?, errorBlock: UberErrorHandler?)
{
completionBlock = successBlock
errorHandler = errorBlock
}
internal func logout(completionBlock success: UberSuccessBlock?, errorHandler failure: UberErrorHandler?)
{
accessToken = nil
refreshToken = nil
expiration = nil
let fileManager = NSFileManager.defaultManager()
if fileManager.fileExistsAtPath(uberOAuthCredentialsLocation)
{
do
{
try fileManager.removeItemAtPath(uberOAuthCredentialsLocation)
success?()
}
catch let error as NSError
{
failure?(UberError(error: error))
}
catch
{
failure?(unknownError)
}
}
else
{
success?()
}
}
} | 9c6b9b5ad0b97b8925bc5b648bd2a32f | 33.846491 | 159 | 0.743832 | false | false | false | false |
skyfe79/TIL | refs/heads/master | about.iOS/about.Swift/15.Deinitialization.playground/Contents.swift | mit | 1 | /*:
# Deinitialization
* 컴퓨터의 자원이 유한하기 때문에 이 모든 것이 필요한 것이다.
*/
import UIKit
/*:
## How Deinitialization Works
*/
do {
class SomeClass {
deinit {
// perform the deinitialization
}
}
}
/*:
## Deinitializers in Action
*/
do {
class Bank {
static var coinsInBank = 10_000
static func vendCoins(numberOfCoinsRequested: Int) -> Int {
let numberOfCoinsToVend = min(numberOfCoinsRequested, coinsInBank)
coinsInBank -= numberOfCoinsToVend
return numberOfCoinsToVend
}
static func receiveCoins(coins: Int) {
coinsInBank += coins
}
}
class Player {
var coinsInPurse: Int
init(coins: Int) {
coinsInPurse = Bank.vendCoins(coins)
}
func winCoins(coins: Int) {
coinsInPurse += Bank.vendCoins(coins)
}
deinit {
Bank.receiveCoins(coinsInPurse)
}
}
var playerOne: Player? = Player(coins: 100)
print("A new player has joined the game with \(playerOne!.coinsInPurse) coins")
// Prints "A new player has joined the game with 100 coins"
print("There are now \(Bank.coinsInBank) coins left in the bank")
// Prints "There are now 9900 coins left in the bank"
playerOne!.winCoins(2_000)
print("PlayerOne won 2000 coins & now has \(playerOne!.coinsInPurse) coins")
// Prints "PlayerOne won 2000 coins & now has 2100 coins"
print("The bank now only has \(Bank.coinsInBank) coins left")
// Prints "The bank now only has 7900 coins left"
playerOne = nil
print("PlayerOne has left the game")
// Prints "PlayerOne has left the game"
print("The bank now has \(Bank.coinsInBank) coins")
// Prints "The bank now has 10000 coins"
} | 54262aee29d125149710f5484cddb1e4 | 27.3125 | 83 | 0.611264 | false | false | false | false |
sessionm/ios-smp-example | refs/heads/master | Offers/Reward Store/RewardStoreTableViewController.swift | mit | 1 | //
// RewardStoreTableViewController.swift
// Offers
//
// Copyright © 2018 SessionM. All rights reserved.
//
import SessionMOffersKit
import UIKit
class RewardStoreTableViewCell: UITableViewCell {
@IBOutlet weak var header: UILabel!
@IBOutlet weak var validDates: UILabel!
@IBOutlet weak var points: UILabel!
@IBOutlet weak var img: UIImageView!
}
class RewardStoreTableViewController: UITableViewController {
override func viewDidLoad() {
super.viewDidLoad()
NotificationCenter.default.addObserver(self, selector: #selector(updateToolbar), name: NSNotification.Name(updatedUserNotification), object: nil)
self.tableView.rowHeight = UITableViewAutomaticDimension
self.tableView.estimatedRowHeight = 200;
self.tableView.contentInset = UIEdgeInsetsMake(64,0,0,0); // Put it below the navigation controller
modalPresentationStyle = .overCurrentContext
definesPresentationContext = true;
providesPresentationContextTransitionStyle = true;
handleRefresh(refresh: nil)
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
performSelector(onMainThread: #selector(updateToolbar), with: nil, waitUntilDone: false)
}
@objc func updateToolbar() {
if let controller = navigationController {
controller.navigationBar.topItem!.title = "Rewards Store"
Common.showUserInToolbar(nav: controller)
}
}
var _offers : [SMStoreOfferItem] = [];
@IBAction func handleRefresh(refresh: UIRefreshControl?) {
SMOffersManager.instance().fetchStoreOffers { (result: SMStoreOffersFetchedResponse?, error: SMError?) in
if let r = refresh, r.isRefreshing {
r.endRefreshing();
}
if let error = error {
self.present(UIAlertController(title: "Nothing Fetched", message: error.message, preferredStyle: .alert), animated: true, completion: {})
} else if let offers = result?.offers {
self._offers = offers;
self.tableView.reloadData();
}
}
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return _offers.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Reward Store Cell", for: indexPath) as! RewardStoreTableViewCell
let item = _offers[indexPath.row];
cell.header.text = item.name;
let df = DateFormatter()
df.dateFormat = "dd.MM.yyyy"
if let endDate = item.endDate {
cell.validDates.text = "This offer is available \(df.string(from: item.startDate)) through \(df.string(from: endDate))"
}
let points = NSNumber(value: item.price).intValue;
cell.points.text = "\(points)";
if (item.media.count > 0) {
Common.loadImage(parent: self.tableView, uri: item.media[0].uri, imgView: cell.img, imageHeight: nil, maxHeight: 200)
}
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let claimVC = storyboard?.instantiateViewController(withIdentifier: "ClaimOffer") as! PurchaseAOfferViewController
claimVC.item = _offers[indexPath.row];
present(claimVC, animated: false) {}
}
}
| 3ef2afe81f0ddc053721f7f57052e52a | 32.458716 | 153 | 0.664107 | false | false | false | false |
faimin/ZDOpenSourceDemo | refs/heads/master | ZDOpenSourceSwiftDemo/Pods/Kingfisher/Sources/Extensions/NSButton+Kingfisher.swift | mit | 1 | //
// NSButton+Kingfisher.swift
// Kingfisher
//
// Created by Jie Zhang on 14/04/2016.
//
// Copyright (c) 2019 Wei Wang <[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.
#if canImport(AppKit) && !targetEnvironment(macCatalyst)
import AppKit
extension KingfisherWrapper where Base: NSButton {
// MARK: Setting Image
/// Sets an image to the button with a source.
///
/// - Parameters:
/// - source: The `Source` object contains information about how to get the image.
/// - placeholder: A placeholder to show while retrieving the image from the given `resource`.
/// - options: An options set to define image setting behaviors. See `KingfisherOptionsInfo` for more.
/// - progressBlock: Called when the image downloading progress gets updated. If the response does not contain an
/// `expectedContentLength`, this block will not be called.
/// - completionHandler: Called when the image retrieved and set finished.
/// - Returns: A task represents the image downloading.
///
/// - Note:
/// Internally, this method will use `KingfisherManager` to get the requested source.
/// Since this method will perform UI changes, you must call it from the main thread.
/// Both `progressBlock` and `completionHandler` will be also executed in the main thread.
///
@discardableResult
public func setImage(
with source: Source?,
placeholder: KFCrossPlatformImage? = nil,
options: KingfisherOptionsInfo? = nil,
progressBlock: DownloadProgressBlock? = nil,
completionHandler: ((Result<RetrieveImageResult, KingfisherError>) -> Void)? = nil) -> DownloadTask?
{
var mutatingSelf = self
guard let source = source else {
base.image = placeholder
mutatingSelf.taskIdentifier = nil
completionHandler?(.failure(KingfisherError.imageSettingError(reason: .emptySource)))
return nil
}
var options = KingfisherParsedOptionsInfo(KingfisherManager.shared.defaultOptions + (options ?? .empty))
if !options.keepCurrentImageWhileLoading {
base.image = placeholder
}
let issuedIdentifier = Source.Identifier.next()
mutatingSelf.taskIdentifier = issuedIdentifier
if let block = progressBlock {
options.onDataReceived = (options.onDataReceived ?? []) + [ImageLoadingProgressSideEffect(block)]
}
if let provider = ImageProgressiveProvider(options, refresh: { image in
self.base.image = image
}) {
options.onDataReceived = (options.onDataReceived ?? []) + [provider]
}
options.onDataReceived?.forEach {
$0.onShouldApply = { issuedIdentifier == self.taskIdentifier }
}
let task = KingfisherManager.shared.retrieveImage(
with: source,
options: options,
completionHandler: { result in
CallbackQueue.mainCurrentOrAsync.execute {
guard issuedIdentifier == self.taskIdentifier else {
let reason: KingfisherError.ImageSettingErrorReason
do {
let value = try result.get()
reason = .notCurrentSourceTask(result: value, error: nil, source: source)
} catch {
reason = .notCurrentSourceTask(result: nil, error: error, source: source)
}
let error = KingfisherError.imageSettingError(reason: reason)
completionHandler?(.failure(error))
return
}
mutatingSelf.imageTask = nil
mutatingSelf.taskIdentifier = nil
switch result {
case .success(let value):
self.base.image = value.image
completionHandler?(result)
case .failure:
if let image = options.onFailureImage {
self.base.image = image
}
completionHandler?(result)
}
}
}
)
mutatingSelf.imageTask = task
return task
}
/// Sets an image to the button with a requested resource.
///
/// - Parameters:
/// - resource: The `Resource` object contains information about the resource.
/// - placeholder: A placeholder to show while retrieving the image from the given `resource`.
/// - options: An options set to define image setting behaviors. See `KingfisherOptionsInfo` for more.
/// - progressBlock: Called when the image downloading progress gets updated. If the response does not contain an
/// `expectedContentLength`, this block will not be called.
/// - completionHandler: Called when the image retrieved and set finished.
/// - Returns: A task represents the image downloading.
///
/// - Note:
/// Internally, this method will use `KingfisherManager` to get the requested resource, from either cache
/// or network. Since this method will perform UI changes, you must call it from the main thread.
/// Both `progressBlock` and `completionHandler` will be also executed in the main thread.
///
@discardableResult
public func setImage(
with resource: Resource?,
placeholder: KFCrossPlatformImage? = nil,
options: KingfisherOptionsInfo? = nil,
progressBlock: DownloadProgressBlock? = nil,
completionHandler: ((Result<RetrieveImageResult, KingfisherError>) -> Void)? = nil) -> DownloadTask?
{
return setImage(
with: resource.map { .network($0) },
placeholder: placeholder,
options: options,
progressBlock: progressBlock,
completionHandler: completionHandler)
}
// MARK: Cancelling Downloading Task
/// Cancels the image download task of the button if it is running.
/// Nothing will happen if the downloading has already finished.
public func cancelImageDownloadTask() {
imageTask?.cancel()
}
// MARK: Setting Alternate Image
@discardableResult
public func setAlternateImage(
with source: Source?,
placeholder: KFCrossPlatformImage? = nil,
options: KingfisherOptionsInfo? = nil,
progressBlock: DownloadProgressBlock? = nil,
completionHandler: ((Result<RetrieveImageResult, KingfisherError>) -> Void)? = nil) -> DownloadTask?
{
var mutatingSelf = self
guard let source = source else {
base.alternateImage = placeholder
mutatingSelf.alternateTaskIdentifier = nil
completionHandler?(.failure(KingfisherError.imageSettingError(reason: .emptySource)))
return nil
}
var options = KingfisherParsedOptionsInfo(KingfisherManager.shared.defaultOptions + (options ?? .empty))
if !options.keepCurrentImageWhileLoading {
base.alternateImage = placeholder
}
let issuedIdentifier = Source.Identifier.next()
mutatingSelf.alternateTaskIdentifier = issuedIdentifier
if let block = progressBlock {
options.onDataReceived = (options.onDataReceived ?? []) + [ImageLoadingProgressSideEffect(block)]
}
if let provider = ImageProgressiveProvider(options, refresh: { image in
self.base.alternateImage = image
}) {
options.onDataReceived = (options.onDataReceived ?? []) + [provider]
}
options.onDataReceived?.forEach {
$0.onShouldApply = { issuedIdentifier == self.alternateTaskIdentifier }
}
let task = KingfisherManager.shared.retrieveImage(
with: source,
options: options,
completionHandler: { result in
CallbackQueue.mainCurrentOrAsync.execute {
guard issuedIdentifier == self.alternateTaskIdentifier else {
let reason: KingfisherError.ImageSettingErrorReason
do {
let value = try result.get()
reason = .notCurrentSourceTask(result: value, error: nil, source: source)
} catch {
reason = .notCurrentSourceTask(result: nil, error: error, source: source)
}
let error = KingfisherError.imageSettingError(reason: reason)
completionHandler?(.failure(error))
return
}
mutatingSelf.alternateImageTask = nil
mutatingSelf.alternateTaskIdentifier = nil
switch result {
case .success(let value):
self.base.alternateImage = value.image
completionHandler?(result)
case .failure:
if let image = options.onFailureImage {
self.base.alternateImage = image
}
completionHandler?(result)
}
}
}
)
mutatingSelf.alternateImageTask = task
return task
}
/// Sets an alternate image to the button with a requested resource.
///
/// - Parameters:
/// - resource: The `Resource` object contains information about the resource.
/// - placeholder: A placeholder to show while retrieving the image from the given `resource`.
/// - options: An options set to define image setting behaviors. See `KingfisherOptionsInfo` for more.
/// - progressBlock: Called when the image downloading progress gets updated. If the response does not contain an
/// `expectedContentLength`, this block will not be called.
/// - completionHandler: Called when the image retrieved and set finished.
/// - Returns: A task represents the image downloading.
///
/// - Note:
/// Internally, this method will use `KingfisherManager` to get the requested resource, from either cache
/// or network. Since this method will perform UI changes, you must call it from the main thread.
/// Both `progressBlock` and `completionHandler` will be also executed in the main thread.
///
@discardableResult
public func setAlternateImage(
with resource: Resource?,
placeholder: KFCrossPlatformImage? = nil,
options: KingfisherOptionsInfo? = nil,
progressBlock: DownloadProgressBlock? = nil,
completionHandler: ((Result<RetrieveImageResult, KingfisherError>) -> Void)? = nil) -> DownloadTask?
{
return setAlternateImage(
with: resource.map { .network($0) },
placeholder: placeholder,
options: options,
progressBlock: progressBlock,
completionHandler: completionHandler)
}
// MARK: Cancelling Alternate Image Downloading Task
/// Cancels the alternate image download task of the button if it is running.
/// Nothing will happen if the downloading has already finished.
public func cancelAlternateImageDownloadTask() {
alternateImageTask?.cancel()
}
}
// MARK: - Associated Object
private var taskIdentifierKey: Void?
private var imageTaskKey: Void?
private var alternateTaskIdentifierKey: Void?
private var alternateImageTaskKey: Void?
extension KingfisherWrapper where Base: NSButton {
// MARK: Properties
public private(set) var taskIdentifier: Source.Identifier.Value? {
get {
let box: Box<Source.Identifier.Value>? = getAssociatedObject(base, &taskIdentifierKey)
return box?.value
}
set {
let box = newValue.map { Box($0) }
setRetainedAssociatedObject(base, &taskIdentifierKey, box)
}
}
private var imageTask: DownloadTask? {
get { return getAssociatedObject(base, &imageTaskKey) }
set { setRetainedAssociatedObject(base, &imageTaskKey, newValue)}
}
public private(set) var alternateTaskIdentifier: Source.Identifier.Value? {
get {
let box: Box<Source.Identifier.Value>? = getAssociatedObject(base, &alternateTaskIdentifierKey)
return box?.value
}
set {
let box = newValue.map { Box($0) }
setRetainedAssociatedObject(base, &alternateTaskIdentifierKey, box)
}
}
private var alternateImageTask: DownloadTask? {
get { return getAssociatedObject(base, &alternateImageTaskKey) }
set { setRetainedAssociatedObject(base, &alternateImageTaskKey, newValue)}
}
}
extension KingfisherWrapper where Base: NSButton {
/// Gets the image URL bound to this button.
@available(*, deprecated, message: "Use `taskIdentifier` instead to identify a setting task.")
public private(set) var webURL: URL? {
get { return nil }
set { }
}
/// Gets the image URL bound to this button.
@available(*, deprecated, message: "Use `alternateTaskIdentifier` instead to identify a setting task.")
public private(set) var alternateWebURL: URL? {
get { return nil }
set { }
}
}
#endif
| 96e04254a7680362ce6c97ee4b56ed5d | 40.815864 | 119 | 0.613644 | false | false | false | false |
sbcmadn1/swift | refs/heads/master | swiftweibo05/GZWeibo05/Class/Module/Home/View/Cell/CZStatusForwardCell.swift | mit | 1 | //
// CZStatusForwardCell.swift
// GZWeibo05
//
// Created by zhangping on 15/11/1.
// Copyright © 2015年 zhangping. All rights reserved.
//
import UIKit
/// 转发微博cell
class CZStatusForwardCell: CZStatusCell {
// 覆盖父类的模型属性
// 添加 override关键字,实现属性监视器,先调用父类的属性监视器,在调用子类的属性监视器
override var status: CZStatus? {
didSet {
// print("\(status?.idstr),子类监视器")
// 设置转发微博label的内容
let name = status?.retweeted_status?.user?.name ?? "名称为空"
let text = status?.retweeted_status?.text ?? "内容为空"
forwardLabel.text = "@\(name): \(text)"
}
}
/// 覆盖父类的方法
override func prepareUI() {
// 记得调用父类的prepareUI
super.prepareUI()
// 添加子控件
// contentView.addSubview(bkgButton)
// 将 bkgButton 插入到 配图的下面
contentView.insertSubview(bkgButton, belowSubview: pictureView)
contentView.addSubview(forwardLabel)
// 添加约束
// 背景
// 左上角约束
bkgButton.ff_AlignVertical(type: ff_AlignType.BottomLeft, referView: contentLabel, size: nil, offset: CGPoint(x: -StatusCellMargin, y: StatusCellMargin))
// 右下角
bkgButton.ff_AlignVertical(type: ff_AlignType.TopRight, referView: bottomView, size: nil)
// 被转发微博内容label
forwardLabel.ff_AlignInner(type: ff_AlignType.TopLeft, referView: bkgButton, size: nil, offset: CGPoint(x: StatusCellMargin, y: StatusCellMargin))
// 宽度约束
contentView.addConstraint(NSLayoutConstraint(item: forwardLabel, attribute: NSLayoutAttribute.Width, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1, constant: UIScreen.width() - 2 * StatusCellMargin))
// 配图的约束
let cons = pictureView.ff_AlignVertical(type: ff_AlignType.BottomLeft, referView: forwardLabel, size: CGSize(width: 0, height: 0), offset: CGPoint(x: 0, y: StatusCellMargin))
// 获取配图的宽高约束
pictureViewHeightCon = pictureView.ff_Constraint(cons, attribute: NSLayoutAttribute.Height)
pictureViewWidthCon = pictureView.ff_Constraint(cons, attribute: NSLayoutAttribute.Width)
}
// MARK: - 懒加载
/// 灰色的背景
private lazy var bkgButton: UIButton = {
let button = UIButton()
// 设置背景
button.backgroundColor = UIColor(white: 0.9, alpha: 1)
return button
}()
/// 被转发微博内容label
private lazy var forwardLabel: UILabel = {
let label = UILabel()
label.textColor = UIColor.darkGrayColor()
label.numberOfLines = 0
label.text = "我是测试文字我是测试文字我是测试文字我是测试文字我是测试文字我是测试文字我是测试文字我是测试文字我是测试文字我是测试文字我是测试文字我是测试文字我是测试文字"
return label
}()
}
| a4f893d2c7cf2b35695286c0049f6691 | 34.126582 | 268 | 0.635676 | false | false | false | false |
Coderian/SwiftedGPX | refs/heads/master | SwiftedGPX/Elements/Type.swift | mit | 1 | //
// Type.swift
// SwiftedGPX
//
// Created by 佐々木 均 on 2016/02/16.
// Copyright © 2016年 S-Parts. All rights reserved.
//
import Foundation
/// GPX Type
///
/// [GPX 1.1 schema](http://www.topografix.com/GPX/1/1/gpx.xsd)
///
/// <xsd:element name="type" type="xsd:string" minOccurs="0">
/// <xsd:annotation>
/// <xsd:documentation>
/// Type (classification) of the waypoint.
/// </xsd:documentation>
/// </xsd:annotation>
/// </xsd:element>
public class Type : SPXMLElement, HasXMLElementValue, HasXMLElementSimpleValue {
public static var elementName: String = "type"
public override var parent:SPXMLElement! {
didSet {
// 複数回呼ばれたて同じものがある場合は追加しない
if self.parent.childs.contains(self) == false {
self.parent.childs.insert(self)
switch parent {
case let v as WayPoint: v.value.type = self
case let v as Track: v.value.type = self
case let v as Route: v.value.type = self
case let v as TrackPoint: v.value.type = self
case let v as RoutePoint: v.value.type = self
default: break
}
}
}
}
public var value: String!
public func makeRelation(contents:String, parent:SPXMLElement) -> SPXMLElement{
self.value = contents
self.parent = parent
return parent
}
public required init(attributes:[String:String]){
super.init(attributes: attributes)
}
} | aac3a5d994c8f6ac9d6640f027459590 | 30.755102 | 83 | 0.576206 | false | false | false | false |
ivygulch/IVGRouter | refs/heads/master | IVGRouterTests/tests/router/RouteSequenceSpec.swift | mit | 1 | //
// RouteSequenceSpec.swift
// IVGRouter
//
// Created by Douglas Sjoquist on 4/24/16.
// Copyright © 2016 Ivy Gulch LLC. All rights reserved.
//
import UIKit
import Quick
import Nimble
import IVGRouter
class RouteSequenceSpec: QuickSpec {
override func spec() {
describe("RouteSequence") {
var router: Router = Router(window: nil, routerContext: RouterContext())
let dummyIdentifier = Identifier(name: "dummy")
let mockVisualRouteSegmentA = MockVisualRouteSegment(segmentIdentifier: Identifier(name: "A"), presenterIdentifier: dummyIdentifier, presentedViewController: nil)
let mockVisualRouteSegmentB = MockVisualRouteSegment(segmentIdentifier: Identifier(name: "B"), presenterIdentifier: dummyIdentifier, presentedViewController: nil)
beforeEach {
router = Router(window: nil, routerContext: RouterContext())
}
context("with valid registered segments") {
var routeSequence: RouteSequence!
var validatedRouteSegments: [RouteSegmentType]?
beforeEach {
router = Router(window: nil, routerContext: RouterContext())
router.routerContext.register(routeSegment: mockVisualRouteSegmentA)
router.routerContext.register(routeSegment: mockVisualRouteSegmentB)
routeSequence = RouteSequence(source: [
mockVisualRouteSegmentA.segmentIdentifier,
mockVisualRouteSegmentB.segmentIdentifier
])
validatedRouteSegments = routeSequence.validatedRouteSegmentsWithRouter(router)
}
it("should have matching route segments") {
if let validatedRouteSegments = validatedRouteSegments {
expect(validatedRouteSegments).to(haveCount(routeSequence.items.count))
for index in 0..<routeSequence.items.count {
if index < validatedRouteSegments.count {
let segmentIdentifier = routeSequence.items[index].segmentIdentifier
let validatedRouteSegment = validatedRouteSegments[index]
expect(validatedRouteSegment.segmentIdentifier).to(equal(segmentIdentifier))
}
}
} else {
expect(validatedRouteSegments).toNot(beNil())
}
}
}
context("with valid but unregistered segments") {
var routeSequence: RouteSequence!
var validatedRouteSegments: [RouteSegmentType]?
beforeEach {
router = Router(window: nil, routerContext: RouterContext())
routeSequence = RouteSequence(source: [
mockVisualRouteSegmentA.segmentIdentifier,
mockVisualRouteSegmentB.segmentIdentifier
])
validatedRouteSegments = routeSequence.validatedRouteSegmentsWithRouter(router)
}
it("should not have validated route segments") {
expect(validatedRouteSegments).to(beNil())
}
}
}
}
}
| fdfc537a0b33dd9c5be63980472b43f4 | 39.576471 | 174 | 0.57292 | false | false | false | false |
lfaoro/Cast | refs/heads/master | Cast/UserNotifications.swift | mit | 1 | //
// Created by Leonardo on 29/07/2015.
// Copyright © 2015 Leonardo Faoro. All rights reserved.
//
import Cocoa
final class UserNotifications: NSObject {
//---------------------------------------------------------------------------
var notificationCenter: NSUserNotificationCenter!
var didActivateNotificationURL: NSURL?
//---------------------------------------------------------------------------
override init() {
super.init()
notificationCenter = NSUserNotificationCenter.defaultUserNotificationCenter()
notificationCenter.delegate = self
}
//---------------------------------------------------------------------------
private func createNotification(title: String, subtitle: String) -> NSUserNotification {
let notification = NSUserNotification()
notification.title = title
notification.subtitle = subtitle
notification.informativeText = "Copied to your clipboard"
notification.actionButtonTitle = "Open URL"
notification.soundName = NSUserNotificationDefaultSoundName
return notification
}
//---------------------------------------------------------------------------
func pushNotification(openURL url: String, title: String = "Casted to gist.GitHub.com") {
didActivateNotificationURL = NSURL(string: url)!
let notification = self.createNotification(title, subtitle: url)
notificationCenter.deliverNotification(notification)
startUserNotificationTimer() //IRC: calling from here doesn't work
}
//---------------------------------------------------------------------------
func pushNotification(error error: String,
description: String = "An error occured, please try again.") {
let notification = NSUserNotification()
notification.title = error
notification.informativeText = description
notification.soundName = NSUserNotificationDefaultSoundName
notification.hasActionButton = false
notificationCenter.deliverNotification(notification)
startUserNotificationTimer()
}
//---------------------------------------------------------------------------
private func startUserNotificationTimer() {
print(__FUNCTION__)
app.timer = NSTimer
.scheduledTimerWithTimeInterval(
10.0,
target: self,
selector: "removeUserNotifcationsAction:",
userInfo: nil,
repeats: false)
}
//---------------------------------------------------------------------------
func removeUserNotifcationsAction(timer: NSTimer) {
print(__FUNCTION__)
notificationCenter.removeAllDeliveredNotifications()
timer.invalidate()
}
//---------------------------------------------------------------------------
}
//MARK:- NSUserNotificationCenterDelegate
extension UserNotifications: NSUserNotificationCenterDelegate {
//---------------------------------------------------------------------------
func userNotificationCenter(center: NSUserNotificationCenter,
didActivateNotification notification: NSUserNotification) {
print("notification pressed")
if let url = didActivateNotificationURL {
NSWorkspace.sharedWorkspace().openURL(url)
} else {
center.removeAllDeliveredNotifications()
}
} // executes an action whenever the notification is pressed
//---------------------------------------------------------------------------
func userNotificationCenter(center: NSUserNotificationCenter,
shouldPresentNotification notification: NSUserNotification) -> Bool {
return true
} // forces the notification to display even when app is active app
//---------------------------------------------------------------------------
}
| f3a3a2cc239b726bb70ff07146ea31d5 | 40.75 | 90 | 0.5931 | false | false | false | false |
Constantine-Fry/das-quadrat | refs/heads/develop | Source/Shared/Endpoints/Pages.swift | apache-2.0 | 2 | //
// Pages.swift
// Quadrat
//
// Created by Constantine Fry on 06/11/14.
// Copyright (c) 2014 Constantine Fry. All rights reserved.
//
import Foundation
open class Pages: Endpoint {
override var endpoint: String {
return "pages"
}
// MARK: - General
/** https://developer.foursquare.com/docs/pages/add */
open func add(_ name: String, completionHandler: ResponseClosure? = nil) -> Task {
let path = "add"
let parameters = [Parameter.name: name]
return self.postWithPath(path, parameters: parameters, completionHandler: completionHandler)
}
/** https://developer.foursquare.com/docs/pages/managing */
open func managing(_ completionHandler: ResponseClosure? = nil) -> Task {
let path = "managing"
return self.getWithPath(path, parameters: nil, completionHandler: completionHandler)
}
// MARK: - Aspects
/** https://developer.foursquare.com/docs/pages/access */
open func access(_ userId: String, completionHandler: ResponseClosure? = nil) -> Task {
let path = userId + "/access"
return self.getWithPath(path, parameters: nil, completionHandler: completionHandler)
}
/** https://developer.foursquare.com/docs/pages/similar */
open func similar(_ userId: String, parameters: Parameters?, completionHandler: ResponseClosure? = nil) -> Task {
let path = userId + "/similar"
return self.getWithPath(path, parameters: parameters, completionHandler: completionHandler)
}
/** https://developer.foursquare.com/docs/pages/timeseries */
open func timeseries(_ pageId: String, parameters: Parameters?, completionHandler: ResponseClosure? = nil) -> Task {
let path = pageId + "/timeseries"
return self.getWithPath(path, parameters: parameters, completionHandler: completionHandler)
}
/** https://developer.foursquare.com/docs/pages/venues */
open func venues(_ pageId: String, parameters: Parameters?, completionHandler: ResponseClosure? = nil) -> Task {
let path = pageId + "/venues"
return self.getWithPath(path, parameters: parameters, completionHandler: completionHandler)
}
// MARK: - Actions
/** https://developer.foursquare.com/docs/pages/follow */
open func follow(_ pageId: String, follow: Bool, completionHandler: ResponseClosure? = nil) -> Task {
let path = pageId + "/follow"
let parameters = [Parameter.set: (follow) ? "1":"0"]
return self.postWithPath(path, parameters: parameters, completionHandler: completionHandler)
}
}
| a82ac4faa43dc0c5d73e541f0bcaddff | 38.238806 | 120 | 0.662609 | false | false | false | false |
blockchain/My-Wallet-V3-iOS | refs/heads/master | Modules/FeatureKYC/Sources/FeatureKYCUI/Identity Verification/VeriffController.swift | lgpl-3.0 | 1 | // Copyright © Blockchain Luxembourg S.A. All rights reserved.
import Localization
import PlatformKit
import UIKit
import Veriff
protocol VeriffController: UIViewController, VeriffSdkDelegate {
var veriff: VeriffSdk { get }
// Actions
func veriffCredentialsRequest()
func launchVeriffController(credentials: VeriffCredentials)
// Completion handlers
func onVeriffSubmissionCompleted()
func trackInternalVeriffError(_ error: InternalVeriffError)
func onVeriffError(message: String)
func onVeriffCancelled()
}
extension VeriffController {
internal var veriff: VeriffSdk {
VeriffSdk.shared
}
func launchVeriffController(credentials: VeriffCredentials) {
veriff.delegate = self
veriff.startAuthentication(sessionUrl: credentials.url)
}
}
enum InternalVeriffError: Swift.Error {
case cameraUnavailable
case microphoneUnavailable
case serverError
case localError
case networkError
case uploadError
case videoFailed
case deprecatedSDKVersion
case unknown
init(veriffError: VeriffSdk.Error) {
switch veriffError {
case .cameraUnavailable:
self = .cameraUnavailable
case .microphoneUnavailable:
self = .microphoneUnavailable
case .serverError:
self = .serverError
case .localError:
self = .localError
case .networkError:
self = .networkError
case .uploadError:
self = .uploadError
case .videoFailed:
self = .videoFailed
case .deprecatedSDKVersion:
self = .deprecatedSDKVersion
case .unknown:
self = .unknown
@unknown default:
self = .unknown
}
}
}
extension VeriffSdk.Error {
var localizedErrorMessage: String {
switch self {
case .cameraUnavailable:
return LocalizationConstants.Errors.cameraAccessDeniedMessage
case .microphoneUnavailable:
return LocalizationConstants.Errors.microphoneAccessDeniedMessage
case .deprecatedSDKVersion,
.localError,
.networkError,
.serverError,
.unknown,
.uploadError,
.videoFailed:
return LocalizationConstants.Errors.genericError
@unknown default:
return LocalizationConstants.Errors.genericError
}
}
}
| cdf20321460c0ca18e7f091152a3ddf4 | 24.402062 | 77 | 0.650568 | false | false | false | false |
sudeepunnikrishnan/ios-sdk | refs/heads/master | Instamojo/UPISubmissionResponse.swift | lgpl-3.0 | 1 | //
// UPISubmissionResponse.swift
// Instamojo
//
// Created by Sukanya Raj on 15/02/17.
// Copyright © 2017 Sukanya Raj. All rights reserved.
//
import UIKit
public class UPISubmissionResponse: NSObject {
public var paymentID: String
public var statusCode: Int
public var payerVirtualAddress: String
public var payeeVirtualAddress: String
public var statusCheckURL: String
public var upiBank: String
public var statusMessage: String
override init() {
self.paymentID = ""
self.statusCode = 0
self.payeeVirtualAddress = ""
self.payerVirtualAddress = ""
self.statusCheckURL = ""
self.upiBank = ""
self.statusMessage = ""
}
public init(paymentID: String, statusCode: Int, payerVirtualAddress: String, payeeVirtualAddress: String, statusCheckURL: String, upiBank: String, statusMessage: String) {
self.paymentID = paymentID
self.statusCode = statusCode
self.payerVirtualAddress = payerVirtualAddress
self.payeeVirtualAddress = payeeVirtualAddress
self.statusCheckURL = statusCheckURL
self.upiBank = upiBank
self.statusMessage = statusMessage
}
}
| f145b82277f9d41d8f8d79cef22b435b | 29.175 | 175 | 0.685998 | false | false | false | false |
m-alani/contests | refs/heads/master | hackerrank/GameOfThrones-I.swift | mit | 1 | //
// GameOfThrones-I.swift
//
// Practice solution - Marwan Alani - 2017
//
// Check the problem (and run the code) on HackerRank @ https://www.hackerrank.com/challenges/game-of-thrones
// Note: make sure that you select "Swift" from the top-right language menu of the code editor when testing this code
//
// Read Input
if let input = readLine() {
var oddChars: Set<Character> = Set()
let word = input.characters
// Process the input line one character at a time. Maintain a set of all characters with odd occurences in the input
for char in word {
if let exists = oddChars.remove(char) {}
else {
oddChars.insert(char)
}
}
// Check for passing condition:
// The input line can have 1 character at most with odd occurences
let output = oddChars.count < 2 ? "YES" : "NO"
// Print Output
print(output)
}
| 32c521951ccbcea717c3f37c42d7c56b | 30.444444 | 118 | 0.685512 | false | false | false | false |
mrdepth/EVEOnlineAPI | refs/heads/master | EVEAPI/EVEAPI/codegen/Fittings.swift | mit | 1 | import Foundation
import Alamofire
import Futures
public extension ESI {
var fittings: Fittings {
return Fittings(esi: self)
}
struct Fittings {
let esi: ESI
@discardableResult
public func deleteFitting(characterID: Int, fittingID: Int, cachePolicy: URLRequest.CachePolicy = .useProtocolCachePolicy) -> Future<ESI.Result<String>> {
let scopes = esi.token?.scopes ?? []
guard scopes.contains("esi-fittings.write_fittings.v1") else {return .init(.failure(ESIError.forbidden))}
let body: Data? = nil
var headers = HTTPHeaders()
headers["Accept"] = "application/json"
headers["Content-Type"] = "application/json"
var query = [URLQueryItem]()
query.append(URLQueryItem(name: "datasource", value: esi.server.rawValue))
let url = esi.baseURL + "/characters/\(characterID)/fittings/\(fittingID)/"
let components = NSURLComponents(string: url)!
components.queryItems = query
let promise = Promise<ESI.Result<String>>()
esi.request(components.url!, method: .delete, encoding: body ?? URLEncoding.default, headers: headers, cachePolicy: cachePolicy).validateESI().responseESI { (response: DataResponse<String>) in
promise.set(response: response, cached: nil)
}
return promise.future
}
@discardableResult
public func getFittings(characterID: Int, ifNoneMatch: String? = nil, cachePolicy: URLRequest.CachePolicy = .useProtocolCachePolicy) -> Future<ESI.Result<[Fittings.Fitting]>> {
let scopes = esi.token?.scopes ?? []
guard scopes.contains("esi-fittings.read_fittings.v1") else {return .init(.failure(ESIError.forbidden))}
let body: Data? = nil
var headers = HTTPHeaders()
headers["Accept"] = "application/json"
if let v = ifNoneMatch?.httpQuery {
headers["If-None-Match"] = v
}
var query = [URLQueryItem]()
query.append(URLQueryItem(name: "datasource", value: esi.server.rawValue))
let url = esi.baseURL + "/characters/\(characterID)/fittings/"
let components = NSURLComponents(string: url)!
components.queryItems = query
let promise = Promise<ESI.Result<[Fittings.Fitting]>>()
esi.request(components.url!, method: .get, encoding: body ?? URLEncoding.default, headers: headers, cachePolicy: cachePolicy).validateESI().responseESI { (response: DataResponse<[Fittings.Fitting]>) in
promise.set(response: response, cached: 300.0)
}
return promise.future
}
@discardableResult
public func createFitting(characterID: Int, fitting: Fittings.MutableFitting, cachePolicy: URLRequest.CachePolicy = .useProtocolCachePolicy) -> Future<ESI.Result<Fittings.CreateFittingResult>> {
let scopes = esi.token?.scopes ?? []
guard scopes.contains("esi-fittings.write_fittings.v1") else {return .init(.failure(ESIError.forbidden))}
let body = try? JSONEncoder().encode(fitting)
var headers = HTTPHeaders()
headers["Accept"] = "application/json"
headers["Content-Type"] = "application/json"
var query = [URLQueryItem]()
query.append(URLQueryItem(name: "datasource", value: esi.server.rawValue))
let url = esi.baseURL + "/characters/\(characterID)/fittings/"
let components = NSURLComponents(string: url)!
components.queryItems = query
let promise = Promise<ESI.Result<Fittings.CreateFittingResult>>()
esi.request(components.url!, method: .post, encoding: body ?? URLEncoding.default, headers: headers, cachePolicy: cachePolicy).validateESI().responseESI { (response: DataResponse<Fittings.CreateFittingResult>) in
promise.set(response: response, cached: nil)
}
return promise.future
}
public struct CreateFittingResult: Codable, Hashable {
public var fittingID: Int
public init(fittingID: Int) {
self.fittingID = fittingID
}
enum CodingKeys: String, CodingKey, DateFormatted {
case fittingID = "fitting_id"
var dateFormatter: DateFormatter? {
switch self {
default: return nil
}
}
}
}
public struct MutableFitting: Codable, Hashable {
public var localizedDescription: String
public var items: [Fittings.Item]
public var name: String
public var shipTypeID: Int
public init(localizedDescription: String, items: [Fittings.Item], name: String, shipTypeID: Int) {
self.localizedDescription = localizedDescription
self.items = items
self.name = name
self.shipTypeID = shipTypeID
}
enum CodingKeys: String, CodingKey, DateFormatted {
case localizedDescription = "description"
case items
case name
case shipTypeID = "ship_type_id"
var dateFormatter: DateFormatter? {
switch self {
default: return nil
}
}
}
}
public struct Fitting: Codable, Hashable {
public var localizedDescription: String
public var fittingID: Int
public var items: [Fittings.Item]
public var name: String
public var shipTypeID: Int
public init(localizedDescription: String, fittingID: Int, items: [Fittings.Item], name: String, shipTypeID: Int) {
self.localizedDescription = localizedDescription
self.fittingID = fittingID
self.items = items
self.name = name
self.shipTypeID = shipTypeID
}
enum CodingKeys: String, CodingKey, DateFormatted {
case localizedDescription = "description"
case fittingID = "fitting_id"
case items
case name
case shipTypeID = "ship_type_id"
var dateFormatter: DateFormatter? {
switch self {
default: return nil
}
}
}
}
public struct Item: Codable, Hashable {
public enum Flag: String, Codable, HTTPQueryable {
case cargo = "Cargo"
case droneBay = "DroneBay"
case fighterBay = "FighterBay"
case hiSlot0 = "HiSlot0"
case hiSlot1 = "HiSlot1"
case hiSlot2 = "HiSlot2"
case hiSlot3 = "HiSlot3"
case hiSlot4 = "HiSlot4"
case hiSlot5 = "HiSlot5"
case hiSlot6 = "HiSlot6"
case hiSlot7 = "HiSlot7"
case invalid = "Invalid"
case loSlot0 = "LoSlot0"
case loSlot1 = "LoSlot1"
case loSlot2 = "LoSlot2"
case loSlot3 = "LoSlot3"
case loSlot4 = "LoSlot4"
case loSlot5 = "LoSlot5"
case loSlot6 = "LoSlot6"
case loSlot7 = "LoSlot7"
case medSlot0 = "MedSlot0"
case medSlot1 = "MedSlot1"
case medSlot2 = "MedSlot2"
case medSlot3 = "MedSlot3"
case medSlot4 = "MedSlot4"
case medSlot5 = "MedSlot5"
case medSlot6 = "MedSlot6"
case medSlot7 = "MedSlot7"
case rigSlot0 = "RigSlot0"
case rigSlot1 = "RigSlot1"
case rigSlot2 = "RigSlot2"
case serviceSlot0 = "ServiceSlot0"
case serviceSlot1 = "ServiceSlot1"
case serviceSlot2 = "ServiceSlot2"
case serviceSlot3 = "ServiceSlot3"
case serviceSlot4 = "ServiceSlot4"
case serviceSlot5 = "ServiceSlot5"
case serviceSlot6 = "ServiceSlot6"
case serviceSlot7 = "ServiceSlot7"
case subSystemSlot0 = "SubSystemSlot0"
case subSystemSlot1 = "SubSystemSlot1"
case subSystemSlot2 = "SubSystemSlot2"
case subSystemSlot3 = "SubSystemSlot3"
public var httpQuery: String? {
return rawValue
}
}
public var flag: Fittings.Item.Flag
public var quantity: Int
public var typeID: Int
public init(flag: Fittings.Item.Flag, quantity: Int, typeID: Int) {
self.flag = flag
self.quantity = quantity
self.typeID = typeID
}
enum CodingKeys: String, CodingKey, DateFormatted {
case flag
case quantity
case typeID = "type_id"
var dateFormatter: DateFormatter? {
switch self {
default: return nil
}
}
}
}
}
}
| 7abfd48e553d31e1af49bc4360fe9060 | 28.267176 | 215 | 0.676448 | false | false | false | false |
nickswalker/ASCIIfy | refs/heads/master | Tests/TestBlockGrid.swift | mit | 1 | //
// Copyright for portions of ASCIIfy are held by Barış Koç, 2014 as part of
// project BKAsciiImage and Amy Dyer, 2012 as part of project Ascii. All other copyright
// for ASCIIfy are held by Nick Walker, 2016.
//
// 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 XCTest
@testable import ASCIIfy
class TestBlockGrid: XCTestCase {
var largeChecker: Image!
override func setUp() {
super.setUp()
let bundle = Bundle(for: type(of: self))
largeChecker = {
let fileLocation = bundle.path(forResource: "checker-1024", ofType: "png")!
let image = Image(contentsOfFile: fileLocation)!
return image
}()
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testPixelGridImageConstructor() {
let result = BlockGrid(image: largeChecker)
XCTAssertEqual(result.width, Int(largeChecker.size.width))
XCTAssertEqual(result.height, Int(largeChecker.size.height))
let black = BlockGrid.Block(r: 0, g: 0, b:0, a: 1)
let white = BlockGrid.Block(r: 1, g: 1, b:1, a: 1)
XCTAssertEqual(result.block(atRow: 0, column: 0), white)
XCTAssertEqual(result.block(atRow:1, column: 0), black)
}
func testConstructionFromImagePerformance() {
measure {
let _ = BlockGrid(image: self.largeChecker)
}
}
}
| 384afb1b4137e9c661ad5c489722caba | 41.3 | 111 | 0.689125 | false | true | false | false |
leo150/Pelican | refs/heads/develop | Sources/Pelican/API/Types/Markup/InlineKey.swift | mit | 1 | //
// InlineKey.swift
// Pelican
//
// Created by Takanu Kyriako on 31/08/2017.
//
import Foundation
import Vapor
import FluentProvider
/**
Defines a single keyboard key on a `MarkupInline` keyboard. Each key supports one of 4 different modes:
_ _ _ _ _
**Callback Data**
This sends a small String back to the bot as a `CallbackQuery`, which is automatically filtered
back to the session and to a `callbackState` if one exists.
Alternatively if the keyboard the button belongs to is part of a `Prompt`, it will automatically
be received by it in the respective ChatSession, and the prompt will respond based on how you have set
it up.
**URL**
The button when pressed will re-direct users to a webpage.
**Inine Query Switch**
This can only be used when the bot supports Inline Queries. This prompts the user to select one of their chats
to open it, and when open the client will insert the bot‘s username and a specified query in the input field.
**Inline Query Current Chat**
This can only be used when the bot supports Inline Queries. Pressing the button will insert the bot‘s username
and an optional specific inline query in the current chat's input field.
*/
final public class MarkupInlineKey: Model, Equatable {
public var storage = Storage()
public var text: String // Label text
public var data: String
public var type: InlineKeyType
/**
Creates a `MarkupInlineKey` as a URL key.
This key type causes the specified URL to be opened by the client
when button is pressed. If it links to a public Telegram chat or bot, it will be immediately opened.
*/
public init(fromURL url: String, text: String) {
self.text = text
self.data = url
self.type = .url
}
/**
Creates a `MarkupInlineKey` as a Callback Data key.
This key sends the defined callback data back to the bot to be handled.
- parameter callback: The data to be sent back to the bot once pressed. Accepts 1-64 bytes of data.
- parameter text: The text label to be shown on the button. Set to nil if you wish it to be the same as the callback.
*/
public init?(fromCallbackData callback: String, text: String?) {
// Check to see if the callback meets the byte requirement.
if callback.lengthOfBytes(using: String.Encoding.utf8) > 64 {
PLog.error("The MarkupKey with the text label, \"\(String(describing:text))\" has a callback of \(callback) that exceeded 64 bytes.")
return nil
}
// Check to see if we have a label
if text != nil { self.text = text! }
else { self.text = callback }
self.data = callback
self.type = .callbackData
}
/**
Creates a `MarkupInlineKey` as a Current Chat Inline Query key.
This key prompts the user to select one of their chats, open it and insert the bot‘s username and the specified query in the input field.
*/
public init(fromInlineQueryCurrent data: String, text: String) {
self.text = text
self.data = data
self.type = .switchInlineQuery_currentChat
}
/**
Creates a `MarkupInlineKey` as a New Chat Inline Query key.
This key inserts the bot‘s username and the specified inline query in the current chat's input field. Can be empty.
*/
public init(fromInlineQueryNewChat data: String, text: String) {
self.text = text
self.data = data
self.type = .switchInlineQuery
}
static public func ==(lhs: MarkupInlineKey, rhs: MarkupInlineKey) -> Bool {
if lhs.text != rhs.text { return false }
if lhs.type != rhs.type { return false }
if lhs.data != rhs.data { return false }
return true
}
// Ignore context, just try and build an object from a node.
public required init(row: Row) throws {
text = try row.get("text")
if row["url"] != nil {
data = try row.get("url")
type = .url
}
else if row["callback_data"] != nil {
data = try row.get("callback_data")
type = .url
}
else if row["switch_inline_query"] != nil {
data = try row.get("switch_inline_query")
type = .url
}
else if row["switch_inline_query_current_chat"] != nil {
data = try row.get("switch_inline_query_current_chat")
type = .url
}
else {
data = ""
type = .url
}
}
public func makeRow() throws -> Row {
var row = Row()
try row.set("text", text)
switch type {
case .url:
try row.set("url", data)
case .callbackData:
try row.set("callback_data", data)
case .switchInlineQuery:
try row.set("switch_inline_query", data)
case .switchInlineQuery_currentChat:
try row.set("switch_inline_query_current_chat", data)
}
return row
}
}
| d07d976547af5b16b1816b57bad5d4fe | 27.124224 | 138 | 0.696334 | false | false | false | false |
Jakobeha/lAzR4t | refs/heads/master | lAzR4t Shared/Code/GridElem/GridElemController.swift | mit | 1 | //
// GridController.swift
// lAzR4t
//
// Created by Jakob Hain on 9/30/17.
// Copyright © 2017 Jakob Hain. All rights reserved.
//
import Foundation
final class GridElemController<TSub: Elem>: ElemController<GridElem<TSub>> {
let grid: GridController<TSub>
var _pos: CellPos
var pos: CellPos {
get { return _pos }
set(newPos) {
_pos = newPos
grid.node.position = pos.toDisplay
}
}
var frame: CellFrame { return curModel.frame }
///Not this element's actual node. This is an actual represetnation of a grid.
let gridNode: GridElemNode?
override var curModel: GridElem<TSub> {
return GridElem(pos: self.pos, grid: self.grid.curModel)
}
convenience init(frame: CellFrame, display: Bool) {
self.init(pos: frame.pos, size: frame.size, display: display)
}
convenience init(pos: CellPos, size: CellSize, display: Bool) {
let node = ElemNode()
node.position = pos.toDisplay
self.init(
grid: GridController(size: size, node: node),
pos: pos,
display: display
)
}
private init(grid: GridController<TSub>, pos: CellPos, display: Bool) {
self.grid = grid
self._pos = pos
self.gridNode = display ? GridElemNode(cellSize: grid.curModel.size) : nil
super.init(node: grid.node)
assert(grid.elemOwner == nil, "Grid can't be owned by two elements")
grid._elemOwner = self
if let gridNode = gridNode {
grid.node.addChild(gridNode)
}
}
}
extension GridElemController where TSub: ElemToController {
convenience init(curModel: GridElem<TSub>, display: Bool) {
let node = ElemNode()
node.position = curModel.pos.toDisplay
self.init(
grid: GridController(curModel: curModel.grid, node: node),
pos: curModel.pos,
display: display
)
}
}
| af218ebc302f4a90cff6a22f16790f56 | 29.121212 | 82 | 0.603119 | false | false | false | false |
wwu-pi/md2-framework | refs/heads/master | de.wwu.md2.framework/res/resources/ios/lib/controller/validator/MD2DateRangeValidator.swift | apache-2.0 | 1 | //
// MD2DateRangeValidator.swift
// md2-ios-library
//
// Created by Christoph Rieger on 23.07.15.
// Copyright (c) 2015 Christoph Rieger. All rights reserved.
//
/**
Validator to check for a given date range.
*/
class MD2DateRangeValidator: MD2Validator {
/// Unique identification string.
let identifier: MD2String
/// Custom message to display.
var message: (() -> MD2String)?
/// Default message to display.
var defaultMessage: MD2String {
get {
return MD2String("The date must be between \(min.toString()) and \(max.toString())!")
}
}
/// Minimum allowed date.
let min: MD2Date
/// Maximum allowed date.
let max: MD2Date
/**
Default initializer.
:param: identifier The unique validator identifier.
:param: message Closure of the custom method to display.
:param: min The minimum date of a valid date.
:param: max The maximum date of a valid date.
*/
init(identifier: MD2String, message: (() -> MD2String)?, min: MD2Date, max: MD2Date) {
self.identifier = identifier
self.message = message
self.min = min
self.max = max
}
/**
Validate a value.
:param: value The value to check.
:return: Validation result
*/
func isValid(value: MD2Type) -> Bool {
if value is MD2Date
&& (value as! MD2Date).gte(min)
&& (value as! MD2Date).lte(max) {
return true
} else {
return false
}
}
/**
Return the message to display on wrong validation.
Use custom method if set or else use default message.
*/
func getMessage() -> MD2String {
if let _ = message {
return message!()
} else {
return defaultMessage
}
}
} | 273d624ad30e9b2ab215359a52569ec1 | 23.974026 | 97 | 0.558273 | false | false | false | false |
bfolder/Sweather | refs/heads/master | Sweather/Sweather.swift | mit | 1 | //
// Sweather.swift
//
// Created by Heiko Dreyer on 08/12/14.
// Copyright (c) 2014 boxedfolder.com. All rights reserved.
//
import Foundation
import CoreLocation
extension String {
func replace(_ string:String, replacement:String) -> String {
return self.replacingOccurrences(of: string,
with: replacement,
options: NSString.CompareOptions.literal,
range: nil)
}
func replaceWhitespace() -> String {
return self.replace(" ", replacement: "+")
}
}
open class Sweather {
public enum TemperatureFormat: String {
case Celsius = "metric"
case Fahrenheit = "imperial"
}
public enum Result {
case success(URLResponse?, NSDictionary?)
case Error(URLResponse?, NSError?)
public func data() -> NSDictionary? {
switch self {
case .success(_, let dictionary):
return dictionary
case .Error(_, _):
return nil
}
}
public func response() -> URLResponse? {
switch self {
case .success(let response, _):
return response
case .Error(let response, _):
return response
}
}
public func error() -> NSError? {
switch self {
case .success(_, _):
return nil
case .Error(_, let error):
return error
}
}
}
open var apiKey: String
open var apiVersion: String
open var language: String
open var temperatureFormat: TemperatureFormat
fileprivate struct Const {
static let basePath = "http://api.openweathermap.org/data/"
}
// MARK: -
// MARK: Initialization
public convenience init(apiKey: String) {
self.init(apiKey: apiKey, language: "en", temperatureFormat: .Fahrenheit, apiVersion: "2.5")
}
public convenience init(apiKey: String, temperatureFormat: TemperatureFormat) {
self.init(apiKey: apiKey, language: "en", temperatureFormat: temperatureFormat, apiVersion: "2.5")
}
public convenience init(apiKey: String, language: String, temperatureFormat: TemperatureFormat) {
self.init(apiKey: apiKey, language: language, temperatureFormat: temperatureFormat, apiVersion: "2.5")
}
public init(apiKey: String, language: String, temperatureFormat: TemperatureFormat, apiVersion: String) {
self.apiKey = apiKey
self.temperatureFormat = temperatureFormat
self.apiVersion = apiVersion
self.language = language
}
// MARK: -
// MARK: Retrieving current weather data
open func currentWeather(_ cityName: String, callback: @escaping (Result) -> ()) {
call("/weather?q=\(cityName.replaceWhitespace())", callback: callback)
}
open func currentWeather(_ coordinate: CLLocationCoordinate2D, callback: @escaping (Result) -> ()) {
let coordinateString = "lat=\(coordinate.latitude)&lon=\(coordinate.longitude)"
call("/weather?\(coordinateString)", callback: callback)
}
open func currentWeather(_ cityId: Int, callback: @escaping (Result) -> ()) {
call("/weather?id=\(cityId)", callback: callback)
}
// MARK: -
// MARK: Retrieving daily forecast
open func dailyForecast(_ cityName: String, callback: @escaping (Result) -> ()) {
call("/forecast/daily?q=\(cityName.replaceWhitespace())", callback: callback)
}
open func dailyForecast(_ coordinate: CLLocationCoordinate2D, callback: @escaping (Result) -> ()) {
call("/forecast/daily?lat=\(coordinate.latitude)&lon=\(coordinate.longitude)", callback: callback)
}
open func dailyForecast(_ cityId: Int, callback: @escaping (Result) -> ()) {
call("/forecast/daily?id=\(cityId)", callback: callback)
}
// MARK: -
// MARK: Retrieving forecast
open func forecast(_ cityName: String, callback: @escaping (Result) -> ()) {
call("/forecast?q=\(cityName.replaceWhitespace())", callback: callback)
}
open func forecast(_ coordinate: CLLocationCoordinate2D, callback:@escaping (Result) -> ()) {
call("/forecast?lat=\(coordinate.latitude)&lon=\(coordinate.longitude)", callback: callback)
}
open func forecast(_ cityId: Int, callback: @escaping (Result) ->()) {
call("/forecast?id=\(cityId)", callback: callback)
}
// MARK: -
// MARK: Retrieving city
open func findCity(_ cityName: String, callback: @escaping (Result) -> ()) {
call("/find?q=\(cityName.replaceWhitespace())", callback: callback)
}
open func findCity(_ coordinate: CLLocationCoordinate2D, callback: @escaping (Result) -> ()) {
call("/find?lat=\(coordinate.latitude)&lon=\(coordinate.longitude)", callback: callback)
}
// MARK: -
// MARK: Call the api
fileprivate func call(_ method: String, callback: @escaping (Result) -> ()) {
let url = Const.basePath + apiVersion + method + "&APPID=\(apiKey)&lang=\(language)&units=\(temperatureFormat.rawValue)"
let request = URLRequest(url: URL(string: url)!)
let currentQueue = OperationQueue.current
let task = URLSession.shared.dataTask(with: request, completionHandler: { data, response, error in
var error: NSError? = error as NSError?
var dictionary: NSDictionary?
if let data = data {
do {
dictionary = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? NSDictionary
} catch let e as NSError {
error = e
}
}
currentQueue?.addOperation {
var result = Result.success(response, dictionary)
if error != nil {
result = Result.Error(response, error)
}
callback(result)
}
})
task.resume()
}
}
| d7517f03c9afcb6a7cae5d8d8eef9333 | 33.227778 | 128 | 0.585295 | false | false | false | false |
IngmarStein/swift | refs/heads/master | validation-test/compiler_crashers_fixed/01170-getselftypeforcontainer.swift | apache-2.0 | 11 | // This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// RUN: not %target-swift-frontend %s -parse
class k<g>: d {
var f: g
init(f: g) {
l. d {
typealias j = je: Int -> Int = {
}
let d: Int = { c, b in
}(f, e)
}
class d {
func l<j where j: h, j: d>(l: j) {
}
func i(k: b) -> <j>(() -> j) -> b {
}
class j {
func y((Any, j))(v: (Any, AnyObject)) {
}
}
func w(j: () -> ()) {
}
class v {
l _ = w() {
}
}
func v<x>() -> (x, x -> x) -> x {
l y j s<q : l, y: l m y.n == q.n> {
}
o l {
}
y q<x> {
}
o n {
}
class r {
func s() -> p {
}
}
class w: r, n {
}
func b<c {
enum b {
}
}
}
class d<j : i, f : i where j.i == f> : e {
}
class d<j, f> {
}
protocol i {
}
protocol e {
}
protocol i : d { func d
| 42c0d37a754d6250ca2f281839ee4d21 | 15.147541 | 78 | 0.551269 | false | false | false | false |
S2dentik/Taylor | refs/heads/master | TaylorFramework/Modules/temper/Rules/CyclomaticComplexityRule.swift | mit | 4 | //
// CyclomaticComplexityRule.swift
// Temper
//
// Created by Mihai Seremet on 9/9/15.
// Copyright © 2015 Yopeso. All rights reserved.
//
final class CyclomaticComplexityRule: Rule {
let rule = "CyclomaticComplexity"
var priority: Int = 2 {
willSet {
if newValue > 0 {
self.priority = newValue
}
}
}
let externalInfoUrl = "http://phpmd.org/rules/codesize.html#cyclomaticcomplexity"
var limit: Int = 5 {
willSet {
if newValue > 0 {
self.limit = newValue
}
}
}
fileprivate let decisionalComponentTypes = [ComponentType.if, .while, .for, .case, .elseIf, .ternary, .nilCoalescing, .guard]
func checkComponent(_ component: Component) -> Result {
if component.type != ComponentType.function { return (true, nil, nil) }
let complexity = findComplexityForComponent(component) + 1
if complexity > limit {
let name = component.name ?? "unknown"
let message = formatMessage(name, value: complexity)
return (false, message, complexity)
}
return (true, nil, complexity)
}
func formatMessage(_ name: String, value: Int) -> String {
return "The method '\(name)' has a Cyclomatic Complexity of \(value). The allowed Cyclomatic Complexity is \(limit)"
}
fileprivate func findComplexityForComponent(_ component: Component) -> Int {
let complexity = decisionalComponentTypes.contains(component.type) ? 1 : 0
return component.components.map({ findComplexityForComponent($0) }).reduce(complexity, +)
}
}
| 31fc9c29afc8b4539a9b362ce7ea4cf1 | 33.854167 | 129 | 0.613867 | false | false | false | false |
Stanbai/MultiThreadBasicDemo | refs/heads/master | Operation/Swift/NSOperation/NSOperation/ImageLoadOperation.swift | mit | 1 | //
// ImageLoadOperation.swift
// NSOperation
//
// Created by Stan on 2017-07-24.
// Copyright © 2017 stan. All rights reserved.
//
import UIKit
class ImageLoadOperation: Operation {
let item: Item
var dataTask: URLSessionDataTask?
let complete: (UIImage?) -> Void
init(forItem: Item, execute: @escaping (UIImage?) -> Void) {
item = forItem
complete = execute
super.init()
}
/*
start: 所有并行的 Operations 都必须重写这个方法,然后在你想要执行的线程中手动调用这个方法。注意:任何时候都不能调用父类的start方法。
main: 在start方法中调用,但是注意要定义独立的自动释放池与别的线程区分开。
isExecuting: 是否执行中,需要实现KVO通知机制。
isFinished: 是否已完成,需要实现KVO通知机制。
isAsynchronous: 该方法默认返回 假 ,表示非并发执行。并发执行需要自定义并且返回 真。后面会根据这个返回值来决定是否并发。
*/
fileprivate var _executing : Bool = false
override var isExecuting: Bool {
get { return _executing }
set {
if newValue != _executing {
willChangeValue(forKey: "isExecuting")
_executing = newValue
didChangeValue(forKey: "isExecuting")
}
}
}
fileprivate var _finished : Bool = false
override var isFinished: Bool {
get { return _finished }
set {
if newValue != _finished {
willChangeValue(forKey: "isFinished")
_finished = newValue
didChangeValue(forKey: "isFinished")
}
}
}
override var isAsynchronous: Bool {
get {
return true
}
}
override func start() {
if !isCancelled {
isExecuting = true
isFinished = false
startOperation()
} else {
isFinished = true
}
if let url = item.imageUrl() {
let dataTask = URLSession.shared.dataTask(with: url, completionHandler: {[weak self](data, response, error) in
if let data = data {
let image = UIImage(data: data)
self?.endOperationWith(image: image)
} else {
self?.endOperationWith(image: nil)
}
})
dataTask.resume()
} else {
self.endOperationWith(image: nil)
}
}
override func cancel() {
if !isCancelled {
cancelOperation()
}
super.cancel()
completeOperation()
}
// MARK: - 自定义对外的方法
func startOperation() {
completeOperation()
}
func cancelOperation() {
dataTask?.cancel()
}
func completeOperation() {
if isExecuting && !isFinished {
isExecuting = false
isFinished = true
}
}
func endOperationWith(image: UIImage?) {
if !isCancelled {
complete(image)
completeOperation()
}
}
}
| 828fe37047dc8f45b9fdde19fc04aaaa | 23.663866 | 122 | 0.520954 | false | false | false | false |
meteochu/HanekeSwift | refs/heads/master | Haneke/CGSize+Swift.swift | apache-2.0 | 1 | //
// CGSize+Swift.swift
// Haneke
//
// Created by Oriol Blanc Gimeno on 09/09/14.
// Copyright (c) 2014 Haneke. All rights reserved.
//
import UIKit
extension CGSize {
func hnk_aspectFillSize(size: CGSize) -> CGSize {
let scaleWidth = size.width / self.width
let scaleHeight = size.height / self.height
let scale = max(scaleWidth, scaleHeight)
let resultSize = CGSize(width: self.width * scale, height: self.height * scale)
return CGSize(width: ceil(resultSize.width), height: ceil(resultSize.height))
}
func hnk_aspectFitSize(size: CGSize) -> CGSize {
let targetAspect = size.width / size.height
let sourceAspect = self.width / self.height
var resultSize = size
if (targetAspect > sourceAspect) {
resultSize.width = size.height * sourceAspect
}
else {
resultSize.height = size.width / sourceAspect
}
return CGSize(width: ceil(resultSize.width), height: ceil(resultSize.height))
}
}
| 23bfb1dee9fa46729c1b5be6c04dcdeb | 28.685714 | 87 | 0.635226 | false | false | false | false |
yonaskolb/XcodeGen | refs/heads/master | Sources/ProjectSpec/Dependency.swift | mit | 1 | import Foundation
import JSONUtilities
public struct Dependency: Equatable {
public static let removeHeadersDefault = true
public static let implicitDefault = false
public static let weakLinkDefault = false
public static let platformFilterDefault: PlatformFilter = .all
public var type: DependencyType
public var reference: String
public var embed: Bool?
public var codeSign: Bool?
public var removeHeaders: Bool = removeHeadersDefault
public var link: Bool?
public var implicit: Bool = implicitDefault
public var weakLink: Bool = weakLinkDefault
public var platformFilter: PlatformFilter = platformFilterDefault
public var platforms: Set<Platform>?
public var copyPhase: BuildPhaseSpec.CopyFilesSettings?
public init(
type: DependencyType,
reference: String,
embed: Bool? = nil,
codeSign: Bool? = nil,
link: Bool? = nil,
implicit: Bool = implicitDefault,
weakLink: Bool = weakLinkDefault,
platformFilter: PlatformFilter = platformFilterDefault,
platforms: Set<Platform>? = nil,
copyPhase: BuildPhaseSpec.CopyFilesSettings? = nil
) {
self.type = type
self.reference = reference
self.embed = embed
self.codeSign = codeSign
self.link = link
self.implicit = implicit
self.weakLink = weakLink
self.platformFilter = platformFilter
self.platforms = platforms
self.copyPhase = copyPhase
}
public enum PlatformFilter: String, Equatable {
case all
case iOS
case macOS
}
public enum CarthageLinkType: String {
case dynamic
case `static`
public static let `default` = dynamic
}
public enum DependencyType: Hashable {
case target
case framework
case carthage(findFrameworks: Bool?, linkType: CarthageLinkType)
case sdk(root: String?)
case package(product: String?)
case bundle
}
}
extension Dependency {
public var uniqueID: String {
switch type {
case .package(let product):
if let product = product {
return "\(reference)/\(product)"
} else {
return reference
}
default: return reference
}
}
}
extension Dependency: Hashable {
public func hash(into hasher: inout Hasher) {
hasher.combine(reference)
}
}
extension Dependency: JSONObjectConvertible {
public init(jsonDictionary: JSONDictionary) throws {
if let target: String = jsonDictionary.json(atKeyPath: "target") {
type = .target
reference = target
} else if let framework: String = jsonDictionary.json(atKeyPath: "framework") {
type = .framework
reference = framework
} else if let carthage: String = jsonDictionary.json(atKeyPath: "carthage") {
let findFrameworks: Bool? = jsonDictionary.json(atKeyPath: "findFrameworks")
let carthageLinkType: CarthageLinkType = (jsonDictionary.json(atKeyPath: "linkType") as String?).flatMap(CarthageLinkType.init(rawValue:)) ?? .default
type = .carthage(findFrameworks: findFrameworks, linkType: carthageLinkType)
reference = carthage
} else if let sdk: String = jsonDictionary.json(atKeyPath: "sdk") {
let sdkRoot: String? = jsonDictionary.json(atKeyPath: "root")
type = .sdk(root: sdkRoot)
reference = sdk
} else if let package: String = jsonDictionary.json(atKeyPath: "package") {
let product: String? = jsonDictionary.json(atKeyPath: "product")
type = .package(product: product)
reference = package
} else if let bundle: String = jsonDictionary.json(atKeyPath: "bundle") {
type = .bundle
reference = bundle
} else {
throw SpecParsingError.invalidDependency(jsonDictionary)
}
embed = jsonDictionary.json(atKeyPath: "embed")
codeSign = jsonDictionary.json(atKeyPath: "codeSign")
link = jsonDictionary.json(atKeyPath: "link")
if let bool: Bool = jsonDictionary.json(atKeyPath: "removeHeaders") {
removeHeaders = bool
}
if let bool: Bool = jsonDictionary.json(atKeyPath: "implicit") {
implicit = bool
}
if let bool: Bool = jsonDictionary.json(atKeyPath: "weak") {
weakLink = bool
}
if let platformFilterString: String = jsonDictionary.json(atKeyPath: "platformFilter"), let platformFilter = PlatformFilter(rawValue: platformFilterString) {
self.platformFilter = platformFilter
} else {
self.platformFilter = .all
}
if let platforms: [ProjectSpec.Platform] = jsonDictionary.json(atKeyPath: "platforms") {
self.platforms = Set(platforms)
}
if let object: JSONDictionary = jsonDictionary.json(atKeyPath: "copy") {
copyPhase = try BuildPhaseSpec.CopyFilesSettings(jsonDictionary: object)
}
}
}
extension Dependency: JSONEncodable {
public func toJSONValue() -> Any {
var dict: [String: Any?] = [
"embed": embed,
"codeSign": codeSign,
"link": link,
"platforms": platforms?.map(\.rawValue).sorted(),
"copy": copyPhase?.toJSONValue(),
]
if removeHeaders != Dependency.removeHeadersDefault {
dict["removeHeaders"] = removeHeaders
}
if implicit != Dependency.implicitDefault {
dict["implicit"] = implicit
}
if weakLink != Dependency.weakLinkDefault {
dict["weak"] = weakLink
}
switch type {
case .target:
dict["target"] = reference
case .framework:
dict["framework"] = reference
case .carthage(let findFrameworks, let linkType):
dict["carthage"] = reference
if let findFrameworks = findFrameworks {
dict["findFrameworks"] = findFrameworks
}
dict["linkType"] = linkType.rawValue
case .sdk:
dict["sdk"] = reference
case .package:
dict["package"] = reference
case .bundle:
dict["bundle"] = reference
}
return dict
}
}
extension Dependency: PathContainer {
static var pathProperties: [PathProperty] {
[
.string("framework"),
]
}
}
| eaf1364499f89d3ca18a5a7faa834054 | 32.323232 | 165 | 0.607305 | false | false | false | false |
chrisjmendez/swift-exercises | refs/heads/master | Music/Apple/iTunesQueryAdvanced/iTunesQueryAdvanced/APIController.swift | mit | 1 | //
// APIController.swift
// iTunesQueryAdvanced
//
// Created by tommy trojan on 5/20/15.
// Copyright (c) 2015 Chris Mendez. All rights reserved.
//
import Foundation
protocol APIControllerProtocol {
func didReceiveAPIResults(results: NSArray)
}
class APIController{
var delegate: APIControllerProtocol?
func searchItunesFor(searchTerm: String, searchCategory: String) {
// The iTunes API wants multiple terms separated by + symbols, so replace spaces with + signs
let itunesSearchTerm = searchTerm.stringByReplacingOccurrencesOfString(" ", withString: "+", options: NSStringCompareOptions.CaseInsensitiveSearch, range: nil)
// Now escape anything else that isn't URL-friendly
if let escapedSearchTerm = itunesSearchTerm.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding) {
let urlPath = "http://itunes.apple.com/search?term=\(escapedSearchTerm)&media=\(searchCategory)"
let url = NSURL(string: urlPath)
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithURL(url!, completionHandler: {data, response, error -> Void in
print("\(escapedSearchTerm) query complete.")
if(error != nil) {
// If there is an error in the web request, print it to the console
print(error!.localizedDescription)
}
var err: NSError?
let jsonResult = (try! NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers)) as! NSDictionary
if(err != nil) {
// If there is an error parsing JSON, print it to the console
print("JSON Error \(err!.localizedDescription)")
}
//Trigger the delegate once the data has been parsed
if let results: NSArray = jsonResult["results"] as? NSArray {
self.delegate?.didReceiveAPIResults(results)
}
})
task.resume()
}
}
}
extension String {
/// Percent escape value to be added to a URL query value as specified in RFC 3986
/// - returns: Return precent escaped string.
func stringByReplacingSpaceWithPlusEncodingForQueryValue() -> String? {
let term = self.stringByReplacingOccurrencesOfString(" ", withString: "+", options: NSStringCompareOptions.CaseInsensitiveSearch, range: nil)
// Anything which is not URL-friendly is escaped
let escapedTerm = term.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)!
return escapedTerm
}
}
| 32943acfb2797c67dc86c34fc7b66567 | 42.790323 | 167 | 0.642357 | false | false | false | false |
XCEssentials/UniFlow | refs/heads/master | Sources/5_MutationDecriptors/2-TransitionFrom.swift | mit | 1 | /*
MIT License
Copyright (c) 2016 Maxim Khatskevich ([email protected])
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
import Foundation /// for access to `Date` type
//---
public
struct TransitionFrom<Old: SomeState>: SomeMutationDecriptor
{
public
let oldState: Old
public
let newState: SomeStateBase
public
let timestamp: Date
public
init?(
from report: Storage.HistoryElement
) {
guard
let transition = Transition(from: report),
let oldState = transition.oldState as? Old
else
{
return nil
}
//---
self.oldState = oldState
self.newState = transition.newState
self.timestamp = report.timestamp
}
}
| d3842e0bf8f8cbb078e08a9bf9604345 | 28 | 79 | 0.696329 | false | false | false | false |
MakeSchool/TripPlanner | refs/heads/master | ArgoTests/Tests/DecodedTests.swift | mit | 9 | import XCTest
import Argo
class DecodedTests: XCTestCase {
func testDecodedSuccess() {
let user: Decoded<User> = decode(JSONFromFile("user_with_email")!)
switch user {
case let .Success(x): XCTAssert(user.description == "Success(\(x))")
default: XCTFail("Unexpected Case Occurred")
}
}
func testDecodedWithError() {
let user: Decoded<User> = decode(JSONFromFile("user_with_bad_type")!)
switch user.error {
case .Some: XCTAssert(true)
case .None: XCTFail("Unexpected Success")
}
}
func testDecodedWithNoError() {
let user: Decoded<User> = decode(JSONFromFile("user_with_email")!)
switch user.error {
case .Some: XCTFail("Unexpected Error Occurred")
case .None: XCTAssert(true)
}
}
func testDecodedTypeMissmatch() {
let user: Decoded<User> = decode(JSONFromFile("user_with_bad_type")!)
switch user {
case let .Failure(.TypeMismatch(expected, actual)): XCTAssert(user.description == "Failure(TypeMismatch(Expected \(expected), got \(actual)))")
default: XCTFail("Unexpected Case Occurred")
}
}
func testDecodedMissingKey() {
let user: Decoded<User> = decode(JSONFromFile("user_without_key")!)
switch user {
case let .Failure(.MissingKey(s)): XCTAssert(user.description == "Failure(MissingKey(\(s)))")
default: XCTFail("Unexpected Case Occurred")
}
}
func testDecodedCustomError() {
let customError: Decoded<Dummy> = decode([:])
switch customError {
case let .Failure(e): XCTAssert(e.description == "Custom(My Custom Error)")
default: XCTFail("Unexpected Case Occurred")
}
}
func testDecodedMaterializeSuccess() {
let user: Decoded<User> = decode(JSONFromFile("user_with_email")!)
let materialized = materialize { user.value! }
switch materialized {
case let .Success(x): XCTAssert(user.description == "Success(\(x))")
default: XCTFail("Unexpected Case Occurred")
}
}
func testDecodedMaterializeFailure() {
let error = NSError(domain: "com.thoughtbot.Argo", code: 0, userInfo: nil)
let materialized = materialize { throw error }
switch materialized {
case let .Failure(e): XCTAssert(e.description == "Custom(\(error.description))")
default: XCTFail("Unexpected Case Occurred")
}
}
func testDecodedDematerializeSuccess() {
let user: Decoded<User> = decode(JSONFromFile("user_with_email")!)
do {
try user.dematerialize()
XCTAssert(true)
} catch {
XCTFail("Unexpected Error Occurred")
}
}
func testDecodedDematerializeTypeMismatch() {
let user: Decoded<User> = decode(JSONFromFile("user_with_bad_type")!)
do {
try user.dematerialize()
XCTFail("Unexpected Success")
} catch DecodeError.TypeMismatch {
XCTAssert(true)
} catch DecodeError.MissingKey {
XCTFail("Unexpected Error Occurred")
} catch {
XCTFail("Unexpected Error Occurred")
}
}
func testDecodedDematerializeMissingKey() {
let user: Decoded<User> = decode(JSONFromFile("user_without_key")!)
do {
try user.dematerialize()
XCTFail("Unexpected Success")
} catch DecodeError.MissingKey {
XCTAssert(true)
} catch DecodeError.TypeMismatch {
XCTFail("Unexpected Error Occurred")
} catch {
XCTFail("Unexpected Error Occurred")
}
}
}
private struct Dummy: Decodable {
static func decode(json: JSON) -> Decoded<Dummy> {
return .Failure(.Custom("My Custom Error"))
}
}
| 712382612626a5765537f0c738060240 | 27.288 | 147 | 0.658654 | false | true | false | false |
jsslai/Action | refs/heads/master | Carthage/Checkouts/RxSwift/Tests/RxCocoaTests/ControlEventTests.swift | mit | 3 | //
// ControlEventTests.swift
// RxTests
//
// Created by Krunoslav Zaher on 12/6/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
import RxCocoa
import RxSwift
import XCTest
class ControlEventTests : RxTest {
func testObservingIsAlwaysHappeningOnMainThread() {
let hotObservable = MainThreadPrimitiveHotObservable<Int>()
var observedOnMainThread = false
let expectSubscribeOffMainThread = expectation(description: "Did subscribe off main thread")
let controlProperty = ControlEvent(events: Observable.deferred { () -> Observable<Int> in
XCTAssertTrue(isMainThread())
observedOnMainThread = true
return hotObservable.asObservable()
})
doOnBackgroundThread {
let d = controlProperty.asObservable().subscribe { n in
}
let d2 = controlProperty.subscribe { n in
}
doOnMainThread {
d.dispose()
d2.dispose()
expectSubscribeOffMainThread.fulfill()
}
}
waitForExpectations(timeout: 1.0) { error in
XCTAssertNil(error)
}
XCTAssertTrue(observedOnMainThread)
}
}
| 3f2273c046dd4c2d134b221bb773cc19 | 25.333333 | 100 | 0.619462 | false | true | false | false |
ricardorauber/iOS-Swift | refs/heads/master | iOS-Swift.playground/Pages/Key Value Observing.xcplaygroundpage/Contents.swift | mit | 1 | //: ## Key Value Observing
//: ----
//: [Previous](@previous)
import Foundation
//: Contexts
private var PersonNameObserverContext = 0
private var PersonAgeObserverContext = 0
//: Observable Properties
class Person: NSObject {
dynamic var name: String
dynamic var age: Int
init(withName name: String, age: Int) {
self.name = name
self.age = age
}
}
//: Handle observing
class People: NSObject {
let manager: Person
init(withManager manager: Person) {
self.manager = manager
super.init()
self.manager.addObserver(self, forKeyPath: "name", options: [.New, .Old], context: &PersonNameObserverContext)
self.manager.addObserver(self, forKeyPath: "age", options: [.New, .Old], context: &PersonAgeObserverContext)
}
override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
switch(context) {
case &PersonNameObserverContext:
let oldName = change!["old"]!
let newName = change!["new"]!
print("Manager name was \(oldName) and now is \(newName)")
case &PersonAgeObserverContext:
let oldAge = change!["old"]!
let newAge = change!["new"]!
print("Manager age was \(oldAge) and now is \(newAge)")
default:
print("Unhandled KVO: \(keyPath)")
}
}
deinit {
self.manager.removeObserver(self, forKeyPath: "name")
self.manager.removeObserver(self, forKeyPath: "age")
}
}
let manager = Person(withName: "John", age: 40)
let team = People(withManager: manager)
manager.name = "Jack"
manager.age = 45
//: [Next](@next)
| 3db6b30c73b24438dd3edce12765675e | 25.984848 | 157 | 0.613139 | false | false | false | false |
NickAger/elm-slider | refs/heads/master | Modules/HTTP/Sources/HTTP/Middleware/SessionMiddleware/SessionMiddleware.swift | mit | 5 | private var uuidCount = 0
private func uuid() -> String {
uuidCount += 1
return String(uuidCount)
}
public struct SessionMiddleware: Middleware {
public static let cookieName = "zewo-session"
public let storage: SessionStorage
public init(storage: SessionStorage = SessionInMemoryStorage()) {
self.storage = storage
}
public func respond(to request: Request, chainingTo chain: Responder) throws -> Response {
var request = request
let (cookie, createdCookie) = getOrCreateCookie(request: request)
// ensure that we have a session and add it to the request
let session = getExistingSession(cookie: cookie) ?? createNewSession(cookie: cookie)
add(session: session, toRequest: &request)
// at this point, we have a cookie and a session. call the rest of the chain!
var response = try chain.respond(to: request)
// if no cookie was originally in the request, we should put it in the response
if createdCookie {
let cookie = AttributedCookie(name: cookie.name, value: cookie.value)
response.cookies.insert(cookie)
}
// done! response have the session cookie and request has the session
return response
}
private func getOrCreateCookie(request: Request) -> (Cookie, Bool) {
// if request contains a session cookie, return that cookie
if let requestCookie = request.cookies.filter({ $0.name == SessionMiddleware.cookieName }).first {
return (requestCookie, false)
}
// otherwise, create a new cookie
let cookie = Cookie(name: SessionMiddleware.cookieName, value: uuid())
return (cookie, true)
}
private func getExistingSession(cookie: Cookie) -> Session? {
return storage.fetchSession(key: cookie.extendedHash)
}
private func createNewSession(cookie: Cookie) -> Session {
// where cookie.value is the cookie uuid
let session = Session(token: cookie.value)
storage.save(key: cookie.extendedHash, session: session)
return session
}
private func add(session: Session, toRequest request: inout Request) {
request.storage[SessionMiddleware.cookieName] = session
}
}
extension Request {
// TODO: Add a Quark compiler flag and then make different versions Session/Session?
public var session: Session {
guard let session = storage[SessionMiddleware.cookieName] as? Session else {
fatalError("SessionMiddleware should be applied to the chain. Quark guarantees it, so this error should never happen within Quark.")
}
return session
}
}
extension Cookie {
public typealias Hash = Int
public var extendedHash: Hash {
return "\(name)+\(value)".hashValue
}
}
| 0c95c71950876c20d1d76b9fc32d9439 | 34.721519 | 144 | 0.669029 | false | false | false | false |
kasei/kineo | refs/heads/master | Sources/Kineo/SPARQL/SPARQLTSV.swift | mit | 1 | //
// SPARQLTSV.swift
// Kineo
//
// Created by Gregory Todd Williams on 4/24/18.
//
import Foundation
import SPARQLSyntax
public struct SPARQLTSVSerializer<T: ResultProtocol> : SPARQLSerializable where T.TermType == Term {
typealias ResultType = T
public let canonicalMediaType = "text/tab-separated-values"
public var serializesTriples = false
public var serializesBindings = true
public var serializesBoolean = false
public var acceptableMediaTypes: [String] { return [canonicalMediaType] }
public init() {
}
public func serialize<R: Sequence, T: Sequence>(_ results: QueryResult<R, T>) throws -> Data where R.Element == SPARQLResultSolution<Term>, T.Element == Triple {
var d = Data()
switch results {
case .boolean(_):
throw SerializationError.encodingError("Boolean results cannot be serialized in SPARQL-TSV")
case let .bindings(vars, seq):
let head = vars.map { "?\($0)" }.joined(separator: "\t")
guard let headData = head.data(using: .utf8) else {
throw SerializationError.encodingError("Failed to encode TSV header as utf-8")
}
d.append(headData)
d.append(0x0a)
for result in seq {
let terms = vars.map { result[$0] }
let strings = try terms.map { (t) -> String in
if let t = t {
guard let termString = t.tsvString else {
throw SerializationError.encodingError("Failed to encode term as utf-8: \(t)")
}
return termString
} else {
return ""
}
}
let line = strings.joined(separator: "\t")
guard let lineData = line.data(using: .utf8) else {
throw SerializationError.encodingError("Failed to encode TSV line as utf-8")
}
d.append(lineData)
d.append(0x0a)
}
return d
case .triples(_):
throw SerializationError.encodingError("RDF triples cannot be serialized in SPARQL-TSV")
}
}
}
private extension String {
var tsvStringEscaped: String {
var escaped = ""
for c in self {
switch c {
case Character(UnicodeScalar(0x22)):
escaped += "\\\""
case Character(UnicodeScalar(0x5c)):
escaped += "\\\\"
case Character(UnicodeScalar(0x09)):
escaped += "\\t"
case Character(UnicodeScalar(0x0a)):
escaped += "\\n"
default:
escaped.append(c)
}
}
return escaped
}
}
private extension Term {
var tsvString: String? {
switch self.type {
case .iri:
return "<\(value.turtleIRIEscaped)>"
case .blank:
return "_:\(self.value)"
case .language(let l):
return "\"\(value.tsvStringEscaped)\"@\(l)"
case .datatype(.integer):
return "\(Int(self.numericValue))"
case .datatype(.string):
return "\"\(value.tsvStringEscaped)\""
case .datatype(let dt):
return "\"\(value.tsvStringEscaped)\"^^<\(dt.value)>"
}
}
}
public struct SPARQLTSVParser : SPARQLParsable {
public let mediaTypes = Set(["text/tab-separated-values"])
var encoding: String.Encoding
var parser: RDFParserCombined
public init(encoding: String.Encoding = .utf8, produceUniqueBlankIdentifiers: Bool = true) {
self.encoding = encoding
self.parser = RDFParserCombined(base: "http://example.org/", produceUniqueBlankIdentifiers: produceUniqueBlankIdentifiers)
}
public func parse(_ data: Data) throws -> QueryResult<[SPARQLResultSolution<Term>], [Triple]> {
guard let s = String(data: data, encoding: encoding) else {
throw SerializationError.encodingError("Failed to decode SPARQL/TSV data as utf-8")
}
let lines = s.split(separator: "\n")
guard let header = lines.first else {
throw SerializationError.parsingError("SPARQL/TSV data missing header line")
}
let names = header.split(separator: "\t").map { String($0.dropFirst()) }
var results = [SPARQLResultSolution<Term>]()
for line in lines.dropFirst() {
let values = line.split(separator: "\t", omittingEmptySubsequences: false)
let terms = try values.map { try parseTerm(String($0)) }
let pairs = zip(names, terms).compactMap { (name, term) -> (String, Term)? in
guard let term = term else {
return nil
}
return (name, term)
}
let d = Dictionary(uniqueKeysWithValues: pairs)
let r = SPARQLResultSolution<Term>(bindings: d)
results.append(r)
}
return QueryResult.bindings(names, results)
}
private func parseTerm(_ string: String) throws -> Term? {
guard !string.isEmpty else {
return nil
}
var term : Term! = nil
let ttl = "<> <> \(string) .\n"
try parser.parse(string: ttl, syntax: .turtle) { (s,p,o) in
term = o
}
return term
}
}
| 8623172c8bfa86212932d7e8794c139a | 34.934641 | 165 | 0.548017 | false | false | false | false |
iosdevelopershq/code-challenges | refs/heads/master | CodeChallenge/Challenges/TwoSum/Entries/Aranasaurus.swift | mit | 1 | //
// Aranasaurus.swift
// CodeChallenge
//
// Created by Ryan Arana on 10/31/15.
// Copyright © 2015 iosdevelopers. All rights reserved.
//
import Foundation
let aranasaurusTwoSumEntry = CodeChallengeEntry<TwoSumChallenge>(name: "Aranasaurus") { input in
var max = Datum(0, 0)
let mid = input.target / 2
for (i, number) in input.numbers.enumerated() {
guard number >= 0 && number <= input.target && number >= mid else { continue }
if number > max.number {
if let diffIndex = input.numbers.index(of: input.target - number) {
return (diffIndex + 1, i + 1)
}
max = Datum(i, number)
}
}
return .none
}
private struct Datum {
let index: Int
let number: Int
init(_ index: Int, _ number: Int) {
self.index = index
self.number = number
}
}
| a6ab132a66692da50cd7f59e7ffeec49 | 22.605263 | 96 | 0.569677 | false | false | false | false |
deltaDNA/ios-sdk | refs/heads/master | Example/tvOS Example/ViewController.swift | apache-2.0 | 1 | //
// Copyright (c) 2016 deltaDNA Ltd. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import UIKit
import DeltaDNA
class ViewController: UIViewController, DDNAImageMessageDelegate {
@IBOutlet weak var sdkVersion: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
self.sdkVersion.text = DDNA_SDK_VERSION;
DDNASDK.setLogLevel(.debug)
DDNASDK.sharedInstance().clientVersion = "tvOS Example v1.0"
DDNASDK.sharedInstance().hashSecret = "KmMBBcNwStLJaq6KsEBxXc6HY3A4bhGw"
DDNASDK.sharedInstance().start(
withEnvironmentKey: "55822530117170763508653519413932",
collectURL: "https://collect2010stst.deltadna.net/collect/api",
engageURL: "https://engage2010stst.deltadna.net"
)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func onSimpleEvent(_ sender: AnyObject) {
DDNASDK.sharedInstance().recordEvent(withName: "achievement", eventParams: [
"achievementName" : "Sunday Showdown Tournament Win",
"achievementID" : "SS-2014-03-02-01",
"reward" : [
"rewardName" : "Medal",
"rewardProducts" : [
"items" : [
[
"item" : [
"itemAmount" : 1,
"itemName" : "Sunday Showdown Medal",
"itemType" : "Victory Badge"
]
]
],
"virtualCurrencies" : [
[
"virtualCurrency" : [
"virtualCurrencyAmount" : 20,
"virtualCurrencyName" : "VIP Points",
"virtualCurrencyType" : "GRIND"
]
]
],
"realCurrency" : [
"realCurrencyAmount" : 5000,
"realCurrencyType" : "USD"
]
]
]
])
}
@IBAction func onEngage(_ sender: AnyObject) {
let engagement = DDNAEngagement(decisionPoint: "gameLoaded")!
engagement.setParam(4 as NSNumber, forKey: "userLevel")
engagement.setParam(1000 as NSNumber, forKey: "experience")
engagement.setParam("Disco Volante" as NSString, forKey: "missionName")
DDNASDK.sharedInstance().request(engagement, engagementHandler:{ (response)->() in
if response?.json != nil {
print("Engagement returned: \(String(describing: response?.json["parameters"]))")
} else {
print("Engagement failed: \(String(describing: response?.error))")
}
})
}
@IBAction func onImageMessage(_ sender: AnyObject) {
let engagement = DDNAEngagement(decisionPoint: "imageMessage");
DDNASDK.sharedInstance().request(engagement, engagementHandler:{ (response)->() in
if let imageMessage = DDNAImageMessage(engagement: response, delegate: self) {
imageMessage.fetchResources()
}
})
}
@IBAction func onUploadEvents(_ sender: AnyObject) {
DDNASDK.sharedInstance().upload();
}
func onDismiss(_ imageMessage: DDNAImageMessage!, name: String!) {
print("Image message dismissed by \(name)")
}
func onActionImageMessage(_ imageMessage: DDNAImageMessage!, name: String!, type: String!, value: String!) {
print("Image message actioned by \(name) with \(type) and \(value)")
}
func didReceiveResources(for imageMessage: DDNAImageMessage!) {
print("Image message received resources")
imageMessage.show(fromRootViewController: self)
}
func didFailToReceiveResources(for imageMessage: DDNAImageMessage!, withReason reason: String!) {
print("Image message failed to receive resources: \(reason)")
}
}
| f4e34523780fcff6a93fd44c5bff368b | 36.896825 | 112 | 0.564607 | false | false | false | false |
brentsimmons/Evergreen | refs/heads/ios-candidate | iOS/MasterFeed/Cell/MasterFeedTableViewIdentifier.swift | mit | 1 | //
// MasterFeedTableViewIdentifier.swift
// NetNewsWire-iOS
//
// Created by Maurice Parker on 6/3/20.
// Copyright © 2020 Ranchero Software. All rights reserved.
//
import Foundation
import Account
import RSTree
final class MasterFeedTableViewIdentifier: NSObject, NSCopying {
let feedID: FeedIdentifier?
let containerID: ContainerIdentifier?
let parentContainerID: ContainerIdentifier?
let isEditable: Bool
let isPsuedoFeed: Bool
let isFolder: Bool
let isWebFeed: Bool
let nameForDisplay: String
let url: String?
let unreadCount: Int
let childCount: Int
var account: Account? {
if isFolder, let parentContainerID = parentContainerID {
return AccountManager.shared.existingContainer(with: parentContainerID) as? Account
}
if isWebFeed, let feedID = feedID {
return (AccountManager.shared.existingFeed(with: feedID) as? WebFeed)?.account
}
return nil
}
init(node: Node, unreadCount: Int) {
let feed = node.representedObject as! Feed
self.feedID = feed.feedID
self.containerID = (node.representedObject as? Container)?.containerID
self.parentContainerID = (node.parent?.representedObject as? Container)?.containerID
self.isEditable = !(node.representedObject is PseudoFeed)
self.isPsuedoFeed = node.representedObject is PseudoFeed
self.isFolder = node.representedObject is Folder
self.isWebFeed = node.representedObject is WebFeed
self.nameForDisplay = feed.nameForDisplay
if let webFeed = node.representedObject as? WebFeed {
self.url = webFeed.url
} else {
self.url = nil
}
self.unreadCount = unreadCount
self.childCount = node.numberOfChildNodes
}
override func isEqual(_ object: Any?) -> Bool {
guard let otherIdentifier = object as? MasterFeedTableViewIdentifier else { return false }
if self === otherIdentifier { return true }
return feedID == otherIdentifier.feedID && parentContainerID == otherIdentifier.parentContainerID
}
override var hash: Int {
var hasher = Hasher()
hasher.combine(feedID)
hasher.combine(parentContainerID)
return hasher.finalize()
}
func copy(with zone: NSZone? = nil) -> Any {
return self
}
}
| 864ca78a8dc0975923f00fb9a7944813 | 26.461538 | 99 | 0.748833 | false | false | false | false |
andreipitis/ASPVideoPlayer | refs/heads/master | Example/ASPVideoPlayer/PlayerViewController.swift | mit | 1 | //
// PlayerViewController.swift
// ASPVideoPlayer
//
// Created by Andrei-Sergiu Pițiș on 09/12/2016.
// Copyright © 2016 CocoaPods. All rights reserved.
//
import UIKit
import ASPVideoPlayer
import AVFoundation
class PlayerViewController: UIViewController {
@IBOutlet weak var containerView: UIView!
@IBOutlet weak var videoPlayerBackgroundView: UIView!
@IBOutlet weak var videoPlayer: ASPVideoPlayer!
let firstLocalVideoURL = Bundle.main.url(forResource: "video", withExtension: "mp4")
let secondLocalVideoURL = Bundle.main.url(forResource: "video2", withExtension: "mp4")
let firstNetworkURL = URL(string: "http://devimages.apple.com/iphone/samples/bipbop/bipbopall.m3u8")
let secondNetworkURL = URL(string: "http://www.easy-fit.ae/wp-content/uploads/2014/09/WebsiteLoop.mp4")
override func viewDidLoad() {
super.viewDidLoad()
let firstAsset = AVURLAsset(url: firstLocalVideoURL!)
let secondAsset = AVURLAsset(url: secondLocalVideoURL!)
let thirdAsset = AVURLAsset(url: firstNetworkURL!)
let fourthAsset = AVURLAsset(url: secondNetworkURL!)
// videoPlayer.videoURLs = [firstLocalVideoURL!, secondLocalVideoURL!, firstNetworkURL!, secondNetworkURL!]
videoPlayer.videoAssets = [firstAsset, secondAsset, thirdAsset, fourthAsset]
// videoPlayer.configuration = ASPVideoPlayer.Configuration(videoGravity: .aspectFit, shouldLoop: true, startPlayingWhenReady: true, controlsInitiallyHidden: true, allowBackgroundPlay: true)
videoPlayer.resizeClosure = { [unowned self] isExpanded in
self.rotate(isExpanded: isExpanded)
}
videoPlayer.delegate = self
}
override var prefersStatusBarHidden: Bool {
return true
}
var previousConstraints: [NSLayoutConstraint] = []
func rotate(isExpanded: Bool) {
let views: [String:Any] = ["videoPlayer": videoPlayer as Any,
"backgroundView": videoPlayerBackgroundView as Any]
var constraints: [NSLayoutConstraint] = []
if isExpanded == false {
self.containerView.removeConstraints(self.videoPlayer.constraints)
self.view.addSubview(self.videoPlayerBackgroundView)
self.view.addSubview(self.videoPlayer)
self.videoPlayer.frame = self.containerView.frame
self.videoPlayerBackgroundView.frame = self.containerView.frame
let padding = (self.view.bounds.height - self.view.bounds.width) / 2.0
var bottomPadding: CGFloat = 0
if #available(iOS 11.0, *) {
if self.view.safeAreaInsets != .zero {
bottomPadding = self.view.safeAreaInsets.bottom
}
}
let metrics: [String:Any] = ["padding":padding,
"negativePaddingAdjusted":-(padding - bottomPadding),
"negativePadding":-padding]
constraints.append(contentsOf:
NSLayoutConstraint.constraints(withVisualFormat: "H:|-(negativePaddingAdjusted)-[videoPlayer]-(negativePaddingAdjusted)-|",
options: [],
metrics: metrics,
views: views))
constraints.append(contentsOf:
NSLayoutConstraint.constraints(withVisualFormat: "V:|-(padding)-[videoPlayer]-(padding)-|",
options: [],
metrics: metrics,
views: views))
constraints.append(contentsOf:
NSLayoutConstraint.constraints(withVisualFormat: "H:|-(negativePadding)-[backgroundView]-(negativePadding)-|",
options: [],
metrics: metrics,
views: views))
constraints.append(contentsOf:
NSLayoutConstraint.constraints(withVisualFormat: "V:|-(padding)-[backgroundView]-(padding)-|",
options: [],
metrics: metrics,
views: views))
self.view.addConstraints(constraints)
} else {
self.view.removeConstraints(self.previousConstraints)
let targetVideoPlayerFrame = self.view.convert(self.videoPlayer.frame, to: self.containerView)
let targetVideoPlayerBackgroundViewFrame = self.view.convert(self.videoPlayerBackgroundView.frame, to: self.containerView)
self.containerView.addSubview(self.videoPlayerBackgroundView)
self.containerView.addSubview(self.videoPlayer)
self.videoPlayer.frame = targetVideoPlayerFrame
self.videoPlayerBackgroundView.frame = targetVideoPlayerBackgroundViewFrame
constraints.append(contentsOf:
NSLayoutConstraint.constraints(withVisualFormat: "H:|[videoPlayer]|",
options: [],
metrics: nil,
views: views))
constraints.append(contentsOf:
NSLayoutConstraint.constraints(withVisualFormat: "V:|[videoPlayer]|",
options: [],
metrics: nil,
views: views))
constraints.append(contentsOf:
NSLayoutConstraint.constraints(withVisualFormat: "H:|[backgroundView]|",
options: [],
metrics: nil,
views: views))
constraints.append(contentsOf:
NSLayoutConstraint.constraints(withVisualFormat: "V:|[backgroundView]|",
options: [],
metrics: nil,
views: views))
self.containerView.addConstraints(constraints)
}
self.previousConstraints = constraints
UIView.animate(withDuration: 0.25, delay: 0.0, options: [], animations: {
self.videoPlayer.transform = isExpanded == true ? .identity : CGAffineTransform(rotationAngle: .pi / 2.0)
self.videoPlayerBackgroundView.transform = isExpanded == true ? .identity : CGAffineTransform(rotationAngle: .pi / 2.0)
self.view.layoutIfNeeded()
})
}
}
extension PlayerViewController: ASPVideoPlayerViewDelegate {
func startedVideo() {
print("Started video")
}
func stoppedVideo() {
print("Stopped video")
}
func newVideo() {
print("New Video")
}
func readyToPlayVideo() {
print("Ready to play video")
}
func playingVideo(progress: Double) {
// print("Playing: \(progress)")
}
func pausedVideo() {
print("Paused Video")
}
func finishedVideo() {
print("Finished Video")
}
func seekStarted() {
print("Seek started")
}
func seekEnded() {
print("Seek ended")
}
func error(error: Error) {
print("Error: \(error)")
}
func willShowControls() {
print("will show controls")
}
func didShowControls() {
print("did show controls")
}
func willHideControls() {
print("will hide controls")
}
func didHideControls() {
print("did hide controls")
}
}
| 175a6f3429621386feb6fe841c084e21 | 37.743842 | 205 | 0.555499 | false | false | false | false |
Nyx0uf/MPDRemote | refs/heads/master | src/iOS/controllers/NYXNavigationController.swift | mit | 1 | // NYXNavigationController.swift
// Copyright (c) 2017 Nyx0uf
//
// 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
final class NYXNavigationController : UINavigationController
{
override var shouldAutorotate: Bool
{
if let topViewController = self.topViewController
{
return topViewController.shouldAutorotate
}
return false
}
override var supportedInterfaceOrientations: UIInterfaceOrientationMask
{
if let topViewController = self.topViewController
{
return topViewController.supportedInterfaceOrientations
}
return .all
}
override var preferredInterfaceOrientationForPresentation: UIInterfaceOrientation
{
if let topViewController = self.topViewController
{
return topViewController.preferredInterfaceOrientationForPresentation
}
return .portrait
}
override var preferredStatusBarStyle: UIStatusBarStyle
{
if let presentedViewController = self.presentedViewController
{
return presentedViewController.preferredStatusBarStyle
}
if let topViewController = self.topViewController
{
return topViewController.preferredStatusBarStyle
}
return .default
}
}
| 1edbc4a096d483c438255659fc9fa5dd | 31.238806 | 82 | 0.785185 | false | false | false | false |
sffernando/CopyItems | refs/heads/master | CPKingFirsher/CPKingFirsher/Resource/Core/Image.swift | mit | 1 | //
// Image.swift
// CPKingFirsher
//
// Created by koudai on 2016/12/8.
// Copyright © 2016年 fernando. All rights reserved.
//
import Foundation
#if os(macOS)
import AppKit
private var imagesKey: Void?
private var durationKey: Void?
#else
import UIKit
import MobileCoreServices
private var imageSourceKey: Void?
private var animatedImageDataKey: Void?
#endif
import ImageIO
import CoreGraphics
#if !os(watchOS)
import Accelerate
import CoreImage
#endif
// MARK: image properties
extension KingFisher where Base: Image {
#if os(macOS)
var cgImage: CGImage? {
return base.cgImage(forProposedRect: nil, context: nil, hints: nil)
}
var scale: CFloat {
return 1.0
}
fileprivate(set) var images: [Image]? {
get {
return objc_getAssociatedObject(base, &imagesKey) as? [Image]
}
set {
objc_setAssociatedObject(base, &imagesKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
fileprivate(set) var duration: TimeInterval {
get {
objc_getAssociatedObject(base, &durationKey) as? TimeInterval ?? 0.0
}
set {
objc_setAssociatedObject(base, &durationKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
var size: CGSize {
return base.representations.reduce(CGSize.zero, { size, rep in
return CGSize(width: max(size.width, CGFloat(rep.pixelsWide)), height: max(size.height, CGFloat(rep.pixelsHigh)))
})
}
#else
var cgImage: CGImage? {
return base.cgImage
}
var scale: CGFloat {
return base.scale
}
var images: [Image]? {
return base.images;
}
var duration: TimeInterval {
return base.duration
}
fileprivate(set) var imageSource: ImageSource? {
get {
return objc_getAssociatedObject(base, &imageSourceKey) as? ImageSource
}
set {
objc_setAssociatedObject(base, &imageSourceKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
fileprivate(set) var animatedImageData: Data? {
get {
return objc_getAssociatedObject(base, &animatedImageDataKey) as? Data
}
set {
objc_setAssociatedObject(base, &animatedImageDataKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
var size: CGSize {
return base.size
}
#endif
}
// MARK: Image Conversion
extension KingFisher where Base: Image {
#if os(macOS)
static func image(cgImage: CGImage, scale: CGFloat, refImage: Image?) -> Image {
return Image(cgImage: cgImage, size: CGSize.zero)
}
/**
Normalize the image. This method does nothing in OS X.
- returns: The image itself.
*/
public var normalized: Image {
return base
}
static func animated(with images: [Image], forDuration forDurationduration: TimeInterval) -> Image? {
return nil
}
#else
static func image(cgImage: CGImage, scale: CGFloat, refImage: Image?) -> Image {
if let refImage = refImage {
return Image(cgImage: cgImage, scale: scale, orientation: refImage.imageOrientation)
} else {
return Image(cgImage: cgImage, scale: scale, orientation: .up)
}
}
/**
Normalize the image. This method will try to redraw an image with orientation and scale considered.
- returns: The normalized image with orientation set to up and correct scale
*/
public var normalized: Image {
// prevent animated image (GIF) lose it's images
guard images == nil else {
return base
}
// no need to do anything if already up
guard base.imageOrientation != .up else {
return base
}
return draw(cgImage: nil, to: size) {
base.draw(in: CGRect(origin: CGPoint.zero, size: size))
}
}
static func animated(with images: [Image], forDuration duration: TimeInterval) -> Image? {
return .animatedImage(with: images, duration: duration)
}
#endif
}
// MARK: Image Representation
extension KingFisher where Base: Image {
// MARK: - PNG
func pngRepresentation() -> Data? {
#if os(macOS)
guard let cgimage = cgImage else {
return nil
}
let rep = NSBitmapImageRep(cgImage: cgimage)
return rep.representation(using: .PNG, properties: [:])
#else
return UIImagePNGRepresentation(base)
#endif
}
// MARK: JPEG
func jpegRepresentation(compressionQuality: CGFloat) -> Data? {
#if os(macOS)
guard let cgImage = cgImage else {
return nil
}
let rep = NSBitmapImageRep(cgImage: cgImage)
return rep.representation(using:.JPEG, properties: [NSImageCompressionFactor: compressionQuality])
#else
return UIImageJPEGRepresentation(base, compressionQuality)
#endif
}
// MARK: - GIF
func gifRepresentation() -> Data? {
#if os(macOS)
return gifRepresentation(duration: 0.0, repeatCount: 0)
#else
return animatedImageData
#endif
}
#if os(macOS)
func gifRepresentation(duration: TimeInterval, repeatCount: Int) -> Data? {
guard let images = images else {
return nil
}
let frameCount = images.count
let gifDuration = duration <= 0.0 ? duration / Double(frameCount) : duration / Double(frameCount)
let frameProperties = [kCGImagePropertyGIFDictionary as String: [kCGImagePropertyGIFDelayTime as String: gifDuration]]
let imageProperties = [kCGImagePropertyGIFDictionary as String: [kCGImagePropertyGIFLoopCount as String: repeatCount]]
let data = NSMutableData()
guard let destination = CGImageDestinationCreateWithData(data, kUTTypeGIF, frameCount, nil) else {
return nil
}
CGImageDestinationSetProperties(destination, imageProperties as CFDictionary)
for image in images {
CGImageDestinationAddImage(destination, image.kf.cgImage!, frameProperties as CFDictionary)
}
return CGImageDestinationFinalize(destination) ? data.copy() as? Data : nil
}
#endif
}
// MARK: create iamges form data
extension KingFisher where Base: Image {
static func animated(with data: Data, scale: CGFloat = 1.0, duration: TimeInterval = 0.0, preloadAll: Bool) -> Image?{
func decode(from imageSource: CGImageSource, for options: NSDictionary) -> ([Image], TimeInterval)? {
// Calculates frame duration for a gif frame out of the kCGImagePropertyGIFDictionary dictionary
func frameDuration(from gifInfo: NSDictionary) -> Double {
let gifDefaultFrameDuration = 0.100
let unclampedDelayTime = gifInfo[kCGImagePropertyGIFUnclampedDelayTime as String] as? NSNumber
let delayTime = gifInfo[kCGImagePropertyGIFDelayTime as String] as? NSNumber
let duration = unclampedDelayTime ?? delayTime
guard let frameDuration = duration else {
return gifDefaultFrameDuration
}
return frameDuration.doubleValue > 0.011 ? frameDuration.doubleValue : gifDefaultFrameDuration
}
let frameCount = CGImageSourceGetCount(imageSource)
var images = [Image]()
var gifDuration = 0.0
for i in 0 ..< frameCount {
guard let imageRef = CGImageSourceCreateImageAtIndex(imageSource, i, options) else {
return nil
}
if frameCount == 1 {
// Single frame
gifDuration = Double.infinity
} else {
// Animated GIF
guard let properties = CGImageSourceCopyPropertiesAtIndex(imageSource, i, nil),let gifInfo = (properties as NSDictionary)[kCGImagePropertyGIFDictionary as String] as? NSDictionary else {
return nil
}
gifDuration += frameDuration(from: gifInfo)
}
images.append(KingFisher<Image>.image(cgImage: imageRef, scale: scale, refImage: nil))
}
return (images, gifDuration)
}
// Start of kf.animatedImageWithGIFData
let options: NSDictionary = [kCGImageSourceShouldCache as String: true, kCGImageSourceTypeIdentifierHint as String: kUTTypeGIF]
guard let imageSource = CGImageSourceCreateWithData(data as CFData, options) else {
return nil
}
#if os(macOS)
guard let (images, gifDuration) = decode(from: imageSource, for: options) else {
return nil
}
let image = Image(data: data)
image?.kf.images = images
image?.kf.duration = gifDuration
return image
#else
if preloadAll {
guard let (images, gifDuration) = decode(from: imageSource, for: options) else {
return nil
}
let image = KingFisher<Image>.animated(with: images, forDuration: duration <= 0.0 ? gifDuration : duration)
image?.kf.animatedImageData = data
return image
} else {
let image = Image(data: data)
image?.kf.animatedImageData = data
image?.kf.imageSource = ImageSource(ref: imageSource)
return image
}
#endif
}
static func image(data: Data, scale: CGFloat, preloadAllGIFData: Bool) -> Image? {
var image: Image?
#if os(macOS)
switch data.kf.imageFormat {
case .JPEG: image = Image(data: data)
case .PNG: image = Image(data: data)
case .GIF: image = KingFisher<Image>.animated(with: data, scale: scale, duration: 0.0, preloadAll: preloadAllGIFData)
case .unknown: image = Image(data: data)
}
#else
switch data.kf.imageFormat {
case .JPEG: image = Image(data: data, scale: scale)
case .PNG: image = Image(data: data, scale: scale)
case .GIF: image = KingFisher<Image>.animated(with: data, scale: scale, duration: 0.0, preloadAll: preloadAllGIFData)
case .unknown: image = Image(data: data, scale: scale)
}
#endif
return image
}
}
// Reference the source image reference
class ImageSource {
var imageRef: CGImageSource?
init(ref: CGImageSource) {
self.imageRef = ref
}
}
extension CGBitmapInfo {
var fixed: CGBitmapInfo {
var fixed = self
let alpha = (rawValue & CGBitmapInfo.alphaInfoMask.rawValue)
if alpha == CGImageAlphaInfo.none.rawValue {
fixed.remove(.alphaInfoMask)
fixed = CGBitmapInfo(rawValue: fixed.rawValue | CGImageAlphaInfo.noneSkipFirst.rawValue)
} else if !(alpha == CGImageAlphaInfo.noneSkipFirst.rawValue) || !(alpha == CGImageAlphaInfo.noneSkipLast.rawValue) {
fixed.remove(.alphaInfoMask)
fixed = CGBitmapInfo(rawValue: fixed.rawValue | CGImageAlphaInfo.premultipliedFirst.rawValue)
}
return fixed
}
}
extension KingFisher where Base: Image {
func draw(cgImage: CGImage?, to size: CGSize, draw: ()->()) -> Image {
#if os(macOS)
guard let rep = NSBitmapImageRep(
bitmapDataPlanes: nil,
pixelsWide: Int(size.width),
pixelsHigh: Int(size.height),
bitsPerSample: cgImage?.bitsPerComponent ?? 8,
samplesPerPixel: 4,
hasAlpha: true,
isPlanar: false,
colorSpaceName: NSCalibratedRGBColorSpace,
bytesPerRow: 0,
bitsPerPixel: 0) else
{
assertionFailure("[KingFisher] Image representation cannot be created.")
}
rep.size = size
NSGraphicsContext.saveGraphicsState()
let context = NSGraphicsContext(bitmapImageRep: rep)
NSGraphicsContext.setCurrent(context)
draw()
NSGraphicsContext.restoreGraphicsState()
let outputImage = Image(size: size)
outputImage.addRepresentation(rep)
return outputImage
#else
UIGraphicsBeginImageContextWithOptions(size, false, scale)
defer {
UIGraphicsEndImageContext()
}
draw()
return UIGraphicsGetImageFromCurrentImageContext() ?? base
#endif
}
#if os(macOS)
func fixedForRetinaPixel(cgImage: CGImage, to size: CGSize) -> Image {
let image = Image(cgImage: cgImage, size: base.size)
let rect = CGRect(origin: CGPoint(x: 0, y: 0), size: size)
return draw(cgImage: cgImage, to: self.size) {
image.draw(in: rect, from: NSRect.zero, operation: .copy, fraction: 1.0)
}
}
#endif
}
extension CGContext {
static func createARGBContext(from imageRef: CGImage) -> CGContext? {
let w = imageRef.width
let h = imageRef.height
let bytesPerRow = w * 4
let colorSpace = CGColorSpaceCreateDeviceRGB()
let data = malloc(bytesPerRow * h)
defer {
free(data)
}
let bitmapInfo = imageRef.bitmapInfo.fixed
// Create the bitmap context. We want pre-multiplied ARGB, 8-bits
// per component. Regardless of what the source image format is
// (CMYK, Grayscale, and so on) it will be converted over to the format
// specified here.
return CGContext(data: data,
width: w,
height: h,
bitsPerComponent: imageRef.bitsPerComponent,
bytesPerRow: bytesPerRow,
space: colorSpace,
bitmapInfo: bitmapInfo.rawValue)
}
}
extension Double {
var isEven: Bool {
return truncatingRemainder(dividingBy: 2.0) == 0
}
}
// MARK: - Image format
private struct ImageHeaderData {
static var PNG: [UInt8] = [0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A]
static var JPEG_SOI: [UInt8] = [0xFF, 0xD8]
static var JPEG_IF: [UInt8] = [0xFF]
static var GIF: [UInt8] = [0x47, 0x49, 0x46]
}
enum ImageFormat {
case unknown, PNG, JPEG, GIF
}
// MARK: - Misc Helpers
public struct DataProxy {
fileprivate let base: Data
init(proxy: Data) {
base = proxy
}
}
extension Data: KingFisherCompatible {
public typealias CompatibleType = DataProxy
public var kf: DataProxy {
return DataProxy(proxy: self)
}
}
extension DataProxy {
var imageFormat: ImageFormat {
var buffer = [UInt8](repeating: 0, count: 8)
(base as NSData).getBytes(&buffer, length: 8)
if buffer == ImageHeaderData.PNG {
return .PNG
} else if buffer[0] == ImageHeaderData.JPEG_SOI[0] &&
buffer[1] == ImageHeaderData.JPEG_SOI[1] &&
buffer[2] == ImageHeaderData.JPEG_IF[0]
{
return .JPEG
} else if buffer[0] == ImageHeaderData.GIF[0] &&
buffer[1] == ImageHeaderData.GIF[1] &&
buffer[2] == ImageHeaderData.GIF[2]
{
return .GIF
}
return .unknown
}
}
| 206c6221c4c183cc25a1824103e84a7b | 31.848548 | 206 | 0.589023 | false | false | false | false |
anpavlov/swiftperl | refs/heads/master | Sources/Perl/SvConvertible.swift | mit | 1 | public protocol PerlSvConvertible {
static func fromUnsafeSvPointer(_: UnsafeSvPointer, perl: UnsafeInterpreterPointer/* = UnsafeInterpreter.current */) throws -> Self
func toUnsafeSvPointer(perl: UnsafeInterpreterPointer/* = UnsafeInterpreter.current */) -> UnsafeSvPointer
}
extension Bool : PerlSvConvertible {
public static func fromUnsafeSvPointer(_ sv: UnsafeSvPointer, perl: UnsafeInterpreterPointer = UnsafeInterpreter.current) -> Bool { return Bool(sv, perl: perl) }
public func toUnsafeSvPointer(perl: UnsafeInterpreterPointer = UnsafeInterpreter.current) -> UnsafeSvPointer { return perl.pointee.newSV(self) }
}
extension Int : PerlSvConvertible {
public static func fromUnsafeSvPointer(_ sv: UnsafeSvPointer, perl: UnsafeInterpreterPointer = UnsafeInterpreter.current) throws -> Int { return try Int(sv, perl: perl) }
public func toUnsafeSvPointer(perl: UnsafeInterpreterPointer = UnsafeInterpreter.current) -> UnsafeSvPointer { return perl.pointee.newSV(self) }
}
extension Double : PerlSvConvertible {
public static func fromUnsafeSvPointer(_ sv: UnsafeSvPointer, perl: UnsafeInterpreterPointer = UnsafeInterpreter.current) throws -> Double { return try Double(sv, perl: perl) }
public func toUnsafeSvPointer(perl: UnsafeInterpreterPointer = UnsafeInterpreter.current) -> UnsafeSvPointer { return perl.pointee.newSV(self) }
}
extension String : PerlSvConvertible {
public static func fromUnsafeSvPointer(_ sv: UnsafeSvPointer, perl: UnsafeInterpreterPointer = UnsafeInterpreter.current) throws -> String { return try String(sv, perl: perl) }
public func toUnsafeSvPointer(perl: UnsafeInterpreterPointer = UnsafeInterpreter.current) -> UnsafeSvPointer { return perl.pointee.newSV(self) }
}
extension PerlScalar : PerlSvConvertible {
public static func fromUnsafeSvPointer(_ sv: UnsafeSvPointer, perl: UnsafeInterpreterPointer = UnsafeInterpreter.current) throws -> PerlScalar {
return try PerlScalar(inc: sv, perl: perl)
}
public func toUnsafeSvPointer(perl: UnsafeInterpreterPointer = UnsafeInterpreter.current) -> UnsafeSvPointer {
return withUnsafeSvPointer { sv, _ in sv.pointee.refcntInc() }
}
}
extension PerlDerived where Self : PerlValue, UnsafeValue : UnsafeSvCastable {
public static func fromUnsafeSvPointer(_ sv: UnsafeSvPointer, perl: UnsafeInterpreterPointer = UnsafeInterpreter.current) throws -> Self {
guard let unsafe = try UnsafeMutablePointer<UnsafeValue>(autoDeref: sv, perl: perl) else { throw PerlError.unexpectedUndef(Perl.fromUnsafeSvPointer(inc: sv, perl: perl)) }
return self.init(inc: unsafe, perl: perl)
}
public func toUnsafeSvPointer(perl: UnsafeInterpreterPointer = UnsafeInterpreter.current) -> UnsafeSvPointer {
return withUnsafeSvPointer { sv, perl in perl.pointee.newRV(inc: sv) }
}
}
extension PerlBridgedObject {
public static func fromUnsafeSvPointer(_ sv: UnsafeSvPointer, perl: UnsafeInterpreterPointer = UnsafeInterpreter.current) throws -> Self {
return try _fromUnsafeSvPointerNonFinalClassWorkaround(sv, perl: perl)
}
public func toUnsafeSvPointer(perl: UnsafeInterpreterPointer = UnsafeInterpreter.current) -> UnsafeSvPointer {
return perl.pointee.newSV(self)
}
public static func _fromUnsafeSvPointerNonFinalClassWorkaround<T>(_ sv: UnsafeSvPointer, perl: UnsafeInterpreterPointer = UnsafeInterpreter.current) throws -> T {
guard let base = sv.pointee.swiftObject(perl: perl) else {
throw PerlError.notSwiftObject(Perl.fromUnsafeSvPointer(inc: sv, perl: perl))
}
guard let obj = base as? T else {
throw PerlError.unexpectedObjectType(Perl.fromUnsafeSvPointer(inc: sv, perl: perl), want: self)
}
return obj
}
}
extension PerlObject {
public static func fromUnsafeSvPointer(_ sv: UnsafeSvPointer, perl: UnsafeInterpreterPointer = UnsafeInterpreter.current) throws -> Self {
return try _fromUnsafeSvPointerNonFinalClassWorkaround(sv, perl: perl)
}
public func toUnsafeSvPointer(perl: UnsafeInterpreterPointer = UnsafeInterpreter.current) -> UnsafeSvPointer {
return withUnsafeSvPointer { sv, _ in sv.pointee.refcntInc() }
}
public static func _fromUnsafeSvPointerNonFinalClassWorkaround<T : PerlObject>(_ sv: UnsafeSvPointer, perl: UnsafeInterpreterPointer = UnsafeInterpreter.current) throws -> T {
guard let classname = sv.pointee.classname(perl: perl) else {
throw PerlError.notObject(Perl.fromUnsafeSvPointer(inc: sv, perl: perl))
}
if let nc = T.self as? PerlNamedClass.Type, nc.perlClassName == classname {
return T(incUnchecked: sv, perl: perl)
}
let base = PerlObject.derivedClass(for: classname).init(incUnchecked: sv, perl: perl)
guard let obj = base as? T else {
throw PerlError.unexpectedObjectType(Perl.fromUnsafeSvPointer(inc: sv, perl: perl), want: self)
}
return obj
}
}
extension Optional where Wrapped : PerlSvConvertible {
public static func fromUnsafeSvPointer(_ sv: UnsafeSvPointer, perl: UnsafeInterpreterPointer = UnsafeInterpreter.current) throws -> Optional<Wrapped> {
return sv.pointee.defined ? try Wrapped.fromUnsafeSvPointer(sv, perl: perl) : nil
}
public func toUnsafeSvPointer(perl: UnsafeInterpreterPointer = UnsafeInterpreter.current) -> UnsafeSvPointer {
switch self {
case .some(let value):
return value.toUnsafeSvPointer(perl: perl)
case .none:
return perl.pointee.newSV()
}
}
}
extension Array where Element : PerlSvConvertible {
public func toUnsafeSvPointer(perl: UnsafeInterpreterPointer = UnsafeInterpreter.current) -> UnsafeSvPointer {
let av = perl.pointee.newAV()!
var c = av.pointee.collection(perl: perl)
c.reserveCapacity(numericCast(count))
for (i, v) in enumerated() {
c[i] = v.toUnsafeSvPointer(perl: perl)
}
return perl.pointee.newRV(noinc: av)
}
}
// where Key == String, but it is unsupported
extension Dictionary where Value : PerlSvConvertible {
public func toUnsafeSvPointer(perl: UnsafeInterpreterPointer = UnsafeInterpreter.current) -> UnsafeSvPointer {
let hv = perl.pointee.newHV()!
var c = hv.pointee.collection(perl: perl)
for (k, v) in self {
c[k as! String] = v.toUnsafeSvPointer(perl: perl)
}
return perl.pointee.newRV(noinc: hv)
}
}
| c136ac5d17dc19fc4b0acc9019e91901 | 46.8125 | 177 | 0.773203 | false | false | false | false |
powerytg/Accented | refs/heads/master | Accented/Core/Storage/Models/UserModel.swift | mit | 1 | //
// UserModel.swift
// Accented
//
// User model
//
// Created by Tiangong You on 8/6/16.
// Copyright © 2016 Tiangong You. All rights reserved.
//
import UIKit
import SwiftyJSON
// User avatar size definition
enum UserAvatar : String {
case Large = "large"
case Default = "default"
case Small = "small"
case Tiny = "tiny"
}
enum UpgradeStatus : Int {
case Basic = 0
case Plus = 1
case Awesome = 2
}
class UserModel: ModelBase {
var dateFormatter = DateFormatter()
var userId : String!
var followersCount : Int?
var coverUrl : String?
var lastName : String?
var firstName : String?
var userName : String!
var fullName : String?
var city : String?
var country : String?
var userPhotoUrl : String?
var about : String?
var registrationDate : Date?
var contacts : [String : String]?
var equipments : [String : [String]]?
var photoCount : Int?
var following : Bool?
var friendCount : Int?
var domain : String?
var upgradeStatus : UpgradeStatus!
var affection : Int?
var galleryCount : Int?
// Avatars
var avatarUrls = [UserAvatar : String]()
override init() {
super.init()
}
init(json : JSON) {
super.init()
self.userId = String(json["id"].int!)
self.modelId = self.userId
if let followCount = json["followers_count"].int {
followersCount = followCount
}
self.coverUrl = json["cover_url"].string
self.lastName = json["lastname"].string
self.firstName = json["firstname"].string
self.fullName = json["fullname"].string
self.userName = json["username"].string!
self.city = json["city"].string
self.country = json["country"].string
self.userPhotoUrl = json["userpic_url"].string
// Avatar urls
if let largeAvatar = json["avatars"]["large"]["https"].string {
avatarUrls[.Large] = largeAvatar
}
if let defaultAvatar = json["avatars"]["default"]["https"].string {
avatarUrls[.Default] = defaultAvatar
}
if let smallAvatar = json["avatars"]["small"]["https"].string {
avatarUrls[.Small] = smallAvatar
}
if let tinyAvatar = json["avatars"]["tiny"]["https"].string {
avatarUrls[.Tiny] = tinyAvatar
}
dateFormatter.dateFormat = "yyyy'-'MM'-'dd'T'HH':'mm':'ssZZZZZ"
self.about = json["about"].string
if let regDate = json["registration_date"].string {
self.registrationDate = dateFormatter.date(from: regDate)
}
if let _ = json["contacts"].dictionary {
self.contacts = [String : String]()
for (key, value) : (String, JSON) in json["contacts"] {
self.contacts![key] = value.stringValue
}
}
if let _ = json["equipments"].dictionary {
self.equipments = [String : [String]]()
for (type, _) : (String, JSON) in json["equipments"] {
self.equipments![type] = []
for (_, gear) in json["equipments"][type] {
self.equipments![type]!.append(gear.stringValue)
}
}
}
self.photoCount = json["photos_count"].int
self.following = json["following"].bool
self.friendCount = json["friends_count"].int
self.domain = json["domain"].string
self.upgradeStatus = UpgradeStatus(rawValue: json["upgrade_status"].intValue)
self.affection = json["affection"].int
self.galleryCount = json["galleries_count"].int
}
override func copy(with zone: NSZone? = nil) -> Any {
let clone = UserModel()
clone.userId = self.userId
clone.modelId = self.modelId
clone.followersCount = self.followersCount
clone.coverUrl = self.coverUrl
clone.lastName = self.lastName
clone.firstName = self.firstName
clone.fullName = self.fullName
clone.userName = self.userName
clone.city = self.city
clone.country = self.country
clone.userPhotoUrl = self.userPhotoUrl
clone.avatarUrls = self.avatarUrls
clone.about = self.about
clone.registrationDate = self.registrationDate
clone.contacts = self.contacts
clone.equipments = self.equipments
clone.photoCount = self.photoCount
clone.following = self.following
clone.friendCount = self.friendCount
clone.domain = self.domain
clone.upgradeStatus = self.upgradeStatus
clone.affection = self.affection
clone.galleryCount = self.galleryCount
return clone
}
}
| ccd0371365c6b8c8d9c44ac88003cce7 | 30.122581 | 85 | 0.582504 | false | false | false | false |
berishaerblin/Attendance | refs/heads/master | Attendance/AppDelegate.swift | gpl-3.0 | 1 | //
// AppDelegate.swift
// Attendance
//
// Created by Erblin Berisha on 8/9/17.
// Copyright © 2017 Erblin Berisha. All rights reserved.
//
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey : Any]? = nil) -> 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: "Attendance")
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)")
}
}
}
}
| 409710920bcfbd1ff4bb37de6f2a017b | 50.633333 | 285 | 0.679793 | false | false | false | false |
scinfu/SwiftSoup | refs/heads/master | Sources/TokenQueue.swift | mit | 1 | //
// TokenQueue.swift
// SwiftSoup
//
// Created by Nabil Chatbi on 13/10/16.
// Copyright © 2016 Nabil Chatbi.. All rights reserved.
//
import Foundation
open class TokenQueue {
private var queue: String
private var pos: Int = 0
private static let empty: Character = Character(UnicodeScalar(0))
private static let ESC: Character = "\\" // escape char for chomp balanced.
/**
Create a new TokenQueue.
@param data string of data to back queue.
*/
public init (_ data: String) {
queue = data
}
/**
* Is the queue empty?
* @return true if no data left in queue.
*/
open func isEmpty() -> Bool {
return remainingLength() == 0
}
private func remainingLength() -> Int {
return queue.count - pos
}
/**
* Retrieves but does not remove the first character from the queue.
* @return First character, or 0 if empty.
*/
open func peek() -> Character {
return isEmpty() ? Character(UnicodeScalar(0)) : queue[pos]
}
/**
Add a character to the start of the queue (will be the next character retrieved).
@param c character to add
*/
open func addFirst(_ c: Character) {
addFirst(String(c))
}
/**
Add a string to the start of the queue.
@param seq string to add.
*/
open func addFirst(_ seq: String) {
// not very performant, but an edge case
queue = seq + queue.substring(pos)
pos = 0
}
/**
* Tests if the next characters on the queue match the sequence. Case insensitive.
* @param seq String to check queue for.
* @return true if the next characters match.
*/
open func matches(_ seq: String) -> Bool {
return queue.regionMatches(ignoreCase: true, selfOffset: pos,
other: seq, otherOffset: 0, targetLength: seq.count)
}
/**
* Case sensitive match test.
* @param seq string to case sensitively check for
* @return true if matched, false if not
*/
open func matchesCS(_ seq: String) -> Bool {
return queue.startsWith(seq, pos)
}
/**
Tests if the next characters match any of the sequences. Case insensitive.
@param seq list of strings to case insensitively check for
@return true of any matched, false if none did
*/
open func matchesAny(_ seq: [String]) -> Bool {
for s in seq {
if (matches(s)) {
return true
}
}
return false
}
open func matchesAny(_ seq: String...) -> Bool {
return matchesAny(seq)
}
open func matchesAny(_ seq: Character...) -> Bool {
if (isEmpty()) {
return false
}
for c in seq {
if (queue[pos] as Character == c) {
return true
}
}
return false
}
open func matchesStartTag() -> Bool {
// micro opt for matching "<x"
return (remainingLength() >= 2 && queue[pos] as Character == "<" && Character.isLetter(queue.charAt(pos+1)))
}
/**
* Tests if the queue matches the sequence (as with match), and if they do, removes the matched string from the
* queue.
* @param seq String to search for, and if found, remove from queue.
* @return true if found and removed, false if not found.
*/
@discardableResult
open func matchChomp(_ seq: String) -> Bool {
if (matches(seq)) {
pos += seq.count
return true
} else {
return false
}
}
/**
Tests if queue starts with a whitespace character.
@return if starts with whitespace
*/
open func matchesWhitespace() -> Bool {
return !isEmpty() && StringUtil.isWhitespace(queue.charAt(pos))
}
/**
Test if the queue matches a word character (letter or digit).
@return if matches a word character
*/
open func matchesWord() -> Bool {
return !isEmpty() && (Character.isLetterOrDigit(queue.charAt(pos)))
}
/**
* Drops the next character off the queue.
*/
open func advance() {
if (!isEmpty()) {pos+=1}
}
/**
* Consume one character off queue.
* @return first character on queue.
*/
open func consume() -> Character {
let i = pos
pos+=1
return queue.charAt(i)
}
/**
* Consumes the supplied sequence of the queue. If the queue does not start with the supplied sequence, will
* throw an illegal state exception -- but you should be running match() against that condition.
<p>
Case insensitive.
* @param seq sequence to remove from head of queue.
*/
open func consume(_ seq: String)throws {
if (!matches(seq)) {
//throw new IllegalStateException("Queue did not match expected sequence")
throw Exception.Error(type: ExceptionType.IllegalArgumentException, Message: "Queue did not match expected sequence")
}
let len = seq.count
if (len > remainingLength()) {
//throw new IllegalStateException("Queue not long enough to consume sequence")
throw Exception.Error(type: ExceptionType.IllegalArgumentException, Message: "Queue not long enough to consume sequence")
}
pos += len
}
/**
* Pulls a string off the queue, up to but exclusive of the match sequence, or to the queue running out.
* @param seq String to end on (and not include in return, but leave on queue). <b>Case sensitive.</b>
* @return The matched data consumed from queue.
*/
@discardableResult
open func consumeTo(_ seq: String) -> String {
let offset = queue.indexOf(seq, pos)
if (offset != -1) {
let consumed = queue.substring(pos, offset-pos)
pos += consumed.count
return consumed
} else {
//return remainder()
}
return ""
}
open func consumeToIgnoreCase(_ seq: String) -> String {
let start = pos
let first = seq.substring(0, 1)
let canScan = first.lowercased() == first.uppercased() // if first is not cased, use index of
while (!isEmpty()) {
if (matches(seq)) {
break
}
if (canScan) {
let skip = queue.indexOf(first, pos) - pos
if (skip == 0) { // this char is the skip char, but not match, so force advance of pos
pos+=1
} else if (skip < 0) { // no chance of finding, grab to end
pos = queue.count
} else {
pos += skip
}
} else {
pos+=1
}
}
return queue.substring(start, pos-start)
}
/**
Consumes to the first sequence provided, or to the end of the queue. Leaves the terminator on the queue.
@param seq any number of terminators to consume to. <b>Case insensitive.</b>
@return consumed string
*/
// todo: method name. not good that consumeTo cares for case, and consume to any doesn't. And the only use for this
// is is a case sensitive time...
open func consumeToAny(_ seq: String...) -> String {
return consumeToAny(seq)
}
open func consumeToAny(_ seq: [String]) -> String {
let start = pos
while (!isEmpty() && !matchesAny(seq)) {
pos+=1
}
return queue.substring(start, pos-start)
}
/**
* Pulls a string off the queue (like consumeTo), and then pulls off the matched string (but does not return it).
* <p>
* If the queue runs out of characters before finding the seq, will return as much as it can (and queue will go
* isEmpty() == true).
* @param seq String to match up to, and not include in return, and to pull off queue. <b>Case sensitive.</b>
* @return Data matched from queue.
*/
open func chompTo(_ seq: String) -> String {
let data = consumeTo(seq)
matchChomp(seq)
return data
}
open func chompToIgnoreCase(_ seq: String) -> String {
let data = consumeToIgnoreCase(seq) // case insensitive scan
matchChomp(seq)
return data
}
/**
* Pulls a balanced string off the queue. E.g. if queue is "(one (two) three) four", (,) will return "one (two) three",
* and leave " four" on the queue. Unbalanced openers and closers can quoted (with ' or ") or escaped (with \). Those escapes will be left
* in the returned string, which is suitable for regexes (where we need to preserve the escape), but unsuitable for
* contains text strings; use unescape for that.
* @param open opener
* @param close closer
* @return data matched from the queue
*/
open func chompBalanced(_ open: Character, _ close: Character) -> String {
var start = -1
var end = -1
var depth = 0
var last: Character = TokenQueue.empty
var inQuote = false
repeat {
if (isEmpty()) {break}
let c = consume()
if (last == TokenQueue.empty || last != TokenQueue.ESC) {
if ((c=="'" || c=="\"") && c != open) {
inQuote = !inQuote
}
if (inQuote) {
continue
}
if (c==open) {
depth+=1
if (start == -1) {
start = pos
}
} else if (c==close) {
depth-=1
}
}
if (depth > 0 && last != TokenQueue.empty) {
end = pos // don't include the outer match pair in the return
}
last = c
} while (depth > 0)
return (end >= 0) ? queue.substring(start, end-start) : ""
}
/**
* Unescaped a \ escaped string.
* @param in backslash escaped string
* @return unescaped string
*/
public static func unescape(_ input: String) -> String {
let out = StringBuilder()
var last = empty
for c in input {
if (c == ESC) {
if (last != empty && last == TokenQueue.ESC) {
out.append(c)
}
} else {
out.append(c)
}
last = c
}
return out.toString()
}
/**
* Pulls the next run of whitespace characters of the queue.
* @return Whether consuming whitespace or not
*/
@discardableResult
open func consumeWhitespace() -> Bool {
var seen = false
while (matchesWhitespace()) {
pos+=1
seen = true
}
return seen
}
/**
* Retrieves the next run of word type (letter or digit) off the queue.
* @return String of word characters from queue, or empty string if none.
*/
@discardableResult
open func consumeWord() -> String {
let start = pos
while (matchesWord()) {
pos+=1
}
return queue.substring(start, pos-start)
}
/**
* Consume an tag name off the queue (word or :, _, -)
*
* @return tag name
*/
open func consumeTagName() -> String {
let start = pos
while (!isEmpty() && (matchesWord() || matchesAny(":", "_", "-"))) {
pos+=1
}
return queue.substring(start, pos-start)
}
/**
* Consume a CSS element selector (tag name, but | instead of : for namespaces (or *| for wildcard namespace), to not conflict with :pseudo selects).
*
* @return tag name
*/
open func consumeElementSelector() -> String {
let start = pos
while (!isEmpty() && (matchesWord() || matchesAny("*|", "|", "_", "-"))) {
pos+=1
}
return queue.substring(start, pos-start)
}
/**
Consume a CSS identifier (ID or class) off the queue (letter, digit, -, _)
http://www.w3.org/TR/CSS2/syndata.html#value-def-identifier
@return identifier
*/
open func consumeCssIdentifier() -> String {
let start = pos
while (!isEmpty() && (matchesWord() || matchesAny("-", "_"))) {
pos+=1
}
return queue.substring(start, pos-start)
}
/**
Consume an attribute key off the queue (letter, digit, -, _, :")
@return attribute key
*/
open func consumeAttributeKey() -> String {
let start = pos
while (!isEmpty() && (matchesWord() || matchesAny("-", "_", ":"))) {
pos+=1
}
return queue.substring(start, pos-start)
}
/**
Consume and return whatever is left on the queue.
@return remained of queue.
*/
open func remainder() -> String {
let remainder = queue.substring(pos, queue.count-pos)
pos = queue.count
return remainder
}
open func toString() -> String {
return queue.substring(pos)
}
}
| 57f92cc144dd65a3cfc0bfd01e3414ac | 29.608392 | 153 | 0.54794 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.