repo_name
stringlengths 6
91
| path
stringlengths 8
968
| copies
stringclasses 210
values | size
stringlengths 2
7
| content
stringlengths 61
1.01M
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6
99.8
| line_max
int64 12
1k
| alpha_frac
float64 0.3
0.91
| ratio
float64 2
9.89
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
xiaolulwr/OpenDrcom-macOS-x86_64 | OpenDrcom/DrInfoProvider.swift | 1 | 5492 | /**
* Copyright (c) 2017, 小路.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License, version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope 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.
*/
import Cocoa
/// 获得使用量的类
class DrInfoProvider: NSObject {
let delegate:DrInfoProviderDelegate
let gatewayURLString = "http://192.168.100.200"
var htmlCode:String?
var remoteHtmlCode:String?
init(delegate: DrInfoProviderDelegate) {
self.delegate = delegate
super.init()
self.searchGateway()
}
/// 连接到校园网网关
func searchGateway() {
let gatewayURL = URL.init(string: gatewayURLString)!
var request = URLRequest(url: gatewayURL)
request.addValue("Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/12.0 Safari/605.1.15", forHTTPHeaderField: "User-Agent")
request.addValue("text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8", forHTTPHeaderField: "Accept")
request.addValue("zh-CN,zh;q=0.9", forHTTPHeaderField: "accept-language")
request.addValue("gzip, deflate, br", forHTTPHeaderField: "accept-encoding")
let task = URLSession.shared.dataTask(with: request, completionHandler: { (data, response, error) in
// 网络相关错误
if let error = error {
print(error.localizedDescription)
return
}
// 服务器错误
guard let data = data else { return }
let httpResponse = response as? HTTPURLResponse
guard let status = httpResponse?.statusCode else { return }
guard status == 200 else {
print(status)
return
}
self.htmlCode = String (data: data, encoding: .ascii)
self.delegate.finishRefreshUsageAndIP()
})
task.resume()
}
/// 从网关获取使用时长
///
/// - Returns: 帐号使用时长,单位是分钟
func timeUsage() -> String? {
guard htmlCode != nil else {
return nil
}
let timeRange = htmlCode?.range(of: "time='")
guard timeRange != nil else {
return nil
}
let timeSubstring = htmlCode?[(timeRange?.upperBound)!...]
var usageTimeString:String=""
for perChar in timeSubstring! {
if perChar >= "0" && perChar <= "9" {
usageTimeString.append(perChar)
} else {
break;
}
}
return usageTimeString
}
/// 从网关获得使用流量
///
/// - Returns: 帐号使用的流量,单位是MB
func flowUsage() -> String? {
guard htmlCode != nil else {
return nil
}
let flowRange = htmlCode?.range(of: "';flow='")
guard flowRange != nil else {
return nil
}
let flowSubstring = htmlCode?[(flowRange?.upperBound)!...]
var usageFlowString:String=""
for perChar in flowSubstring! {
if perChar >= "0" && perChar <= "9" {
usageFlowString.append(perChar)
} else {
break;
}
}
let usageFlowInt:Int? = Int.init(usageFlowString)
var flow0:Int = usageFlowInt! % 1024;
let flow1:Int = usageFlowInt! - flow0;
flow0 = flow0 * 1000;
flow0 = flow0 - flow0 % 1024;
usageFlowString = String.init(format: "%ld.%ld", flow1 / 1024 ,flow0 / 1024)
return usageFlowString
}
/// 从网关获得余额
///
/// - Returns: 帐号的余额,单位是CNY
func balanceUsage() -> String? {
guard htmlCode != nil else {
return nil
}
let balanceRange = htmlCode?.range(of: "fee='")
guard balanceRange != nil else {
return nil
}
let balanceSubstring = htmlCode?[(balanceRange?.upperBound)!...]
var usageBalanceString:String=""
for perChar in balanceSubstring! {
if perChar >= "0" && perChar <= "9" {
usageBalanceString.append(perChar)
} else {
break;
}
}
var usageBalanceDouble = Double.init(usageBalanceString)!
usageBalanceDouble = usageBalanceDouble / 10000
usageBalanceString = String.init(format: "%.2f", usageBalanceDouble);
return usageBalanceString
}
/// 从网关获得本地IPv4地址
///
/// - Returns: 本地IPv4地址
func ipv4Private() -> String? {
guard htmlCode != nil else {
return nil
}
let ipRange = htmlCode?.range(of: "v4ip='")
guard ipRange != nil else {
return nil
}
let ipSubstring = htmlCode?[(ipRange?.upperBound)!...]
var iPString:String=""
for perChar in ipSubstring! {
if (perChar >= "0" && perChar <= "9") || perChar == "." {
iPString.append(perChar)
} else {
break;
}
}
return iPString
}
}
| gpl-3.0 | c5a5290a19b09a0ee394c2e240b3d6f9 | 32.308176 | 177 | 0.558535 | 4.402328 | false | false | false | false |
slavapestov/swift | stdlib/public/SDK/UIKit/UIKit.swift | 1 | 6498 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import Foundation
@_exported import UIKit
//===----------------------------------------------------------------------===//
// Equatable types.
//===----------------------------------------------------------------------===//
@_transparent // @fragile
@warn_unused_result
public func == (lhs: UIEdgeInsets, rhs: UIEdgeInsets) -> Bool {
return lhs.top == rhs.top &&
lhs.left == rhs.left &&
lhs.bottom == rhs.bottom &&
lhs.right == rhs.right
}
extension UIEdgeInsets : Equatable {}
@_transparent // @fragile
@warn_unused_result
public func == (lhs: UIOffset, rhs: UIOffset) -> Bool {
return lhs.horizontal == rhs.horizontal &&
lhs.vertical == rhs.vertical
}
extension UIOffset : Equatable {}
// These are un-imported macros in UIKit.
//===----------------------------------------------------------------------===//
// UIDeviceOrientation
//===----------------------------------------------------------------------===//
#if !os(watchOS) && !os(tvOS)
public extension UIDeviceOrientation {
var isLandscape: Bool {
return self == .LandscapeLeft || self == .LandscapeRight
}
var isPortrait: Bool {
return self == .Portrait || self == .PortraitUpsideDown
}
var isFlat: Bool {
return self == .FaceUp || self == .FaceDown
}
var isValidInterfaceOrientation: Bool {
switch (self) {
case .Portrait, .PortraitUpsideDown, .LandscapeLeft, .LandscapeRight:
return true
default:
return false
}
}
}
@warn_unused_result
public func UIDeviceOrientationIsLandscape(
orientation: UIDeviceOrientation
) -> Bool {
return orientation.isLandscape
}
@warn_unused_result
public func UIDeviceOrientationIsPortrait(
orientation: UIDeviceOrientation
) -> Bool {
return orientation.isPortrait
}
@warn_unused_result
public func UIDeviceOrientationIsValidInterfaceOrientation(
orientation: UIDeviceOrientation) -> Bool
{
return orientation.isValidInterfaceOrientation
}
#endif
//===----------------------------------------------------------------------===//
// UIInterfaceOrientation
//===----------------------------------------------------------------------===//
#if !os(watchOS) && !os(tvOS)
public extension UIInterfaceOrientation {
var isLandscape: Bool {
return self == .LandscapeLeft || self == .LandscapeRight
}
var isPortrait: Bool {
return self == .Portrait || self == .PortraitUpsideDown
}
}
@warn_unused_result
public func UIInterfaceOrientationIsPortrait(
orientation: UIInterfaceOrientation) -> Bool {
return orientation.isPortrait
}
@warn_unused_result
public func UIInterfaceOrientationIsLandscape(
orientation: UIInterfaceOrientation
) -> Bool {
return orientation.isLandscape
}
#endif
// Overlays for variadic initializers.
#if !os(watchOS) && !os(tvOS)
public extension UIActionSheet {
convenience init(title: String?,
delegate: UIActionSheetDelegate?,
cancelButtonTitle: String?,
destructiveButtonTitle: String?,
// Hack around overload ambiguity with non-variadic constructor.
// <rdar://problem/16704770>
otherButtonTitles firstButtonTitle: String,
_ moreButtonTitles: String...) {
self.init(title: title,
delegate: delegate,
cancelButtonTitle: cancelButtonTitle,
destructiveButtonTitle: destructiveButtonTitle)
self.addButtonWithTitle(firstButtonTitle)
for buttonTitle in moreButtonTitles {
self.addButtonWithTitle(buttonTitle)
}
}
}
#endif
#if !os(watchOS) && !os(tvOS)
public extension UIAlertView {
convenience init(title: String,
message: String,
delegate: UIAlertViewDelegate?,
cancelButtonTitle: String?,
// Hack around overload ambiguity with non-variadic constructor.
// <rdar://problem/16704770>
otherButtonTitles firstButtonTitle: String,
_ moreButtonTitles: String...) {
self.init(title: title,
message: message,
delegate: delegate,
cancelButtonTitle: cancelButtonTitle)
self.addButtonWithTitle(firstButtonTitle)
for buttonTitle in moreButtonTitles {
self.addButtonWithTitle(buttonTitle)
}
}
}
#endif
#if !os(watchOS)
internal struct _UIViewQuickLookState {
static var views = Set<UIView>()
}
extension UIView : CustomPlaygroundQuickLookable {
public func customPlaygroundQuickLook() -> PlaygroundQuickLook {
if _UIViewQuickLookState.views.contains(self) {
return .View(UIImage())
} else {
_UIViewQuickLookState.views.insert(self)
// in case of an empty rectangle abort the logging
if (bounds.size.width == 0) || (bounds.size.height == 0) {
return .View(UIImage())
}
UIGraphicsBeginImageContextWithOptions(bounds.size, false, 0.0)
// UIKit is about to update this to be optional, so make it work
// with both older and newer SDKs. (In this context it should always
// be present.)
let ctx: CGContext! = UIGraphicsGetCurrentContext()
UIColor(white:1.0, alpha:0.0).set()
CGContextFillRect(ctx, bounds)
layer.renderInContext(ctx)
let image: UIImage! = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
_UIViewQuickLookState.views.remove(self)
return .View(image)
}
}
}
#endif
extension UIColor : _ColorLiteralConvertible {
public required convenience init(colorLiteralRed red: Float, green: Float,
blue: Float, alpha: Float) {
self.init(red: CGFloat(red), green: CGFloat(green),
blue: CGFloat(blue), alpha: CGFloat(alpha))
}
}
public typealias _ColorLiteralType = UIColor
extension UIImage : _ImageLiteralConvertible {
private convenience init!(failableImageLiteral name: String) {
self.init(named: name)
}
public required convenience init(imageLiteral name: String) {
self.init(failableImageLiteral: name)
}
}
public typealias _ImageLiteralType = UIImage
| apache-2.0 | 1c9b4f3156251d6eda210ff9a6ffec4d | 28.008929 | 80 | 0.626347 | 5.120567 | false | false | false | false |
hejunbinlan/GRDB.swift | GRDB/Foundation/DatabaseDateComponents.swift | 1 | 9636 | import Foundation
/**
DatabaseDateComponents reads and stores NSDateComponents in the database.
*/
public struct DatabaseDateComponents : DatabaseValueConvertible {
/// The available formats for reading and storing date components.
public enum Format : String {
/// The format "yyyy-MM-dd".
case YMD = "yyyy-MM-dd"
/// The format "yyyy-MM-dd HH:mm".
///
/// This format is lexically comparable with SQLite's CURRENT_TIMESTAMP.
case YMD_HM = "yyyy-MM-dd HH:mm"
/// The format "yyyy-MM-dd HH:mm:ss".
///
/// This format is lexically comparable with SQLite's CURRENT_TIMESTAMP.
case YMD_HMS = "yyyy-MM-dd HH:mm:ss"
/// The format "yyyy-MM-dd HH:mm:ss.SSS".
///
/// This format is lexically comparable with SQLite's CURRENT_TIMESTAMP.
case YMD_HMSS = "yyyy-MM-dd HH:mm:ss.SSS"
/// The format "HH:mm".
case HM = "HH:mm"
/// The format "HH:mm:ss".
case HMS = "HH:mm:ss"
/// The format "HH:mm:ss.SSS".
case HMSS = "HH:mm:ss.SSS"
}
// MARK: - NSDateComponents conversion
/// The date components
public let dateComponents: NSDateComponents
/// The database format
public let format: Format
/**
Creates a DatabaseDateComponents from an NSDateComponents and a format.
The result is nil if and only if *dateComponents* is nil.
- parameter dateComponents: An optional NSDateComponents.
- parameter format: The format used for storing the date components in the
database.
- returns: An optional DatabaseDateComponents.
*/
public init?(_ dateComponents: NSDateComponents?, format: Format) {
if let dateComponents = dateComponents {
self.format = format
self.dateComponents = dateComponents
} else {
return nil
}
}
// MARK: - DatabaseValueConvertible adoption
/// Returns a value that can be stored in the database.
public var databaseValue: DatabaseValue {
let dateString: String?
switch format {
case .YMD_HM, .YMD_HMS, .YMD_HMSS, .YMD:
let year = (dateComponents.year == NSDateComponentUndefined) ? 0 : dateComponents.year
let month = (dateComponents.month == NSDateComponentUndefined) ? 1 : dateComponents.month
let day = (dateComponents.day == NSDateComponentUndefined) ? 1 : dateComponents.day
dateString = NSString(format: "%04d-%02d-%02d", year, month, day) as String
default:
dateString = nil
}
let timeString: String?
switch format {
case .YMD_HM, .HM:
let hour = (dateComponents.hour == NSDateComponentUndefined) ? 0 : dateComponents.hour
let minute = (dateComponents.minute == NSDateComponentUndefined) ? 0 : dateComponents.minute
timeString = NSString(format: "%02d:%02d", hour, minute) as String
case .YMD_HMS, .HMS:
let hour = (dateComponents.hour == NSDateComponentUndefined) ? 0 : dateComponents.hour
let minute = (dateComponents.minute == NSDateComponentUndefined) ? 0 : dateComponents.minute
let second = (dateComponents.second == NSDateComponentUndefined) ? 0 : dateComponents.second
timeString = NSString(format: "%02d:%02d:%02d", hour, minute, second) as String
case .YMD_HMSS, .HMSS:
let hour = (dateComponents.hour == NSDateComponentUndefined) ? 0 : dateComponents.hour
let minute = (dateComponents.minute == NSDateComponentUndefined) ? 0 : dateComponents.minute
let second = (dateComponents.second == NSDateComponentUndefined) ? 0 : dateComponents.second
let nanosecond = (dateComponents.nanosecond == NSDateComponentUndefined) ? 0 : dateComponents.nanosecond
timeString = NSString(format: "%02d:%02d:%02d.%03d", hour, minute, second, Int(round(Double(nanosecond) / 1_000_000.0))) as String
default:
timeString = nil
}
return .Text([dateString, timeString].flatMap { $0 }.joinWithSeparator(" "))
}
/**
Returns a DatabaseDateComponents if *databaseValue* contains a valid date.
- parameter databaseValue: A DatabaseValue.
- returns: An optional DatabaseDateComponents.
*/
public static func fromDatabaseValue(databaseValue: DatabaseValue) -> DatabaseDateComponents? {
// https://www.sqlite.org/lang_datefunc.html
//
// Supported formats are:
//
// - YYYY-MM-DD
// - YYYY-MM-DD HH:MM
// - YYYY-MM-DD HH:MM:SS
// - YYYY-MM-DD HH:MM:SS.SSS
// - YYYY-MM-DDTHH:MM
// - YYYY-MM-DDTHH:MM:SS
// - YYYY-MM-DDTHH:MM:SS.SSS
// - HH:MM
// - HH:MM:SS
// - HH:MM:SS.SSS
// We need a String
guard let string = String.fromDatabaseValue(databaseValue) else {
return nil
}
let dateComponents = NSDateComponents()
let scanner = NSScanner(string: string)
scanner.charactersToBeSkipped = NSCharacterSet()
let hasDate: Bool
// YYYY or HH
var initialNumber: Int = 0
if !scanner.scanInteger(&initialNumber) {
return nil
}
switch scanner.scanLocation {
case 2:
// HH
hasDate = false
let hour = initialNumber
if hour >= 0 && hour <= 23 {
dateComponents.hour = hour
} else {
return nil
}
case 4:
// YYYY
hasDate = true
let year = initialNumber
if year >= 0 && year <= 9999 {
dateComponents.year = year
} else {
return nil
}
// -
if !scanner.scanString("-", intoString: nil) {
return nil
}
// MM
var month: Int = 0
if scanner.scanInteger(&month) && month >= 1 && month <= 12 {
dateComponents.month = month
} else {
return nil
}
// -
if !scanner.scanString("-", intoString: nil) {
return nil
}
// DD
var day: Int = 0
if scanner.scanInteger(&day) && day >= 1 && day <= 31 {
dateComponents.day = day
} else {
return nil
}
// YYYY-MM-DD
if scanner.atEnd {
return DatabaseDateComponents(dateComponents, format: .YMD)
}
// T/space
if !scanner.scanString("T", intoString: nil) && !scanner.scanString(" ", intoString: nil) {
return nil
}
// HH
var hour: Int = 0
if scanner.scanInteger(&hour) && hour >= 0 && hour <= 23 {
dateComponents.hour = hour
} else {
return nil
}
default:
return nil
}
// :
if !scanner.scanString(":", intoString: nil) {
return nil
}
// MM
var minute: Int = 0
if scanner.scanInteger(&minute) && minute >= 0 && minute <= 59 {
dateComponents.minute = minute
} else {
return nil
}
// [YYYY-MM-DD] HH:MM
if scanner.atEnd {
if hasDate {
return DatabaseDateComponents(dateComponents, format: .YMD_HM)
} else {
return DatabaseDateComponents(dateComponents, format: .HM)
}
}
// :
if !scanner.scanString(":", intoString: nil) {
return nil
}
// SS
var second: Int = 0
if scanner.scanInteger(&second) && second >= 0 && second <= 59 {
dateComponents.second = second
} else {
return nil
}
// [YYYY-MM-DD] HH:MM:SS
if scanner.atEnd {
if hasDate {
return DatabaseDateComponents(dateComponents, format: .YMD_HMS)
} else {
return DatabaseDateComponents(dateComponents, format: .HMS)
}
}
// .
if !scanner.scanString(".", intoString: nil) {
return nil
}
// SSS
var millisecondDigits: NSString? = nil
if scanner.scanCharactersFromSet(NSCharacterSet.decimalDigitCharacterSet(), intoString: &millisecondDigits), var millisecondDigits = millisecondDigits {
if millisecondDigits.length > 3 {
millisecondDigits = millisecondDigits.substringToIndex(3)
}
dateComponents.nanosecond = millisecondDigits.integerValue * 1_000_000
} else {
return nil
}
// [YYYY-MM-DD] HH:MM:SS.SSS
if scanner.atEnd {
if hasDate {
return DatabaseDateComponents(dateComponents, format: .YMD_HMSS)
} else {
return DatabaseDateComponents(dateComponents, format: .HMSS)
}
}
// Unknown format
return nil
}
}
| mit | 3e90a1f1c3062fbc0f754eb6b623e5f9 | 32.574913 | 160 | 0.526256 | 5.194609 | false | false | false | false |
xixijiushui/douyu | douyu/douyu/Classes/Home/View/RecommendGameView.swift | 1 | 2038 | //
// RecommendGameView.swift
// douyu
//
// Created by 赵伟 on 2016/11/9.
// Copyright © 2016年 赵伟. All rights reserved.
//
import UIKit
private let kGameCellID = "kGameCellID"
private let kEdgeInsetMargin : CGFloat = 10
class RecommendGameView: UIView {
@IBOutlet weak var collectionView: UICollectionView!
var groups : [AnchorGroup]? {
didSet {
// 刷新表格
collectionView.reloadData()
}
}
override func awakeFromNib() {
super.awakeFromNib()
autoresizingMask = .None
collectionView.registerNib(UINib(nibName: "CollectionGameCell", bundle: nil), forCellWithReuseIdentifier: kGameCellID)
// 给collectionView添加内边距
collectionView.contentInset = UIEdgeInsets(top: 0, left: kEdgeInsetMargin, bottom: 0, right: kEdgeInsetMargin)
}
override func layoutSubviews() {
super.layoutSubviews()
let layout = collectionView.collectionViewLayout as! UICollectionViewFlowLayout
layout.itemSize = CGSizeMake(80, 90)
layout.minimumLineSpacing = 0
layout.minimumInteritemSpacing = 0
}
}
// MARK:- 提供一个快速创建View的类方法
extension RecommendGameView {
class func recommendGameView() -> RecommendGameView {
return NSBundle.mainBundle().loadNibNamed("RecommendGameView", owner: nil, options: nil)?.first as! RecommendGameView
}
}
extension RecommendGameView : UICollectionViewDataSource {
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return groups?.count ?? 0
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(kGameCellID, forIndexPath: indexPath) as! CollectionGameCell
cell.anchorGroup = groups![indexPath.item]
return cell
}
}
| mit | a8c4320fe0d58ff677e87e7ad3579b05 | 29.984375 | 133 | 0.684821 | 5.601695 | false | false | false | false |
zhou9734/ZCJImagePicker | ZCJImagePicker/ImagePicker/ALAssentModel.swift | 1 | 457 | //
// PhotoLibraryModel.swift
// 图片选择器
//
// Created by zhoucj on 16/8/25.
// Copyright © 2016年 zhoucj. All rights reserved.
//
import UIKit
import AssetsLibrary
class ALAssentModel: NSObject {
var alsseet: ALAsset?
var isChecked = false
var isFirst = false
var orginIndex = -1
var takePhtoto: UIImage?
var currentIndex = -1
init(alsseet: ALAsset?) {
super.init()
self.alsseet = alsseet
}
}
| mit | 596e7271d1d78152edfea8883af348a6 | 19.181818 | 50 | 0.644144 | 3.44186 | false | false | false | false |
erikmartens/NearbyWeather | NearbyWeather/Scenes/Settings Scene/Table View Cells/Settings Imaged Single Label Toggle Cell/SettingsImagedSingleLabelToggleCellViewModel.swift | 1 | 2891 | //
// SettingsImagedSingleLabelToggleCellViewModel.swift
// NearbyWeather
//
// Created by Erik Maximilian Martens on 06.03.22.
// Copyright © 2022 Erik Maximilian Martens. All rights reserved.
//
import RxSwift
import RxCocoa
// MARK: - Dependencies
extension SettingsImagedSingleLabelToggleCellViewModel {
struct Dependencies {
let symbolImageBackgroundColor: UIColor
let symbolImageName: String?
let labelText: String
let isToggleOnObservable: Observable<Bool>
let didFlipToggleSwitchSubject: PublishSubject<Bool>
}
}
// MARK: - Class Definition
final class SettingsImagedSingleLabelToggleCellViewModel: NSObject, BaseCellViewModel {
let associatedCellReuseIdentifier = SettingsImagedSingleLabelToggleCell.reuseIdentifier
// MARK: - Assets
private let disposeBag = DisposeBag()
// MARK: - Properties
private let dependencies: Dependencies
// MARK: - Events
let onDidFlipToggleSwitchSubject = PublishSubject<Bool>()
// MARK: - Observables
private lazy var cellModelRelay: BehaviorRelay<SettingsImagedSingleLabelToggleCellModel> = Self.createCellModelRelay(with: dependencies)
// MARK: - Drivers
lazy var cellModelDriver: Driver<SettingsImagedSingleLabelToggleCellModel> = cellModelRelay.asDriver(onErrorJustReturn: SettingsImagedSingleLabelToggleCellModel())
// MARK: - Initialization
init(dependencies: Dependencies) {
self.dependencies = dependencies
}
// MARK: - Functions
func observeEvents() {
observeDataSource()
observeUserTapEvents()
}
}
extension SettingsImagedSingleLabelToggleCellViewModel {
func observeDataSource() {
dependencies.isToggleOnObservable
.map { [dependencies] isToggleOn -> SettingsImagedSingleLabelToggleCellModel in
SettingsImagedSingleLabelToggleCellModel(
symbolImageBackgroundColor: dependencies.symbolImageBackgroundColor,
symbolImageName: dependencies.symbolImageName,
labelText: dependencies.labelText,
isToggleOn: isToggleOn
)
}
.bind(to: cellModelRelay)
.disposed(by: disposeBag)
}
func observeUserTapEvents() {
onDidFlipToggleSwitchSubject
.bind(to: dependencies.didFlipToggleSwitchSubject)
.disposed(by: disposeBag)
}
}
// MARK: - Observation Helpers
private extension SettingsImagedSingleLabelToggleCellViewModel {
static func createCellModelRelay(with dependencies: Dependencies) -> BehaviorRelay<SettingsImagedSingleLabelToggleCellModel> {
BehaviorRelay<SettingsImagedSingleLabelToggleCellModel>(
value: SettingsImagedSingleLabelToggleCellModel(
symbolImageBackgroundColor: dependencies.symbolImageBackgroundColor,
symbolImageName: dependencies.symbolImageName,
labelText: dependencies.labelText,
isToggleOn: false // start with default value
)
)
}
}
| mit | a8e4b9eb5a95459315ab2e71d04cd70d | 27.613861 | 165 | 0.752941 | 5.688976 | false | false | false | false |
PekanMmd/Pokemon-XD-Code | Revolution Tool CL/enums/PBRItems.swift | 1 | 1785 | //
// XGPokemon.swift
// XG Tool
//
// Created by StarsMmd on 01/06/2015.
// Copyright (c) 2015 StarsMmd. All rights reserved.
//
import Foundation
enum XGItems : XGIndexedValue {
case index(Int)
var index : Int {
switch self {
case .index(let i): return i
}
}
var description : String {
return self.name.string
}
var nameID : Int {
return data.nameID
}
var name : XGString {
return getStringSafelyWithID(id: nameID)
}
var data : XGItem {
get {
return XGItem(index: self.index)
}
}
static func allItems() -> [XGItems] {
var items = [XGItems]()
for i in 0 ..< kNumberOfItems {
items.append(.index(i))
}
return items
}
static func pokeballs() -> [XGItems] {
var items = [XGItems]()
for i in 0 ... 16 {
items.append(.index(i))
}
return items
}
}
func allItems() -> [String : XGItems] {
var dic = [String : XGItems]()
for i in 0 ..< kNumberOfItems {
let a = XGItems.index(i)
dic[a.name.unformattedString.simplified] = a
}
return dic
}
let items = allItems()
func item(_ name: String) -> XGItems {
if items[name.simplified] == nil { printg("couldn't find: " + name) }
return items[name.simplified] ?? .index(0)
}
func allItemsArray() -> [XGItems] {
var items : [XGItems] = []
for i in 0 ..< kNumberOfItems {
items.append(XGItems.index(i))
}
return items
}
extension XGItems: XGEnumerable, Equatable {
var enumerableName: String {
return name.unformattedString.spaceToLength(20)
}
var enumerableValue: String? {
return index.string
}
static var className: String {
return "Items"
}
static var allValues: [XGItems] {
return XGItems.allItems()
}
public static func != (lhs: Self, rhs: Self) -> Bool {
lhs.enumerableValue != rhs.enumerableValue
}
}
| gpl-2.0 | c444e1a4c24299868ef5a54b58f83099 | 14.9375 | 70 | 0.638655 | 3.072289 | false | false | false | false |
vulgur/WeeklyFoodPlan | WeeklyFoodPlan/WeeklyFoodPlan/Views/PlanList/PlanMealCell.swift | 1 | 4270 | //
// PlanMealCell.swift
// WeeklyFoodPlan
//
// Created by vulgur on 2017/3/3.
// Copyright © 2017年 MAD. All rights reserved.
//
import UIKit
class PlanMealCell: UITableViewCell {
@IBOutlet var mealLabel: UILabel!
@IBOutlet var mealCollectionView: UICollectionView!
let planFoodCellIdentifier = "PlanFoodCell"
let cellFontSize: CGFloat = 12
let cellHeight: CGFloat = 30
var meal = Meal()
override func awakeFromNib() {
super.awakeFromNib()
mealCollectionView.dataSource = self
mealCollectionView.delegate = self
mealCollectionView.isScrollEnabled = false
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
override func systemLayoutSizeFitting(_ targetSize: CGSize, withHorizontalFittingPriority horizontalFittingPriority: UILayoutPriority, verticalFittingPriority: UILayoutPriority) -> CGSize {
var totalSize = CGSize.zero
mealCollectionView.frame = CGRect(x: 0, y: 0, width: self.bounds.width, height: CGFloat.leastNormalMagnitude)
mealCollectionView.layoutIfNeeded()
totalSize.height = mealLabel.bounds.height + mealCollectionView.collectionViewLayout.collectionViewContentSize.height + 8*3
totalSize.width = self.bounds.width
// return mealCollectionView.collectionViewLayout.collectionViewContentSize
return totalSize
}
func config(with meal: Meal) {
self.mealLabel.text = meal.name
self.meal = meal
}
}
extension PlanMealCell: UICollectionViewDataSource {
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return meal.mealFoods.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: planFoodCellIdentifier, for: indexPath) as! PlanFoodCell
let food = meal.mealFoods[indexPath.row]
cell.delegate = self
cell.config(by: food)
return cell
}
}
extension PlanMealCell: UICollectionViewDelegateFlowLayout {
private func cellWidthFor(title: String) -> CGFloat {
let font = UIFont.systemFont(ofSize: cellFontSize)
let tagWidth = title.widthWithConstrainedHeight(height: cellHeight, font: font) + 30
return tagWidth
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let title = meal.mealFoods[indexPath.row].food?.name
let cellWidth = cellWidthFor(title: title!)
return CGSize(width: cellWidth, height: cellHeight)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
return UIEdgeInsetsMake(8, 0, 8, 0)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
return 8
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
if let cell = collectionView.cellForItem(at: indexPath) as? PlanFoodCell {
cell.toggle()
}
}
}
extension PlanMealCell: PlanFoodCellDelegate {
func didToggle(cell: PlanFoodCell, isDone: Bool) {
if let indexPath = mealCollectionView.indexPath(for: cell) {
let food = meal.mealFoods[indexPath.row]
updateIngredients(of: food, isDone: isDone)
}
}
private func updateIngredients(of mealFood: MealFood, isDone: Bool) {
BaseManager.shared.transaction {
mealFood.isDone = isDone
if isDone {
mealFood.food?.consumeIngredients()
} else {
mealFood.food?.restoreIngredients()
}
}
}
}
| mit | 0e417098608ff72966dda362bb53ef0d | 34.857143 | 193 | 0.690649 | 5.401266 | false | false | false | false |
JoniVR/VerticalCardSwiper | Sources/PanDirection.swift | 1 | 1538 | // MIT License
//
// Copyright (c) 2017 Joni Van Roost
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
import Foundation
/// The direction of the `UIPanGesture`.
public enum PanDirection: Int {
case Up
case Down
case Left
case Right
case None
/// Returns true is the PanDirection is horizontal.
public var isX: Bool { return self == .Left || self == .Right }
/// Returns true if the PanDirection is vertical.
public var isY: Bool { return self == .Up || self == .Down }
}
| mit | 7e93b5f65352e34d3d1acd3cb837109f | 40.567568 | 81 | 0.730819 | 4.497076 | false | false | false | false |
OMTS/Warg | Example/Tests/Tests.swift | 1 | 7535 | //import Quick
//import Nimble
//import Warg
//
//class WargSpec: QuickSpec {
//
// //Helper method based on https://gist.github.com/yannickl/16f0ed38f0698d9a8ae7
// private func colorWithHexString(string: String) -> UIColor {
// let hexString: NSString = string.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())
// let scanner = NSScanner(string: hexString as String)
//
// if (hexString.hasPrefix("#")) {
// scanner.scanLocation = 1
// }
//
// var color:UInt32 = 0
// scanner.scanHexInt(&color)
//
// let mask = 0x000000FF
// let r = Int(color >> 16) & mask
// let g = Int(color >> 8) & mask
// let b = Int(color) & mask
//
// let red = CGFloat(r) / 255.0
// let green = CGFloat(g) / 255.0
// let blue = CGFloat(b) / 255.0
//
// return UIColor(red:red, green:green, blue:blue, alpha:1)
// }
//
// override func spec() {
// describe("the ColorMatchingStrategy") {
// context("given a linear strategy") {
// it("has the correct name output") {
// let strategy = Warg.ColorMatchingStrategy.ColorMatchingStrategyLinear
// expect(strategy.name).to(equal("Linear Strategy"))
// }
// }
// }
//
// describe("the firstReadableColorInRect method of an UIView") {
//
// var backgroundView: UIView!
// var rect = CGRectZero
// var prefColor = UIColor.blackColor()
// var strategy = ColorMatchingStrategy.ColorMatchingStrategyLinear
// var expectedColor: UIColor!
//
// beforeEach {
// backgroundView = UIView(frame: CGRect(origin: CGPoint(x: 0, y: 0), size: CGSize(width: 100, height: 100)))
// rect = CGRect(origin: CGPoint(x: 0, y: 0), size: CGSize(width: 10, height: 10))
// strategy = ColorMatchingStrategy.ColorMatchingStrategyLinear
// }
//
// context("given a zero rect zone, a prefered color to back, and a linear strategy") {
//
// beforeEach {
// rect = CGRectZero
// prefColor = UIColor.blackColor()
// }
//
// it("throws with an InvalidBackgroundContent error code ") {
// expect{
// try backgroundView.firstReadableColorInRect(rect, preferredColor:prefColor, strategy:strategy)
// }.to(throwError(Warg.WargError.InvalidBackgroundContent))
// }
// }
//
// context("given a black background, a 10X10 pts rect zone, a prefered color to back, and a linear strategy") {
//
// beforeEach {
// backgroundView.backgroundColor = UIColor.blackColor()
// prefColor = UIColor.blackColor()
// }
//
// it("returns #979797 color as the first readable color ") {
// expectedColor = self.colorWithHexString("#979797")
//
// do {
// let readableColor = try backgroundView.firstReadableColorInRect(rect, preferredColor:prefColor, strategy:strategy)
// expect(readableColor).to(equal(expectedColor))
// }
// catch {
// fail("should not throw an error")
// }
// }
// }
//
// context("given a white background, a 10X10 pts rect zone, a prefered color to white, and a linear strategy") {
//
// beforeEach {
// backgroundView.backgroundColor = UIColor.whiteColor()
// prefColor = UIColor.whiteColor()
// }
//
// it("returns #7d7d7d color as the first readable color ") {
// expectedColor = self.colorWithHexString("#7d7d7d")
//
// do {
// let readableColor = try backgroundView.firstReadableColorInRect(rect, preferredColor:prefColor, strategy:strategy)
// expect(readableColor).to(equal(expectedColor))
// }
// catch {
// fail("should not throw an error")
// }
// }
// }
//
// context("given a medium grey background (127,127,127), a 10X10 pts rect zone, a prefered color to black, and a linear strategy") {
//
// beforeEach {
// backgroundView.backgroundColor = UIColor(red: 127.0/255.0, green: 127.0/255.0, blue: 127.0/255.0, alpha: 1.0)
// prefColor = UIColor.blackColor()
// }
//
// it("returns #000000 (black) color as the first readable color ") {
// expectedColor = self.colorWithHexString("#000000")
//
// do {
// let readableColor = try backgroundView.firstReadableColorInRect(rect, preferredColor:prefColor, strategy:strategy)
// expect(readableColor).to(equal(expectedColor))
// }
// catch {
// fail("should not throw an error")
// }
// }
// }
//
// context("given a medium grey background (127,127,127), a 10X10 pts rect zone, a prefered color to white, and a linear strategy") {
//
// beforeEach {
// backgroundView.backgroundColor = UIColor(red: 127.0/255.0, green: 127.0/255.0, blue: 127.0/255.0, alpha: 1.0)
// prefColor = UIColor.whiteColor()
// }
//
// it("returns #ffffff (white) color as the first readable color ") {
// let expectedColor = self.colorWithHexString("#ffffff")
//
// do {
// let readableColor = try backgroundView.firstReadableColorInRect(rect, preferredColor:prefColor, strategy:strategy)
// expect(readableColor).to(equal(expectedColor))
// }
// catch {
// fail("should not throw an error")
// }
// }
// }
//
// context("given a black background, a 10X10 pts rect zone, no prefered color, and a linear strategy") {
//
// beforeEach {
// backgroundView.backgroundColor = UIColor.blackColor()
// }
//
// it("returns #ff5454 color as the first readable color ") {
// let expectedColor = self.colorWithHexString("#979797")
//
// do {
// let readableColor = try backgroundView.firstReadableColorInRect(rect, strategy:strategy)
// expect(readableColor).to(equal(expectedColor))
// }
// catch {
// fail("should not throw an error")
// }
// }
// }
// }
// }
//}
| mit | d97fe4f93f810f5e6eebbaf6d5114bb0 | 43.585799 | 144 | 0.479496 | 4.721178 | false | false | false | false |
sharath-cliqz/browser-ios | Client/Cliqz/Frontend/Browser/CustomViews/ClickableUITableViewCell.swift | 2 | 1303 | //
// ClickableUITableViewCell.swift
// Client
//
// Created by Mahmoud Adam on 11/8/17.
// Copyright © 2017 Cliqz. All rights reserved.
//
import UIKit
class ClickableUITableViewCell: UITableViewCell {
var clickedElement = ""
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
// tab gesture recognizer
let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(cellPressed(_:)))
tapGestureRecognizer.cancelsTouchesInView = false
tapGestureRecognizer.delegate = self
self.addGestureRecognizer(tapGestureRecognizer)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
override func prepareForReuse() {
super.prepareForReuse()
clickedElement = "cell"
}
func cellPressed(_ gestureRecognizer: UIGestureRecognizer) {
}
}
| mpl-2.0 | 7fe263e7ae4d2f62145291bba259f5a3 | 26.702128 | 107 | 0.665131 | 5.336066 | false | false | false | false |
yaobanglin/viossvc | viossvc/AppAPI/SocketAPI/OrderListSocketAPI.swift | 1 | 3079 | //
// OrderListSocketAPI.swift
// viossvc
//
// Created by J-bb on 16/11/30.
// Copyright © 2016年 com.yundian. All rights reserved.
//
import UIKit
class OrderListSocketAPI: BaseSocketAPI, OrderListAPI{
/**
请求订单列表
- parameter last_id: 上一此请求id
- parameter count: 每次请求数量
- parameter complete: 请求完成回调
- parameter error: 错误信息
*/
func list(last_id:Int,count:Int,complete:CompleteBlock,error:ErrorBlock) {
let dict:[String : AnyObject] = [SocketConst.Key.uid : CurrentUserHelper.shared.userInfo.uid, SocketConst.Key.last_id : last_id, SocketConst.Key.count : count]
let packet = SocketDataPacket(opcode: .OrderList, dict: dict)
startDataListRequest(packet, modelClass: OrderListModel.classForCoder(), complete: complete, error: error)
}
/**
修改订单状态
- parameter status: 修改后状态
- parameter from_uid: 订单发起者 ID
- parameter to_uid: 订单 to ID
- parameter order_id: 订单ID
*/
func modfyOrderStatus(status:Int, from_uid:Int,to_uid:Int, order_id:Int,complete:CompleteBlock,error:ErrorBlock) {
let dict:[String : AnyObject] = [SocketConst.Key.order_id:order_id, SocketConst.Key.to_uid : to_uid, SocketConst.Key.from_uid: from_uid, SocketConst.Key.order_status : status]
let packet = SocketDataPacket(opcode: .ModfyOrderStatus, dict: dict, type: SocketConst.type.Chat)
startRequest(packet, complete: complete, error: error)
}
/**
获取订单详情
- parameter orderid: 订单ID
- parameter complete: 完成回调
- parameter error: 错误回调
*/
func getOrderDetail(orderid:Int,complete:CompleteBlock,error:ErrorBlock) {
let dict:[String : AnyObject] = [SocketConst.Key.order_id : orderid]
let packet = SocketDataPacket(opcode: .OrderDetail, dict: dict)
startModelRequest(packet, modelClass: OrderDetailModel.classForCoder(), complete: complete, error: error)
}
/**
获取全部技能标签
*/
func getSkills(complete:CompleteBlock,error:ErrorBlock) {
let packet = SocketDataPacket(opcode: .AllSkills)
startModelsRequest(packet, listName: "skills_list_", modelClass: SkillsModel.classForCoder(), complete: complete, error: error)
}
/**
* 获取预约订单对应的标签
*/
func getSKillsWithModel(skillsString:String?, dict:[Int : SkillsModel]) -> Array<SkillsModel> {
guard skillsString != nil else {
return []
}
let skillsIDArray:[String] = (skillsString!.componentsSeparatedByString(","))
var array:[SkillsModel] = []
for skillID in skillsIDArray {
if skillID != "" {
if let Id = Int(skillID) {
array.append(dict[Id]!)
}
}
}
return array
}
}
| apache-2.0 | e9431d6001e27a1356c6c683c6c31e6c | 31.355556 | 183 | 0.613668 | 4.130496 | false | false | false | false |
GyrosWorkshop/WukongiOS | UI/Cells/PlayingSongCell.swift | 1 | 3182 | import UIKit
import Cartography
class PlayingSongCell: UICollectionViewCell {
private lazy var artworkView: ImageView = {
let view = ImageView()
view.contentMode = .scaleAspectFill
view.clipsToBounds = true
return view
}()
private lazy var titleLabel: UILabel = {
let view = UILabel()
view.font = UIFont.systemFont(ofSize: 20)
view.textColor = .black
return view
}()
private lazy var albumLabel: UILabel = {
let view = UILabel()
view.font = UIFont.systemFont(ofSize: 16)
view.textColor = .black
return view
}()
private lazy var artistLabel: UILabel = {
let view = UILabel()
view.font = UIFont.systemFont(ofSize: 16)
view.textColor = .black
return view
}()
private lazy var infoLabel: UILabel = {
let view = UILabel()
view.font = UIFont.systemFont(ofSize: 12)
view.textColor = .gray
return view
}()
override init(frame: CGRect) {
super.init(frame: frame)
contentView.addSubview(artworkView)
contentView.addSubview(titleLabel)
contentView.addSubview(albumLabel)
contentView.addSubview(artistLabel)
contentView.addSubview(infoLabel)
constrain(contentView, artworkView) { (view, artworkView) in
artworkView.top == view.top
artworkView.bottom == view.bottom
artworkView.leading == view.leading
artworkView.width == artworkView.height
}
constrain(contentView, artworkView, titleLabel) { (view, artworkView, titleLabel) in
titleLabel.leading == artworkView.trailing + 12
titleLabel.trailing == view.trailing
titleLabel.bottom == artworkView.centerY - 15
}
constrain(titleLabel, albumLabel, artistLabel, infoLabel) { (titleLabel, albumLabel, artistLabel, infoLabel) in
align(leading: titleLabel, albumLabel, artistLabel, infoLabel)
align(trailing: titleLabel, albumLabel, artistLabel, infoLabel)
albumLabel.top == titleLabel.bottom
artistLabel.top == albumLabel.bottom
infoLabel.top == artistLabel.bottom
}
}
required convenience init?(coder aDecoder: NSCoder) {
self.init(frame: CGRect.zero)
}
func setData(id: String, song: [Constant.State: String], artworkFile: String?, running: Bool, elapsed: Double, duration: Double) {
let title = song[.title] ?? ""
let album = song[.album] ?? ""
let artist = song[.artist] ?? ""
let format = song[.format] ?? ""
let quality = song[.quality] ?? ""
let artwork = artworkFile ?? ""
let remaining = Int(ceil(duration - elapsed))
titleLabel.text = title
albumLabel.text = album
artistLabel.text = artist
infoLabel.text = running ? "\(String(format: "%d:%0.2d", remaining / 60, remaining % 60)) \(format) \(quality)" : ""
artworkView.setImage(key: "\(id).\((artwork as NSString).pathExtension)", url: URL(string: artwork), placeholder: #imageLiteral(resourceName: "Artwork"))
}
}
| mit | b27cb1f409668c8e34927cd4f6fff719 | 37.337349 | 161 | 0.61785 | 4.828528 | false | false | false | false |
mrommel/MiRoRecipeBook | MiRoRecipeBook/MiRoRecipeBook/Presentation/Integrients/RecipesListViewController.swift | 1 | 2883 | //
// RecipesListViewController.swift
// MiRoRecipeBook
//
// Created by Michael Rommel on 13.12.16.
// Copyright © 2016 MiRo Soft. All rights reserved.
//
import UIKit
class RecipesListViewController: UITableViewController {
var recipes: [Recipe]? //
var recipeListTitle: String?
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.title = self.recipeListTitle
}
}
// MARK: UITableViewDelegate methods
extension RecipesListViewController {
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let indexPath: IndexPath = self.tableView.indexPathForSelectedRow!
let recipe = self.getRecipe(withIndex: indexPath.row)
AppDelegate.shared?.appDependecies?.recipesWireframe?.presentDetail(forRecipe:recipe)
}
func getRecipe(withIndex index: Int) -> Recipe {
return self.recipes![index]
}
override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let footerView = UIView(frame: CGRect(x:0,y: 0,width: tableView.frame.size.width,height: 12))
footerView.backgroundColor = ColorPalette.gray25
return footerView
}
override func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
let footerView = UIView(frame: CGRect(x:0,y: 0,width: tableView.frame.size.width,height: 12))
footerView.backgroundColor = ColorPalette.gray25
return footerView
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 80
}
override func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
return 12.0
}
override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 12.0
}
}
// MARK: UITableViewDataSource methods
extension RecipesListViewController {
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.recipes!.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "recipeCell", for: indexPath) as! RecipeTableViewCell
let recipe = self.getRecipe(withIndex: indexPath.row)
cell.recipeTitleLabel?.text = recipe.name
cell.recipeDescriptionLabel?.text = recipe.teaser
cell.recipeImageView?.setImage(with: recipe.getImageUrl()!, placeholder: UIImage(named: "recipe-default-image.png"))
return cell
}
}
| gpl-3.0 | 2895dc703013fc46b9bf056143414e82 | 31.382022 | 118 | 0.678348 | 5.029668 | false | false | false | false |
mpclarkson/HISwiftExtensions | Example/UIImage.swift | 1 | 1335 | //
// UIImage.swift
// HISwiftExtensions
//
// Created by Matthew on 6/07/2015.
// Copyright © 2015 Hilenium Pty Ltd. All rights reserved.
//
import UIKit
public extension UIImage {
public func tint(tintColor: UIColor) -> UIImage {
UIGraphicsBeginImageContextWithOptions(self.size, false, self.scale)
let context = UIGraphicsGetCurrentContext()
CGContextTranslateCTM(context, 0, self.size.height)
CGContextScaleCTM(context, 1.0, -1.0);
CGContextSetBlendMode(context, CGBlendMode.Normal)
let rect = CGRectMake(0, 0, self.size.width, self.size.height) as CGRect
CGContextClipToMask(context, rect, self.CGImage)
tintColor.setFill()
CGContextFillRect(context, rect)
let newImage = UIGraphicsGetImageFromCurrentImageContext() as UIImage
UIGraphicsEndImageContext()
return newImage
}
public class func getImageWithColor(color: UIColor, size: CGSize) -> UIImage {
let rect = CGRectMake(0, 0, size.width, size.height)
UIGraphicsBeginImageContextWithOptions(size, false, 0)
color.setFill()
UIRectFill(rect)
let image: UIImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
}
| mit | 2b94a345b5a98be14ae5f5a2f548dde5 | 30.023256 | 83 | 0.663418 | 5.130769 | false | false | false | false |
WhisperSystems/Signal-iOS | SignalServiceKit/src/Messages/Stickers/MessageSticker.swift | 1 | 7066 | //
// Copyright (c) 2019 Open Whisper Systems. All rights reserved.
//
import Foundation
import PromiseKit
// MARK: - MessageStickerDraft
@objc
public class MessageStickerDraft: NSObject {
@objc
public let info: StickerInfo
@objc
public var packId: Data {
return info.packId
}
@objc
public var packKey: Data {
return info.packKey
}
@objc
public var stickerId: UInt32 {
return info.stickerId
}
@objc
public let stickerData: Data
@objc
public init(info: StickerInfo, stickerData: Data) {
self.info = info
self.stickerData = stickerData
}
}
// MARK: - MessageSticker
@objc
public class MessageSticker: MTLModel {
// MTLModel requires default values.
@objc
public var info = StickerInfo.defaultValue
@objc
public var packId: Data {
return info.packId
}
@objc
public var packKey: Data {
return info.packKey
}
@objc
public var stickerId: UInt32 {
return info.stickerId
}
// MTLModel requires default values.
@objc
public var attachmentId: String = ""
@objc
public init(info: StickerInfo, attachmentId: String) {
self.info = info
self.attachmentId = attachmentId
super.init()
}
@objc
public override init() {
super.init()
}
@objc
public required init!(coder: NSCoder) {
super.init(coder: coder)
}
@objc
public required init(dictionary dictionaryValue: [String: Any]!) throws {
try super.init(dictionary: dictionaryValue)
}
@objc
public var isValid: Bool {
return info.isValid()
}
@objc
public class func isNoStickerError(_ error: Error) -> Bool {
guard let error = error as? StickerError else {
return false
}
return error == .noSticker
}
@objc
public class func buildValidatedMessageSticker(dataMessage: SSKProtoDataMessage,
transaction: SDSAnyWriteTransaction) throws -> MessageSticker {
guard FeatureFlags.stickerReceive else {
throw StickerError.noSticker
}
guard let stickerProto: SSKProtoDataMessageSticker = dataMessage.sticker else {
throw StickerError.noSticker
}
let packID: Data = stickerProto.packID
let packKey: Data = stickerProto.packKey
let stickerID: UInt32 = stickerProto.stickerID
let dataProto: SSKProtoAttachmentPointer = stickerProto.data
let stickerInfo = StickerInfo(packId: packID, packKey: packKey, stickerId: stickerID)
let attachment = try saveAttachment(dataProto: dataProto,
stickerInfo: stickerInfo,
transaction: transaction)
let attachmentId = attachment.uniqueId
let messageSticker = MessageSticker(info: stickerInfo, attachmentId: attachmentId)
guard messageSticker.isValid else {
throw StickerError.invalidInput
}
return messageSticker
}
private class func saveAttachment(dataProto: SSKProtoAttachmentPointer,
stickerInfo: StickerInfo,
transaction: SDSAnyWriteTransaction) throws -> TSAttachment {
// As an optimization, if the sticker is already installed,
// try to derive an TSAttachmentStream using that.
if let attachment = attachmentForInstalledSticker(dataProto: dataProto,
stickerInfo: stickerInfo,
transaction: transaction) {
return attachment
}
guard let attachmentPointer = TSAttachmentPointer(fromProto: dataProto, albumMessage: nil) else {
throw StickerError.invalidInput
}
attachmentPointer.anyInsert(transaction: transaction)
return attachmentPointer
}
private class func attachmentForInstalledSticker(dataProto: SSKProtoAttachmentPointer,
stickerInfo: StickerInfo,
transaction: SDSAnyWriteTransaction) -> TSAttachmentStream? {
guard let filePath = StickerManager.filepathForInstalledSticker(stickerInfo: stickerInfo, transaction: transaction) else {
// Sticker is not installed.
return nil
}
guard let fileSize = OWSFileSystem.fileSize(ofPath: filePath) else {
owsFailDebug("Could not determine file size for installed sticker.")
return nil
}
do {
let dataSource = try DataSourcePath.dataSource(withFilePath: filePath, shouldDeleteOnDeallocation: false)
let contentType = dataProto.contentType ?? OWSMimeTypeImageWebp
let attachment = TSAttachmentStream(contentType: contentType, byteCount: fileSize.uint32Value, sourceFilename: nil, caption: nil, albumMessageId: nil, shouldAlwaysPad: false)
try attachment.writeCopyingDataSource(dataSource)
attachment.anyInsert(transaction: transaction)
return attachment
} catch {
owsFailDebug("Could not write data source for path: \(filePath), error: \(error)")
return nil
}
}
@objc
public class func buildValidatedMessageSticker(fromDraft draft: MessageStickerDraft,
transaction: SDSAnyWriteTransaction) throws -> MessageSticker {
let attachmentId = try MessageSticker.saveAttachment(stickerData: draft.stickerData,
transaction: transaction)
let messageSticker = MessageSticker(info: draft.info, attachmentId: attachmentId)
guard messageSticker.isValid else {
throw StickerError.assertionFailure
}
return messageSticker
}
private class func saveAttachment(stickerData: Data,
transaction: SDSAnyWriteTransaction) throws -> String {
let fileSize = stickerData.count
guard fileSize > 0 else {
owsFailDebug("Invalid file size for data.")
throw StickerError.assertionFailure
}
let fileExtension = "webp"
let contentType = OWSMimeTypeImageWebp
let fileUrl = OWSFileSystem.temporaryFileUrl(fileExtension: fileExtension)
try stickerData.write(to: fileUrl)
let dataSource = try DataSourcePath.dataSource(with: fileUrl, shouldDeleteOnDeallocation: true)
let attachment = TSAttachmentStream(contentType: contentType, byteCount: UInt32(fileSize), sourceFilename: nil, caption: nil, albumMessageId: nil, shouldAlwaysPad: true)
try attachment.writeConsumingDataSource(dataSource)
attachment.anyInsert(transaction: transaction)
return attachment.uniqueId
}
}
| gpl-3.0 | 991f3e4cb3aeac46f894043bd796be63 | 33.300971 | 186 | 0.623125 | 5.758761 | false | false | false | false |
VladislavJevremovic/Atom-Attack | AtomAttack Shared/Sources/Game/Entities/BackgroundFlashEffect.swift | 1 | 972 | //
// BackgroundFlashEffect.swift
// Atom Attack
//
// Copyright © 2015-2021 Vladislav Jevremović. All rights reserved.
//
import SpriteKit
struct BackgroundFlashEffect: Entity {
// MARK: - Entity
let node: SKNode
// MARK: - Lifecycle
init(sceneBounds: CGRect, fillColor: SKColor) {
node = BackgroundFlashEffect.makeShapeNode(
bounds: sceneBounds,
fillColor: fillColor
)
}
// MARK: - Private Factory Methods
private static func makeShapeNode(
bounds: CGRect,
fillColor: SKColor
) -> SKShapeNode {
let node = SKShapeNode(rect: bounds)
node.fillColor = fillColor
node.alpha = 0.0
node.zPosition = 0
return node
}
// MARK: - Entity
func getInitialPosition(sceneBounds: CGRect) -> CGPoint {
.zero
}
// MARK: - Public Methods
func run(completion: (() -> Void)? = nil) {
completion?()
}
}
| mit | 46fc6296c002854a9d5fb41d4ead58af | 18.795918 | 68 | 0.590722 | 4.409091 | false | false | false | false |
RyoAbe/PARTNER | PARTNER/PARTNER/UI/MainView/HistoryView/HistoryBaseCell.swift | 1 | 5078 | //
// HistoryCell.swift
// PARTNER
//
// Created by RyoAbe on 2015/03/15.
// Copyright (c) 2015年 RyoAbe. All rights reserved.
//
import UIKit
class HistoryBaseCell: UITableViewCell {
var prevStatus: Status!
var nextStatus: Status!
var currentStatus: Status! {
didSet {
if currentStatus == nil {
return
}
textLabel!.text = currentStatus.types.statusType.name
imageView!.image = UIImage(named: currentStatus.types.statusType.iconImageName)
let fmt = NSDateFormatter()
fmt.dateFormat = "yyyy/MM/dd HH:mm"
detailTextLabel?.text = fmt.stringFromDate(currentStatus.date)
setNeedsDisplay()
}
}
override func awakeFromNib() {
super.awakeFromNib()
backgroundColor = UIColor.clearColor()
if let textLabel = textLabel {
textLabel.textColor = UIColor.blackColor()
textLabel.font = UIFont.systemFontOfSize(12)
}
if let detailTextLabel = detailTextLabel {
detailTextLabel.textColor = UIColor(white: 0.2, alpha: 1.000)
detailTextLabel.font = UIFont.systemFontOfSize(10)
}
if let imageView = imageView {
imageView.tintColor = UIColor.blackColor()
}
}
var iconDiameter : CGFloat { return 30 }
var iconRadius : CGFloat { return iconDiameter * 0.5 }
var lineWidth : CGFloat { return 1 / UIScreen.mainScreen().scale }
var lineColor : UIColor { return UIColor.blackColor() }
var iconMargin : CGFloat { return 10 }
var marginPointX : CGFloat { return 20 }
var marginPointY : CGFloat { return 18 }
override func layoutSubviews() {
super.layoutSubviews()
if let imageView = imageView {
var f = imageView.frame
f.size = CGSizeMake(iconDiameter, iconDiameter)
f.origin.y = frame.size.height * 0.5 - f.size.height * 0.5
imageView.frame = f
}
}
override func drawRect(rect: CGRect) {
super.drawRect(rect)
drawCircle()
drawUpperLine()
drawLowerLine()
}
func drawCircle() {
var circle = UIBezierPath(ovalInRect:CGRectInset(imageView!.frame, -4, -4))
lineColor.setStroke()
circle.lineWidth = lineWidth
circle.stroke()
}
func drawUpperLine() {
if prevStatus == nil {
return
}
let isSameState = object_getClassName(prevStatus) == object_getClassName(currentStatus)
let startPointX = isSameState ? imageView!.center.x : frame.size.width * 0.5
let startPoint = CGPointMake(startPointX, 0)
let endPointY = isSameState ? CGRectGetMinY(imageView!.frame) - iconMargin : imageView!.center.y
var endPoint = CGPointMake(imageView!.center.x, endPointY)
if !isSameState {
if currentStatus is MyStatus {
let marginPoint = calcMarginPoint(startPoint, endPoint: endPoint)
endPoint = CGPointMake(endPoint.x + marginPointX, endPoint.y - marginPointY)
} else if currentStatus is PartnersStatus {
endPoint = CGPointMake(endPoint.x - marginPointX, endPoint.y - marginPointY)
}
}
drawLineWithStartPoint(startPoint, endPoint: endPoint)
}
func drawLowerLine() {
if nextStatus == nil {
return
}
let isSameState = object_getClassName(nextStatus) == object_getClassName(currentStatus)
let startPointY = isSameState ? CGRectGetMaxY(imageView!.frame) + iconMargin : imageView!.center.y
let endPointX = isSameState ? imageView!.center.x : frame.size.width * 0.5
var startPoint = CGPointMake(imageView!.center.x, startPointY)
let endPoint = CGPointMake(endPointX, frame.size.height)
if !isSameState {
if currentStatus is MyStatus {
startPoint = CGPointMake(startPoint.x + marginPointX, startPoint.y + marginPointY)
} else if currentStatus is PartnersStatus {
startPoint = CGPointMake(startPoint.x - marginPointX, startPoint.y + marginPointY)
}
}
drawLineWithStartPoint(startPoint, endPoint: endPoint)
}
func calcMarginPoint(startPoint: CGPoint, endPoint: CGPoint) -> CGPoint {
let x = endPoint.x - startPoint.x
let y = endPoint.y - startPoint.y
let radians = atan2f(Float(y), Float(x))
let degree = radians * Float(180 / M_PI)
let marginY = CGFloat(Float(iconRadius + iconMargin) * sinf(degree))
let marginX = CGFloat(Float(iconRadius + iconMargin) * cosf(degree))
return CGPointMake(marginX, marginY)
}
func drawLineWithStartPoint(startPoint: CGPoint, endPoint: CGPoint){
var line = UIBezierPath()
line.moveToPoint(startPoint)
line.addLineToPoint(endPoint)
lineColor.setStroke()
line.lineWidth = lineWidth
line.stroke();
}
}
| gpl-3.0 | 8c177f5804d4b12313f66d11b3b51fe5 | 34.25 | 106 | 0.616627 | 4.838894 | false | false | false | false |
crazypoo/PTools | Pods/NotificationBannerSwift/NotificationBanner/Classes/GrowingNotificationBanner.swift | 2 | 8878 | /*
The MIT License (MIT)
Copyright (c) 2017-2018 Dalton Hinterscher
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH
THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
import UIKit
import SnapKit
open class GrowingNotificationBanner: BaseNotificationBanner {
public enum IconPosition {
case top
case center
}
/// The height of the banner when it is presented
override public var bannerHeight: CGFloat {
get {
if let customBannerHeight = customBannerHeight {
return customBannerHeight
} else {
// Calculate the height based on contents of labels
// Determine available width for displaying the label
var boundingWidth = UIScreen.main.bounds.width - padding * 2
// Substract safeAreaInsets from width, if available
// We have to use keyWindow to ask for safeAreaInsets as `self` only knows its' safeAreaInsets in layoutSubviews
if #available(iOS 11.0, *), let keyWindow = UIApplication.shared.keyWindow {
let safeAreaOffset = keyWindow.safeAreaInsets.left + keyWindow.safeAreaInsets.right
boundingWidth -= safeAreaOffset
}
if leftView != nil {
boundingWidth -= sideViewSize + padding
}
if rightView != nil {
boundingWidth -= sideViewSize + padding
}
let titleHeight = ceil(titleLabel?.sizeThatFits(
CGSize(width: boundingWidth,
height: .greatestFiniteMagnitude)).height ?? 0.0)
let subtitleHeight = ceil(subtitleLabel?.sizeThatFits(
CGSize(width: boundingWidth,
height: .greatestFiniteMagnitude)).height ?? 0.0)
let topOffset: CGFloat = shouldAdjustForNotchFeaturedIphone() ? 44.0 : verticalSpacing
let minHeight: CGFloat = shouldAdjustForNotchFeaturedIphone() ? 88.0 : 64.0
var actualBannerHeight = topOffset + titleHeight + subtitleHeight + verticalSpacing
if !subtitleHeight.isZero && !titleHeight.isZero {
actualBannerHeight += innerSpacing
}
return heightAdjustment + max(actualBannerHeight, minHeight)
}
} set {
customBannerHeight = newValue
}
}
/// Spacing between the last label and the bottom edge of the banner
private let verticalSpacing: CGFloat = 14.0
/// Spacing between title and subtitle
private let innerSpacing: CGFloat = 2.5
/// The bottom most label of the notification if a subtitle is provided
public internal(set) var subtitleLabel: UILabel?
/// The view that is presented on the left side of the notification
private var leftView: UIView?
/// The view that is presented on the right side of the notification
private var rightView: UIView?
/// Square size for left/right view if set
private let sideViewSize: CGFloat
/// Font used for the title label
internal var titleFont: UIFont = UIFont.systemFont(ofSize: 17.5, weight: UIFont.Weight.bold)
/// Font used for the subtitle label
internal var subtitleFont: UIFont = UIFont.systemFont(ofSize: 15.0)
public init(
title: String? = nil,
subtitle: String? = nil,
leftView: UIView? = nil,
rightView: UIView? = nil,
style: BannerStyle = .info,
colors: BannerColorsProtocol? = nil,
iconPosition: IconPosition = .center,
sideViewSize: CGFloat = 24.0
) {
self.leftView = leftView
self.rightView = rightView
self.sideViewSize = sideViewSize
super.init(style: style, colors: colors)
let labelsView = UIStackView()
labelsView.axis = .vertical
labelsView.spacing = innerSpacing
let outerStackView = UIStackView()
outerStackView.spacing = padding
switch iconPosition {
case .top:
outerStackView.alignment = .top
case .center:
outerStackView.alignment = .center
}
if let leftView = leftView {
outerStackView.addArrangedSubview(leftView)
leftView.snp.makeConstraints { $0.size.equalTo(sideViewSize) }
}
outerStackView.addArrangedSubview(labelsView)
if let title = title {
titleLabel = UILabel()
titleLabel!.font = titleFont
titleLabel!.numberOfLines = 0
titleLabel!.textColor = .white
titleLabel!.text = title
titleLabel!.setContentHuggingPriority(.required, for: .vertical)
labelsView.addArrangedSubview(titleLabel!)
}
if let subtitle = subtitle {
subtitleLabel = UILabel()
subtitleLabel!.font = subtitleFont
subtitleLabel!.numberOfLines = 0
subtitleLabel!.textColor = .white
subtitleLabel!.text = subtitle
if title == nil {
subtitleLabel!.setContentHuggingPriority(.required, for: .vertical)
}
labelsView.addArrangedSubview(subtitleLabel!)
}
if let rightView = rightView {
outerStackView.addArrangedSubview(rightView)
rightView.snp.makeConstraints { $0.size.equalTo(sideViewSize) }
}
contentView.addSubview(outerStackView)
outerStackView.snp.makeConstraints { (make) in
if #available(iOS 11.0, *) {
make.left.equalTo(safeAreaLayoutGuide).offset(padding)
make.right.equalTo(safeAreaLayoutGuide).offset(-padding)
} else {
make.left.equalToSuperview().offset(padding)
make.right.equalToSuperview().offset(-padding)
}
make.centerY.equalToSuperview()
}
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func spacerViewHeight() -> CGFloat {
return super.spacerViewHeight() + heightAdjustment
}
}
public extension GrowingNotificationBanner {
func applyStyling(
cornerRadius: CGFloat? = nil,
titleFont: UIFont? = nil,
titleColor: UIColor? = nil,
titleTextAlign: NSTextAlignment? = nil,
subtitleFont: UIFont? = nil,
subtitleColor: UIColor? = nil,
subtitleTextAlign: NSTextAlignment? = nil
) {
if let cornerRadius = cornerRadius {
contentView.layer.cornerRadius = cornerRadius
}
if let titleFont = titleFont {
self.titleFont = titleFont
titleLabel!.font = titleFont
}
if let titleColor = titleColor {
titleLabel!.textColor = titleColor
}
if let titleTextAlign = titleTextAlign {
titleLabel!.textAlignment = titleTextAlign
}
if let subtitleFont = subtitleFont {
self.subtitleFont = subtitleFont
subtitleLabel!.font = subtitleFont
}
if let subtitleColor = subtitleColor {
subtitleLabel!.textColor = subtitleColor
}
if let subtitleTextAlign = subtitleTextAlign {
subtitleLabel!.textAlignment = subtitleTextAlign
}
if titleFont != nil || subtitleFont != nil {
updateBannerHeight()
}
}
}
| mit | c2278eb46676dc18497901ef26334136 | 36.146444 | 147 | 0.597207 | 5.902926 | false | false | false | false |
xgdgsc/AlecrimCoreData | Source/AlecrimCoreData/Core/Protocols/AttributeQueryType.swift | 1 | 2864 | //
// AttributeQueryType.swift
// AlecrimCoreData
//
// Created by Vanderlei Martinelli on 2015-08-08.
// Copyright (c) 2015 Alecrim. All rights reserved.
//
import Foundation
import CoreData
public protocol AttributeQueryType: CoreDataQueryable {
var returnsDistinctResults: Bool { get set }
var propertiesToFetch: [String] { get set }
}
// MARK: -
extension AttributeQueryType {
public func distinct() -> Self {
var clone = self
clone.returnsDistinctResults = true
return self
}
}
// MARK: - GenericQueryable
extension AttributeQueryType {
public func toArray() -> [Self.Item] {
var results: [Self.Item] = []
do {
let fetchRequestResult = try self.dataContext.executeFetchRequest(self.toFetchRequest())
if let dicts = fetchRequestResult as? [NSDictionary] {
for dict in dicts {
guard dict.count == 1, let value = dict.allValues.first as? Self.Item else {
throw AlecrimCoreDataError.UnexpectedValue(value: dict)
}
results.append(value)
}
}
else {
throw AlecrimCoreDataError.UnexpectedValue(value: fetchRequestResult)
}
}
catch {
// TODO: throw error?
}
return results
}
}
extension AttributeQueryType where Self.Item: NSDictionary {
public func toArray() -> [NSDictionary] {
do {
let fetchRequestResult = try self.dataContext.executeFetchRequest(self.toFetchRequest())
if let dicts = fetchRequestResult as? [NSDictionary] {
return dicts
}
else {
throw AlecrimCoreDataError.UnexpectedValue(value: fetchRequestResult)
}
}
catch {
// TODO: throw error?
return [NSDictionary]()
}
}
}
// MARK: - CoreDataQueryable
extension AttributeQueryType {
public func toFetchRequest() -> NSFetchRequest {
let fetchRequest = NSFetchRequest()
fetchRequest.entity = self.entityDescription
fetchRequest.fetchOffset = self.offset
fetchRequest.fetchLimit = self.limit
fetchRequest.fetchBatchSize = (self.limit > 0 && self.batchSize > self.limit ? 0 : self.batchSize)
fetchRequest.predicate = self.predicate
fetchRequest.sortDescriptors = self.sortDescriptors
//
fetchRequest.resultType = .DictionaryResultType
fetchRequest.returnsDistinctResults = self.returnsDistinctResults
fetchRequest.propertiesToFetch = self.propertiesToFetch
//
return fetchRequest
}
}
| mit | 421f829b32f92a16fd65c53fc458d8ec | 25.036364 | 106 | 0.582053 | 5.571984 | false | false | false | false |
apatronl/GifMaker | GifMaker/Gif.swift | 1 | 1500 | //
// Gif.swift
// GifMaker
//
// Created by Alejandrina Patron on 1/3/17.
// Copyright © 2017 Alejandrina Patron. All rights reserved.
//
import UIKit
class Gif: NSObject, NSCoding {
let url: URL?
let videoURL: URL?
var caption: String?
let gifImage: UIImage?
var gifData: NSData?
init(url: URL, videoURL: URL, caption: String?) {
self.url = url
self.videoURL = videoURL
self.caption = caption
self.gifImage = UIImage.gif(url: url.absoluteString)!
self.gifData = nil
}
init(name: String) {
self.url = nil
self.videoURL = nil
self.caption = nil
self.gifData = nil
self.gifImage = UIImage.gif(name: name)
}
required init?(coder aDecoder: NSCoder) {
self.url = aDecoder.decodeObject(forKey: "url") as? URL
self.videoURL = aDecoder.decodeObject(forKey: "videoURL") as? URL
self.caption = aDecoder.decodeObject(forKey: "caption") as? String
self.gifImage = aDecoder.decodeObject(forKey: "gifImage") as? UIImage
self.gifData = aDecoder.decodeObject(forKey: "gifData") as? NSData
}
func encode(with aCoder: NSCoder) {
aCoder.encode(self.url, forKey: "url")
aCoder.encode(self.videoURL, forKey: "videoURL")
aCoder.encode(self.caption, forKey: "caption")
aCoder.encode(self.gifImage, forKey: "gifImage")
aCoder.encode(self.gifData, forKey: "gifData")
}
}
| mit | 7b3b9e7cbcecb9dc46ce4b78f35cad32 | 28.392157 | 77 | 0.616411 | 3.965608 | false | false | false | false |
kazedayo/GaldenApp | GaldenApp/View Controllers/UserDetailViewController.swift | 1 | 3319 | //
// UserDetailViewController.swift
// GaldenApp
//
// Created by Kin Wa Lam on 19/10/2017.
// Copyright © 2017年 1080@galden. All rights reserved.
//
import UIKit
import KeychainSwift
import Toaster
class UserDetailViewController: UITableViewController,UINavigationControllerDelegate,UITextFieldDelegate {
@IBOutlet weak var userName: UILabel!
@IBOutlet weak var logoutButton: UIButton!
@IBOutlet weak var leaveNameTextField: UITextField!
@IBOutlet weak var blocklistButton: UIButton!
let api = HKGaldenAPI()
override func viewDidLoad() {
super.viewDidLoad()
//cancelButton.heroModifiers = [.position(CGPoint.init(x: 500, y: cancelButton.frame.midY))]
let keychain = KeychainSwift()
if (keychain.get("userKey") != nil) {
loggedIn()
}
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
@IBAction func logoutButtonPressed(_ sender: UIButton) {
api.logout {
let keychain = KeychainSwift()
keychain.delete("isLoggedIn")
self.performSegue(withIdentifier: "logout", sender: self)
}
}
@IBAction func cancelButtonPressed(_ sender: UIBarButtonItem) {
dismiss(animated: true, completion: nil)
}
@IBAction func confirmButtonPressed(_ sender: UIButton) {
leaveNameTextField.endEditing(true)
let keychain = KeychainSwift()
keychain.set(leaveNameTextField.text!, forKey: "LeaveNameText")
}
@IBAction func changeNameButtonPressed(_ sender: UIButton) {
let alert = UIAlertController.init(title: "改名怪", message: "你想改咩名?", preferredStyle: .alert)
alert.addTextField {
textField in
textField.placeholder = "新名"
}
alert.addAction(UIAlertAction(title:"改名",style:.default,handler:{
[weak alert] _ in
let textField = alert?.textFields![0]
self.api.changeName(name: (textField?.text)!, completion: {
status,newName in
if status == "true" {
let keychain = KeychainSwift()
keychain.set(newName, forKey: "userName")
self.loggedIn()
} else if status == "false" {
Toast.init(text: "改名失敗", delay: 0, duration: 1).show()
}
})
}))
present(alert,animated: true,completion: nil)
}
func loggedIn() {
let keychain = KeychainSwift()
self.userName.text = "已登入為: " + keychain.get("userName")! + " (UID: " + keychain.get("userID")! + ")"
leaveNameTextField.text = keychain.get("LeaveNameText")
self.userName.textColor = UIColor.gray
}
}
| mit | 81c849bc481c6cddde553012053e4940 | 33.484211 | 109 | 0.615079 | 4.810573 | false | false | false | false |
ibm-bluemix-mobile-services/bms-clientsdk-swift-analytics | Source/Analytics/BMSAnalytics+watchOS.swift | 1 | 5609 | /*
* Copyright 2016 IBM Corp.
* 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 WatchKit
import BMSCore
// MARK: - Swift 3
#if swift(>=3.0)
public extension Analytics {
/**
Starts a timer to record the length of time the watchOS app is being used before becoming inactive.
This event will be recorded and sent to the Mobile Analytics service, provided that the `Analytics.enabled` property is set to `true`.
This should be called in the `ExtensionDelegate` `applicationDidBecomeActive()` method.
*/
public static func recordApplicationDidBecomeActive() {
BMSAnalytics.logSessionStart()
}
/**
Ends the timer started by the `Analytics startRecordingApplicationLifecycleEvents` method.
This event will be recorded and sent to the Mobile Analytics service, provided that the `Analytics.enabled` property is set to `true`.
This should be called in the `ExtensionDelegate` `applicationWillResignActive()` method.
*/
public static func recordApplicationWillResignActive() {
BMSAnalytics.logSessionEnd()
}
}
// MARK: -
public extension BMSAnalytics {
// Create a UUID for the current device and save it to the keychain
// This is necessary because there is currently no API for programatically retrieving the UDID for watchOS devices
internal static var uniqueDeviceId: String? {
// First, check if a UUID was already created
let bmsUserDefaults = UserDefaults(suiteName: Constants.userDefaultsSuiteName)
guard bmsUserDefaults != nil else {
Analytics.logger.error(message: "Failed to get an ID for this device.")
return ""
}
var deviceId = bmsUserDefaults!.string(forKey: Constants.Metadata.Analytics.deviceId)
if deviceId == nil {
deviceId = UUID().uuidString
bmsUserDefaults!.setValue(deviceId, forKey: Constants.Metadata.Analytics.deviceId)
}
return deviceId!
}
internal static func getWatchOSDeviceInfo() -> (String, String, String) {
var osVersion = "", model = "", deviceId = ""
let device = WKInterfaceDevice.current()
osVersion = device.systemVersion
model = device.model
deviceId = BMSAnalytics.getDeviceId(from: BMSAnalytics.uniqueDeviceId)
return (osVersion, model, deviceId)
}
}
/**************************************************************************************************/
// MARK: - Swift 2
#else
public extension Analytics {
/**
Starts a timer to record the length of time the watchOS app is being used before becoming inactive.
This event will be recorded and sent to the Mobile Analytics service, provided that the `Analytics.enabled` property is set to `true`.
This should be called in the `ExtensionDelegate` `applicationDidBecomeActive()` method.
*/
public static func recordApplicationDidBecomeActive() {
BMSAnalytics.logSessionStart()
}
/**
Ends the timer started by the `Analytics startRecordingApplicationLifecycleEvents` method.
This event will be recorded and sent to the Mobile Analytics service, provided that the `Analytics.enabled` property is set to `true`.
This should be called in the `ExtensionDelegate` `applicationWillResignActive()` method.
*/
public static func recordApplicationWillResignActive() {
BMSAnalytics.logSessionEnd()
}
}
// MARK: -
public extension BMSAnalytics {
// Create a UUID for the current device and save it to the keychain
// This is necessary because there is currently no API for programatically retrieving the UDID for watchOS devices
internal static var uniqueDeviceId: String? {
// First, check if a UUID was already created
let bmsUserDefaults = NSUserDefaults(suiteName: Constants.userDefaultsSuiteName)
guard bmsUserDefaults != nil else {
Analytics.logger.error(message: "Failed to get an ID for this device.")
return ""
}
var deviceId = bmsUserDefaults!.stringForKey(Constants.Metadata.Analytics.deviceId)
if deviceId == nil {
deviceId = NSUUID().UUIDString
bmsUserDefaults!.setValue(deviceId, forKey: Constants.Metadata.Analytics.deviceId)
}
return deviceId!
}
internal static func getWatchOSDeviceInfo() -> (String, String, String) {
var osVersion = "", model = "", deviceId = ""
let device = WKInterfaceDevice.currentDevice()
osVersion = device.systemVersion
model = device.model
deviceId = BMSAnalytics.getDeviceId(from: BMSAnalytics.uniqueDeviceId)
return (osVersion, model, deviceId)
}
}
#endif
| apache-2.0 | da184c111486dc9aaf01a71811068bac | 28.994624 | 142 | 0.642588 | 5.390338 | false | false | false | false |
WSDOT/wsdot-ios-app | wsdot/AppDelegate.swift | 1 | 17782 | //
// AppDelegate.swift
// wsdot
//
// Copyright (c) 2016 Washington State Department of Transportation
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>
//
import UIKit
import Firebase
import GoogleMobileAds
import UserNotifications
import GoogleMaps
import RealmSwift
import Realm
import EasyTipView
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate, MessagingDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
let theme = Theme(rawValue: EventStore.getActiveEventThemeId()) ?? .defaultTheme
ThemeManager.applyTheme(theme: theme)
migrateRealm()
CachesStore.initCacheItem()
GMSServices.provideAPIKey(ApiKeys.getGoogleAPIKey())
FirebaseApp.configure()
application.registerForRemoteNotifications()
GADMobileAds.sharedInstance().start(completionHandler: nil)
// print(GADMobileAds.sharedInstance().sdkVersion)
// GADMobileAds.sharedInstance().requestConfiguration.testDeviceIdentifiers = [ "9c3a9dd6ec9e8078003e5d4f8c885944" ]
// EasyTipView Setup
var preferences = EasyTipView.Preferences()
preferences.drawing.font = UIFont(name: "Futura-Medium", size: 13)!
preferences.drawing.foregroundColor = UIColor.white
preferences.drawing.backgroundColor = UIColor(hue:0.46, saturation:0.99, brightness:0.6, alpha:1)
preferences.drawing.arrowPosition = EasyTipView.ArrowPosition.top
// Make these preferences global for all future EasyTipViews
EasyTipView.globalPreferences = preferences
// Reset Warning each time app starts
UserDefaults.standard.set(false, forKey: UserDefaultsKeys.hasSeenWarning)
if #available(iOS 10.0, *) {
// For iOS 10 display notification (sent via APNS)
UNUserNotificationCenter.current().delegate = self
Messaging.messaging().delegate = self
}
FerryRealmStore.flushOldData()
CamerasStore.flushOldData()
TravelTimesStore.flushOldData()
HighwayAlertsStore.flushOldData()
NotificationsStore.flushOldData()
TollRateSignsStore.flushOldData()
TollRateTableStore.flushOldData()
BorderWaitStore.flushOldData()
BridgeAlertsStore.flushOldData()
NSSetUncaughtExceptionHandler { exception in
print(exception)
print(exception.callStackSymbols)
}
return true
}
func applicationWillTerminate(_ application: UIApplication) {
FerryRealmStore.flushOldData()
CamerasStore.flushOldData()
TravelTimesStore.flushOldData()
HighwayAlertsStore.flushOldData()
NotificationsStore.flushOldData()
TollRateSignsStore.flushOldData()
TollRateTableStore.flushOldData()
BorderWaitStore.flushOldData()
BridgeAlertsStore.flushOldData()
}
// MARK: Push Notifications
func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String?) {
// ensure topic subs are always in sync with what we have stored on the client.
for topic in NotificationsStore.getTopics() {
if topic.subscribed {
Messaging.messaging().subscribe(toTopic: topic.topic)
} else {
Messaging.messaging().unsubscribe(fromTopic: topic.topic)
}
}
}
// catches notifications while app is in foreground and displays
@available(iOS 10.0, *)
func userNotificationCenter(_ center: UNUserNotificationCenter,
willPresent notification: UNNotification,
withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
UIApplication.shared.applicationIconBadgeNumber = 0
// Display the notificaion.
completionHandler(UNNotificationPresentationOptions.alert)
}
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any],
fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
print("didReceiveRemoteNotification w/ completionHandler.")
Messaging.messaging().appDidReceiveMessage(userInfo)
if let alertType = userInfo["type"] as? String {
if alertType == "ferry_alert" {
MyAnalytics.event(category: "Notification", action: "Message Opened" , label: "Ferry Alert")
if let routeIdString = userInfo["route_id"] as? String {
if let routeId = Int(routeIdString){
launchFerriesAlertScreen(routeId: routeId)
}
}
} else if alertType == "highway_alert" {
MyAnalytics.event(category: "Notification", action: "Message Opened" , label: "Traffic Alert")
if let alertIdString = userInfo["alert_id"] as? String, let latString = userInfo["lat"] as? String, let longString = userInfo["long"] as? String {
if let alertId = Int(alertIdString), let lat = Double(latString), let long = Double(longString) {
launchTrafficAlertDetailsScreen(alertId: alertId, latitude: lat, longitude: long)
}
}
} else if alertType == "bridge_alert" {
MyAnalytics.event(category: "Notification", action: "Message Opened" , label: "Bridge Alert")
launchBridgeAlertsScreen()
}
}
completionHandler(UIBackgroundFetchResult.newData)
}
// unused - old method from before bridge alerts had their own section
func launchTrafficAlertDetailsScreenWithNoAlert(
title: String, description: String, latitude: Double, longitude: Double) {
let trafficMapStoryboard: UIStoryboard = UIStoryboard(name: "TrafficMap", bundle: nil)
// Set up nav and vc stack
let trafficMapNav = trafficMapStoryboard.instantiateViewController(withIdentifier: "TrafficMapNav") as! UINavigationController
let trafficMap = trafficMapStoryboard.instantiateViewController(withIdentifier: "TrafficMapViewController") as! TrafficMapViewController
let HighwayAlertStoryboard: UIStoryboard = UIStoryboard(name: "HighwayAlert", bundle: nil)
let highwayAlertDetails = HighwayAlertStoryboard.instantiateViewController(withIdentifier: "HighwayAlertViewController") as! HighwayAlertViewController
highwayAlertDetails.fromPush = true
highwayAlertDetails.hasAlert = false
highwayAlertDetails.pushLat = latitude
highwayAlertDetails.pushLong = longitude
highwayAlertDetails.title = title
highwayAlertDetails.pushMessage = description
// assign vc stack to new nav controller
trafficMapNav.setViewControllers([trafficMap, highwayAlertDetails], animated: false)
setNavController(newNavigationController: trafficMapNav)
}
func launchTrafficAlertDetailsScreen(alertId: Int, latitude: Double, longitude: Double){
let trafficMapStoryboard: UIStoryboard = UIStoryboard(name: "TrafficMap", bundle: nil)
// Set up nav and vc stack
let trafficMapNav = trafficMapStoryboard.instantiateViewController(withIdentifier: "TrafficMapNav") as! UINavigationController
let trafficMap = trafficMapStoryboard.instantiateViewController(withIdentifier: "TrafficMapViewController") as! TrafficMapViewController
let HighwayAlertStoryboard: UIStoryboard = UIStoryboard(name: "HighwayAlert", bundle: nil)
let highwayAlertDetails = HighwayAlertStoryboard.instantiateViewController(withIdentifier: "HighwayAlertViewController") as! HighwayAlertViewController
highwayAlertDetails.alertId = alertId
highwayAlertDetails.fromPush = true
highwayAlertDetails.pushLat = latitude
highwayAlertDetails.pushLong = longitude
// assign vc stack to new nav controller
trafficMapNav.setViewControllers([trafficMap, highwayAlertDetails], animated: false)
setNavController(newNavigationController: trafficMapNav)
}
func launchFerriesAlertScreen(routeId: Int) {
let mainStoryboard: UIStoryboard = UIStoryboard(name: "Ferries", bundle: nil)
// Set up nav and vc stack
let ferriesNav = mainStoryboard.instantiateViewController(withIdentifier: "FerriesNav") as! UINavigationController
let ferrySchedules = mainStoryboard.instantiateViewController(withIdentifier: "RouteSchedulesViewController") as! RouteSchedulesViewController
let ferrySailings = mainStoryboard.instantiateViewController(withIdentifier: "RouteDeparturesViewController") as! RouteDeparturesViewController
ferrySailings.routeId = routeId
let ferryAlerts = mainStoryboard.instantiateViewController(withIdentifier: "RouteAlertsViewController") as! RouteAlertsViewController
ferryAlerts.routeId = routeId
// assign vc stack to new nav controller
ferriesNav.setViewControllers([ferrySchedules, ferrySailings, ferryAlerts], animated: false)
setNavController(newNavigationController: ferriesNav)
}
func launchBridgeAlertsScreen(){
let trafficMapStoryboard: UIStoryboard = UIStoryboard(name: "TrafficMap", bundle: nil)
// Set up nav and vc stack
let trafficMapNav = trafficMapStoryboard.instantiateViewController(withIdentifier: "TrafficMapNav") as! UINavigationController
let trafficMap = trafficMapStoryboard.instantiateViewController(withIdentifier: "TrafficMapViewController") as! TrafficMapViewController
let BridgeAlertsStoryboard: UIStoryboard = UIStoryboard(name: "BridgeAlerts", bundle: nil)
let BridgeAlertsVC = BridgeAlertsStoryboard.instantiateViewController(withIdentifier: "BridgeAlertsViewController") as! BridgeAlertsViewController
// assign vc stack to new nav controller
trafficMapNav.setViewControllers([trafficMap, BridgeAlertsVC], animated: false)
setNavController(newNavigationController: trafficMapNav)
}
func setNavController(newNavigationController: UINavigationController){
// get the main split view, check how VCs are currently displayed
let rootViewController = self.window!.rootViewController as! UISplitViewController
if (rootViewController.isCollapsed) {
// Only one vc displayed, pop current stack and assign new vc stack
let nav = rootViewController.viewControllers[0] as! UINavigationController
nav.popToRootViewController(animated: false)
nav.pushViewController(newNavigationController, animated: true)
print("1")
} else {
// Master/Detail displayed, swap out the current detail view with the new stack of view controllers.
newNavigationController.viewControllers[0].navigationItem.leftBarButtonItem = rootViewController.displayModeButtonItem
newNavigationController.viewControllers[0].navigationItem.leftItemsSupplementBackButton = true
rootViewController.showDetailViewController(newNavigationController, sender: self)
print("2")
}
}
// MARK: Realm
func migrateRealm(){
Realm.Configuration.defaultConfiguration = Realm.Configuration(
schemaVersion: 10,
migrationBlock: { migration, oldSchemaVersion in
if (oldSchemaVersion < 1) {
// The enumerateObjects(ofType:_:) method iterates
// over every MountainPassItem object stored in the Realm file
migration.enumerateObjects(ofType: MountainPassItem.className()) { oldObject, newObject in
// pull the camera ids from the old field and place it into the new
let oldCameras = oldObject!["cameras"] as! List<DynamicObject>
let passCameraIds = newObject!["cameraIds"] as! List<DynamicObject>
for camera in oldCameras {
let newPassCameraId = migration.create(PassCameraIDItem.className())
newPassCameraId["cameraId"] = camera["cameraId"] as! Int
passCameraIds.append(newPassCameraId)
}
}
}
if (oldSchemaVersion < 2) {
// The enumerateObjects(ofType:_:) method iterates
// over every TravelTime object stored in the Realm file
migration.enumerateObjects(ofType: TravelTimeItem.className()) { oldObject, newObject in
// Add start/end lat/long to travel times
newObject!["startLatitude"] = 0.0
newObject!["endLatitude"] = 0.0
newObject!["startLongitude"] = 0.0
newObject!["endLongitude"] = 0.0
}
}
if (oldSchemaVersion < 3) {
migration.deleteData(forType: TravelTimeItemGroup.className())
migration.deleteData(forType: TravelTimeItem.className())
migration.deleteData(forType: CacheItem.className())
}
if (oldSchemaVersion < 4) {
migration.enumerateObjects(ofType: CacheItem.className()) { oldObject, newObject in
newObject!["notificationsLastUpdate"] = Date(timeIntervalSince1970: 0)
}
}
if (oldSchemaVersion < 5) {
migration.enumerateObjects(ofType: CacheItem.className()) { oldObject, newObject in
newObject!["tollRatesLastUpdate"] = Date(timeIntervalSince1970: 0)
}
}
/*
Adds milepost and direction fields.
Clears cache times to force refresh
*/
if (oldSchemaVersion < 6) {
migration.enumerateObjects(ofType: CameraItem.className()) { oldObject, newObject in
newObject!["milepost"] = -1
newObject!["direction"] = ""
}
migration.deleteData(forType: CacheItem.className())
}
/*
Adds favorite field to borderwaits.
Clears cache times to force refresh
*/
if (oldSchemaVersion < 7) {
migration.enumerateObjects(ofType: BorderWaitItem.className()) { oldObject, newObject in
newObject!["selected"] = false
newObject!["delete"] = false
}
migration.deleteData(forType: CacheItem.className())
}
/*
Adds cameraId and tavelTimeId field to my route item.
Clears cache times to force refresh
*/
if (oldSchemaVersion < 8) {
migration.enumerateObjects(ofType: MyRouteItem.className()) { oldObject, newObject in
newObject!["cameraIds"] = List<Int>()
newObject!["foundCameras"] = false
newObject!["travelTimeIds"] = List<Int>()
newObject!["foundTravelTimes"] = false
}
migration.deleteData(forType: CacheItem.className())
}
/*
tollTableItem added and cache item for toll table data
*/
if (oldSchemaVersion < 9) {
migration.enumerateObjects(ofType: CacheItem.className()) { oldObject, newObject in
newObject!["staticTollRatesLastUpdate"] = Date(timeIntervalSince1970: 0)
}
}
/*
BridgeAlertItem added and cache item for bridge alert date
*/
if (oldSchemaVersion < 10) {
migration.enumerateObjects(ofType: CacheItem.className()) { oldObject, newObject in
newObject!["bridgeAlertsLastUpdate"] = Date(timeIntervalSince1970: 0)
}
}
})
}
}
| gpl-3.0 | c4de6fb724847d27e1a0735dd08b6af1 | 46.292553 | 169 | 0.62462 | 6.185043 | false | false | false | false |
natecook1000/swift | validation-test/Reflection/reflect_multiple_types.swift | 1 | 13722 | // RUN: %empty-directory(%t)
// RUN: %target-build-swift -lswiftSwiftReflectionTest %s -o %t/reflect_multiple_types
// RUN: %target-codesign %t/reflect_multiple_types
// Link %target-swift-reflection-test into %t to convince %target-run to copy
// it.
// RUN: ln -s %target-swift-reflection-test %t/swift-reflection-test
// RUN: %target-run %t/swift-reflection-test %t/reflect_multiple_types | %FileCheck %s --check-prefix=CHECK-%target-ptrsize
// REQUIRES: objc_interop
// REQUIRES: executable_test
// FIXME: Handle different forms of %target-run more robustly
// REQUIRES: OS=macosx
import SwiftReflectionTest
import Foundation
class TestClass {
var t00: Array<Int>
var t01: Bool
var t02: Character
var t03: Dictionary<Int, Int>
var t04: Double
var t05: Float
var t06: Int
var t07: Int16
var t08: Int32
var t09: Int64
var t10: Int8
var t11: NSArray
var t12: NSNumber
var t13: NSSet
var t14: NSString
var t15: Set<Int>
var t16: String
var t17: UInt
var t18: UInt16
var t19: UInt32
var t20: UInt64
var t21: UInt8
init(
t00: Array<Int>,
t01: Bool,
t02: Character,
t03: Dictionary<Int, Int>,
t04: Double,
t05: Float,
t06: Int,
t07: Int16,
t08: Int32,
t09: Int64,
t10: Int8,
t11: NSArray,
t12: NSNumber,
t13: NSSet,
t14: NSString,
t15: Set<Int>,
t16: String,
t17: UInt,
t18: UInt16,
t19: UInt32,
t20: UInt64,
t21: UInt8
) {
self.t00 = t00
self.t01 = t01
self.t02 = t02
self.t03 = t03
self.t04 = t04
self.t05 = t05
self.t06 = t06
self.t07 = t07
self.t08 = t08
self.t09 = t09
self.t10 = t10
self.t11 = t11
self.t12 = t12
self.t13 = t13
self.t14 = t14
self.t15 = t15
self.t16 = t16
self.t17 = t17
self.t18 = t18
self.t19 = t19
self.t20 = t20
self.t21 = t21
}
}
var obj = TestClass(
t00: [1, 2, 3],
t01: true,
t02: "A",
t03: [1: 3, 2: 2, 3: 1],
t04: 123.45,
t05: 123.45,
t06: 123,
t07: 123,
t08: 123,
t09: 123,
t10: 123,
t11: [1, 2, 3],
t12: 123,
t13: [1, 2, 3, 3, 2, 1],
t14: "Hello, NSString!",
t15: [1, 2, 3, 3, 2, 1],
t16: "Hello, Reflection!",
t17: 123,
t18: 123,
t19: 123,
t20: 123,
t21: 123
)
reflect(object: obj)
// CHECK-64: Reflecting an object.
// CHECK-64: Instance pointer in child address space: 0x{{[0-9a-fA-F]+}}
// CHECK-64: Type reference:
// CHECK-64: (class reflect_multiple_types.TestClass)
// CHECK-64: Type info:
// CHECK-64-NEXT: (class_instance size=177 alignment=8 stride=184 num_extra_inhabitants=0
// CHECK-64-NEXT: (field name=t00 offset=16
// CHECK-64-NEXT: (struct size=8 alignment=8 stride=8 num_extra_inhabitants=1
// (unstable implementation details omitted)
// CHECK-64: (field name=t01 offset=24
// CHECK-64-NEXT: (struct size=1 alignment=1 stride=1 num_extra_inhabitants=254
// CHECK-64-NEXT: (field name=_value offset=0
// CHECK-64-NEXT: (builtin size=1 alignment=1 stride=1 num_extra_inhabitants=254))))
// CHECK-64-NEXT: (field name=t02 offset=32
// CHECK-64-NEXT: (struct size=8 alignment=8 stride=8 num_extra_inhabitants=0
// CHECK-64-NEXT: (field name=_representation offset=0
// CHECK-64-NEXT: (multi_payload_enum size=8 alignment=8 stride=8 num_extra_inhabitants=0
// CHECK-64-NEXT: (field name=smallUTF16 offset=0
// CHECK-64-NEXT: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=2147483647))
// CHECK-64-NEXT: (field name=large offset=0
// CHECK-64-NEXT: (reference kind=strong refcounting=native))))))
// CHECK-64-NEXT: (field name=t03 offset=40
// CHECK-64-NEXT: (struct size=8 alignment=8 stride=8 num_extra_inhabitants=0
// (unstable implementation details omitted)
// CHECK-64: (field name=t04 offset=48
// CHECK-64-NEXT: (struct size=8 alignment=8 stride=8 num_extra_inhabitants=0
// CHECK-64-NEXT: (field name=_value offset=0
// CHECK-64-NEXT: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=0))))
// CHECK-64-NEXT: (field name=t05 offset=56
// CHECK-64-NEXT: (struct size=4 alignment=4 stride=4 num_extra_inhabitants=0
// CHECK-64-NEXT: (field name=_value offset=0
// CHECK-64-NEXT: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=0))))
// CHECK-64-NEXT: (field name=t06 offset=64
// CHECK-64-NEXT: (struct size=8 alignment=8 stride=8 num_extra_inhabitants=0
// CHECK-64-NEXT: (field name=_value offset=0
// CHECK-64-NEXT: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=0))))
// CHECK-64-NEXT: (field name=t07 offset=72
// CHECK-64-NEXT: (struct size=2 alignment=2 stride=2 num_extra_inhabitants=0
// CHECK-64-NEXT: (field name=_value offset=0
// CHECK-64-NEXT: (builtin size=2 alignment=2 stride=2 num_extra_inhabitants=0))))
// CHECK-64-NEXT: (field name=t08 offset=76
// CHECK-64-NEXT: (struct size=4 alignment=4 stride=4 num_extra_inhabitants=0
// CHECK-64-NEXT: (field name=_value offset=0
// CHECK-64-NEXT: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=0))))
// CHECK-64-NEXT: (field name=t09 offset=80
// CHECK-64-NEXT: (struct size=8 alignment=8 stride=8 num_extra_inhabitants=0
// CHECK-64-NEXT: (field name=_value offset=0
// CHECK-64-NEXT: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=0))))
// CHECK-64-NEXT: (field name=t10 offset=88
// CHECK-64-NEXT: (struct size=1 alignment=1 stride=1 num_extra_inhabitants=0
// CHECK-64-NEXT: (field name=_value offset=0
// CHECK-64-NEXT: (builtin size=1 alignment=1 stride=1 num_extra_inhabitants=0))))
// CHECK-64-NEXT: (field name=t11 offset=96
// CHECK-64-NEXT: (reference kind=strong refcounting=unknown))
// CHECK-64-NEXT: (field name=t12 offset=104
// CHECK-64-NEXT: (reference kind=strong refcounting=unknown))
// CHECK-64-NEXT: (field name=t13 offset=112
// CHECK-64-NEXT: (reference kind=strong refcounting=unknown))
// CHECK-64-NEXT: (field name=t14 offset=120
// CHECK-64-NEXT: (reference kind=strong refcounting=unknown))
// CHECK-64-NEXT: (field name=t15 offset=128
// CHECK-64-NEXT: (struct size=8 alignment=8 stride=8 num_extra_inhabitants=0
// (unstable implementation details omitted)
// CHECK-64: (field name=t16 offset=136
// CHECK-64-NEXT: (struct size=16 alignment=8 stride=16 num_extra_inhabitants=1
// (unstable implementation details omitted)
// CHECK-64: (field name=t17 offset=152
// CHECK-64-NEXT: (struct size=8 alignment=8 stride=8 num_extra_inhabitants=0
// CHECK-64-NEXT: (field name=_value offset=0
// CHECK-64-NEXT: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=0))))
// CHECK-64-NEXT: (field name=t18 offset=160
// CHECK-64-NEXT: (struct size=2 alignment=2 stride=2 num_extra_inhabitants=0
// CHECK-64-NEXT: (field name=_value offset=0
// CHECK-64-NEXT: (builtin size=2 alignment=2 stride=2 num_extra_inhabitants=0))))
// CHECK-64-NEXT: (field name=t19 offset=164
// CHECK-64-NEXT: (struct size=4 alignment=4 stride=4 num_extra_inhabitants=0
// CHECK-64-NEXT: (field name=_value offset=0
// CHECK-64-NEXT: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=0))))
// CHECK-64-NEXT: (field name=t20 offset=168
// CHECK-64-NEXT: (struct size=8 alignment=8 stride=8 num_extra_inhabitants=0
// CHECK-64-NEXT: (field name=_value offset=0
// CHECK-64-NEXT: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=0))))
// CHECK-64-NEXT: (field name=t21 offset=176
// CHECK-64-NEXT: (struct size=1 alignment=1 stride=1 num_extra_inhabitants=0
// CHECK-64-NEXT: (field name=_value offset=0
// CHECK-64-NEXT: (builtin size=1 alignment=1 stride=1 num_extra_inhabitants=0)))))
// CHECK-32: Reflecting an object.
// CHECK-32: Instance pointer in child address space: 0x{{[0-9a-fA-F]+}}
// CHECK-32: Type reference:
// CHECK-32: (class reflect_multiple_types.TestClass)
// CHECK-32: Type info:
// CHECK-32-NEXT: (class_instance size=121 alignment=8 stride=128 num_extra_inhabitants=0
// CHECK-32-NEXT: (field name=t00 offset=8
// CHECK-32-NEXT: (struct size=4 alignment=4 stride=4 num_extra_inhabitants=1
// (unstable implementation details omitted)
// CHECK-32: (field name=t01 offset=12
// CHECK-32-NEXT: (struct size=1 alignment=1 stride=1 num_extra_inhabitants=254
// CHECK-32-NEXT: (field name=_value offset=0
// CHECK-32-NEXT: (builtin size=1 alignment=1 stride=1 num_extra_inhabitants=254))))
// CHECK-32-NEXT: (field name=t02 offset=16
// CHECK-32-NEXT: (struct size=8 alignment=8 stride=8 num_extra_inhabitants=0
// CHECK-32-NEXT: (field name=_representation offset=0
// CHECK-32-NEXT: (multi_payload_enum size=8 alignment=8 stride=8 num_extra_inhabitants=0
// CHECK-32-NEXT: (field name=smallUTF16 offset=0
// CHECK-32-NEXT: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=2147483647))
// CHECK-32-NEXT: (field name=large offset=0
// CHECK-32-NEXT: (reference kind=strong refcounting=native))))))
// CHECK-32-NEXT: (field name=t03 offset=24
// CHECK-32-NEXT: (struct size=4 alignment=4 stride=4 num_extra_inhabitants=0
// (unstable implementation details omitted)
// CHECK-32: (field name=t04 offset=32
// CHECK-32-NEXT: (struct size=8 alignment=8 stride=8 num_extra_inhabitants=0
// CHECK-32-NEXT: (field name=_value offset=0
// CHECK-32-NEXT: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=0))))
// CHECK-32-NEXT: (field name=t05 offset=40
// CHECK-32-NEXT: (struct size=4 alignment=4 stride=4 num_extra_inhabitants=0
// CHECK-32-NEXT: (field name=_value offset=0
// CHECK-32-NEXT: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=0))))
// CHECK-32-NEXT: (field name=t06 offset=44
// CHECK-32-NEXT: (struct size=4 alignment=4 stride=4 num_extra_inhabitants=0
// CHECK-32-NEXT: (field name=_value offset=0
// CHECK-32-NEXT: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=0))))
// CHECK-32-NEXT: (field name=t07 offset=48
// CHECK-32-NEXT: (struct size=2 alignment=2 stride=2 num_extra_inhabitants=0
// CHECK-32-NEXT: (field name=_value offset=0
// CHECK-32-NEXT: (builtin size=2 alignment=2 stride=2 num_extra_inhabitants=0))))
// CHECK-32-NEXT: (field name=t08 offset=52
// CHECK-32-NEXT: (struct size=4 alignment=4 stride=4 num_extra_inhabitants=0
// CHECK-32-NEXT: (field name=_value offset=0
// CHECK-32-NEXT: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=0))))
// CHECK-32-NEXT: (field name=t09 offset=56
// CHECK-32-NEXT: (struct size=8 alignment=8 stride=8 num_extra_inhabitants=0
// CHECK-32-NEXT: (field name=_value offset=0
// CHECK-32-NEXT: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=0))))
// CHECK-32-NEXT: (field name=t10 offset=64
// CHECK-32-NEXT: (struct size=1 alignment=1 stride=1 num_extra_inhabitants=0
// CHECK-32-NEXT: (field name=_value offset=0
// CHECK-32-NEXT: (builtin size=1 alignment=1 stride=1 num_extra_inhabitants=0))))
// CHECK-32-NEXT: (field name=t11 offset=68
// CHECK-32-NEXT: (reference kind=strong refcounting=unknown))
// CHECK-32-NEXT: (field name=t12 offset=72
// CHECK-32-NEXT: (reference kind=strong refcounting=unknown))
// CHECK-32-NEXT: (field name=t13 offset=76
// CHECK-32-NEXT: (reference kind=strong refcounting=unknown))
// CHECK-32-NEXT: (field name=t14 offset=80
// CHECK-32-NEXT: (reference kind=strong refcounting=unknown))
// CHECK-32-NEXT: (field name=t15 offset=84
// CHECK-32-NEXT: (struct size=4 alignment=4 stride=4 num_extra_inhabitants=0
// (unstable implementation details omitted)
// CHECK-32: (field name=t16 offset=88
// CHECK-32-NEXT: (struct size=12 alignment=4 stride=12 num_extra_inhabitants=4092
// (unstable implementation details omitted)
// CHECK-32: (field name=t17 offset=100
// CHECK-32-NEXT: (struct size=4 alignment=4 stride=4 num_extra_inhabitants=0
// CHECK-32-NEXT: (field name=_value offset=0
// CHECK-32-NEXT: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=0))))
// CHECK-32-NEXT: (field name=t18 offset=104
// CHECK-32-NEXT: (struct size=2 alignment=2 stride=2 num_extra_inhabitants=0
// CHECK-32-NEXT: (field name=_value offset=0
// CHECK-32-NEXT: (builtin size=2 alignment=2 stride=2 num_extra_inhabitants=0))))
// CHECK-32-NEXT: (field name=t19 offset=108
// CHECK-32-NEXT: (struct size=4 alignment=4 stride=4 num_extra_inhabitants=0
// CHECK-32-NEXT: (field name=_value offset=0
// CHECK-32-NEXT: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=0))))
// CHECK-32-NEXT: (field name=t20 offset=112
// CHECK-32-NEXT: (struct size=8 alignment=8 stride=8 num_extra_inhabitants=0
// CHECK-32-NEXT: (field name=_value offset=0
// CHECK-32-NEXT: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=0))))
// CHECK-32-NEXT: (field name=t21 offset=120
// CHECK-32-NEXT: (struct size=1 alignment=1 stride=1 num_extra_inhabitants=0
// CHECK-32-NEXT: (field name=_value offset=0
// CHECK-32-NEXT: (builtin size=1 alignment=1 stride=1 num_extra_inhabitants=0)))))
doneReflecting()
// CHECK-64: Done.
// CHECK-32: Done.
| apache-2.0 | 6e966dc9e4325182c93815f08923d171 | 45.04698 | 123 | 0.655517 | 3.060214 | false | false | false | false |
richardpiazza/SOSwift | Sources/SOSwift/QualitativeValue.swift | 1 | 4160 | import Foundation
/// A predefined value for a product characteristic, e.g. the power cord plug type
/// 'US' or the garment sizes 'S', 'M', 'L', and 'XL'.
public class QualitativeValue: Enumeration {
/// A property-value pair representing an additional characteristics of the entitity,
/// e.g. a product feature or another characteristic for which there is no
/// matching property in schema.org.
/// - note: Publishers should be aware that applications designed to use
/// specific schema.org properties (e.g. http://schema.org/width,
/// http://schema.org/color, http://schema.org/gtin13, ...)
/// will typically expect such data to be provided using those properties,
/// rather than using the generic property/value mechanism.
public var additionalProperty: PropertyValue?
/// This ordering relation for qualitative values indicates that the subject
/// is equal to the object.
public var equal: QualitativeValue?
/// This ordering relation for qualitative values indicates that the subject is
/// greater than the object.
public var greater: QualitativeValue?
/// This ordering relation for qualitative values indicates that the subject is
/// greater than or equal to the object.
public var greaterOrEqual: QualitativeValue?
/// This ordering relation for qualitative values indicates that the subject is
/// lesser than the object.
public var lesser: QualitativeValue?
/// This ordering relation for qualitative values indicates that the subject is
/// lesser than or equal to the object.
public var lesserOrEqual: QualitativeValue?
/// This ordering relation for qualitative values indicates that the subject is
/// not equal to the object.
public var nonEqual: QualitativeValue?
/// A pointer to a secondary value that provides additional information on the
/// original value, e.g. a reference temperature.
public var valueReference: ValueReference?
internal enum QualitativeValueCodingKeys: String, CodingKey {
case additionalProperty
case equal
case greater
case greaterOrEqual
case lesser
case lesserOrEqual
case nonEqual
case valueReference
}
public override init() {
super.init()
}
public required init(from decoder: Decoder) throws {
try super.init(from: decoder)
let container = try decoder.container(keyedBy: QualitativeValueCodingKeys.self)
additionalProperty = try container.decodeIfPresent(PropertyValue.self, forKey: .additionalProperty)
equal = try container.decodeIfPresent(QualitativeValue.self, forKey: .equal)
greater = try container.decodeIfPresent(QualitativeValue.self, forKey: .greater)
greaterOrEqual = try container.decodeIfPresent(QualitativeValue.self, forKey: .greaterOrEqual)
lesser = try container.decodeIfPresent(QualitativeValue.self, forKey: .lesser)
lesserOrEqual = try container.decodeIfPresent(QualitativeValue.self, forKey: .lesserOrEqual)
nonEqual = try container.decodeIfPresent(QualitativeValue.self, forKey: .nonEqual)
valueReference = try container.decodeIfPresent(ValueReference.self, forKey: .valueReference)
}
public override func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: QualitativeValueCodingKeys.self)
try container.encodeIfPresent(additionalProperty, forKey: .additionalProperty)
try container.encodeIfPresent(equal, forKey: .equal)
try container.encodeIfPresent(greater, forKey: .greater)
try container.encodeIfPresent(greaterOrEqual, forKey: .greaterOrEqual)
try container.encodeIfPresent(lesser, forKey: .lesser)
try container.encodeIfPresent(lesserOrEqual, forKey: .lesserOrEqual)
try container.encodeIfPresent(nonEqual, forKey: .nonEqual)
try container.encodeIfPresent(valueReference, forKey: .valueReference)
try super.encode(to: encoder)
}
}
| mit | 5a1fb8b52958a2302d2acee192ff2b94 | 45.741573 | 107 | 0.704567 | 5.232704 | false | false | false | false |
dhf/SwiftForms | SwiftForms/cells/FormPickerCell.swift | 2 | 2916 | //
// FormPickerCell.swift
// SwiftForms
//
// Created by Miguel Angel Ortuno on 22/08/14.
// Copyright (c) 2014 Miguel Angel Ortuño. All rights reserved.
//
import UIKit
public class FormPickerCell: FormValueCell, UIPickerViewDelegate, UIPickerViewDataSource {
/// MARK: Properties
private let picker = UIPickerView()
private let hiddenTextField = UITextField(frame: CGRectZero)
public required init(style: UITableViewCellStyle, reuseIdentifier: String!) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
accessoryType = .None
picker.delegate = self
picker.dataSource = self
hiddenTextField.inputView = picker
contentView.addSubview(hiddenTextField)
}
public override func update() {
super.update()
titleLabel.text = rowDescriptor.title
if let value = rowDescriptor.value {
valueLabel.text = rowDescriptor.titleForOptionValue(value)
if let options = rowDescriptor.configuration.options,
let index = options.indexOf(value) {
picker.selectRow(index, inComponent: 0, animated: false)
}
}
}
public override class func formViewController(formViewController: FormViewController, didSelectRow selectedRow: FormBaseCell) {
if let row = selectedRow as? FormPickerCell {
if let optionValue = selectedRow.rowDescriptor.value {
row.valueLabel.text = selectedRow.rowDescriptor.titleForOptionValue(optionValue)
} else if let optionValue = selectedRow.rowDescriptor.configuration.options?.first {
selectedRow.rowDescriptor.value = optionValue
row.valueLabel.text = selectedRow.rowDescriptor.titleForOptionValue(optionValue)
}
row.hiddenTextField.becomeFirstResponder()
}
}
/// MARK: UIPickerViewDelegate
public func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return rowDescriptor.titleForOptionAtIndex(row)
}
public func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
if let optionValue = rowDescriptor.configuration.options?[row] {
rowDescriptor.value = optionValue
valueLabel.text = rowDescriptor.titleForOptionValue(optionValue)
}
}
/// MARK: UIPickerViewDataSource
public func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int {
return 1
}
public func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return rowDescriptor.configuration.options?.count ?? 0
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
}
| mit | 4b42aba03ed1a1a0df2b1819171726d7 | 34.120482 | 131 | 0.663122 | 5.76087 | false | false | false | false |
zvonler/PasswordElephant | external/github.com/apple/swift-protobuf/Sources/SwiftProtobuf/Google_Protobuf_Wrappers+Extensions.swift | 9 | 7976 | // Sources/SwiftProtobuf/Google_Protobuf_Wrappers+Extensions.swift - Well-known wrapper type extensions
//
// Copyright (c) 2014 - 2016 Apple Inc. and the project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See LICENSE.txt for license information:
// https://github.com/apple/swift-protobuf/blob/master/LICENSE.txt
//
// -----------------------------------------------------------------------------
///
/// Extensions to the well-known types in wrapper.proto that customize the JSON
/// format of those messages and provide convenience initializers from literals.
///
// -----------------------------------------------------------------------------
import Foundation
/// Internal protocol that minimizes the code duplication across the multiple
/// wrapper types extended below.
protocol ProtobufWrapper {
/// The wrapped protobuf type (for example, `ProtobufDouble`).
associatedtype WrappedType: FieldType
/// Exposes the generated property to the extensions here.
var value: WrappedType.BaseType { get set }
/// Exposes the parameterless initializer to the extensions here.
init()
/// Creates a new instance of the wrapper with the given value.
init(_ value: WrappedType.BaseType)
}
extension Google_Protobuf_DoubleValue:
ProtobufWrapper, ExpressibleByFloatLiteral, _CustomJSONCodable {
public typealias WrappedType = ProtobufDouble
public typealias FloatLiteralType = WrappedType.BaseType
public init(_ value: WrappedType.BaseType) {
self.init()
self.value = value
}
public init(floatLiteral: FloatLiteralType) {
self.init(floatLiteral)
}
func encodedJSONString() throws -> String {
var encoder = JSONEncoder()
encoder.putDoubleValue(value: value)
return encoder.stringResult
}
mutating func decodeJSON(from decoder: inout JSONDecoder) throws {
var v: WrappedType.BaseType?
try WrappedType.decodeSingular(value: &v, from: &decoder)
value = v ?? WrappedType.proto3DefaultValue
}
}
extension Google_Protobuf_FloatValue:
ProtobufWrapper, ExpressibleByFloatLiteral, _CustomJSONCodable {
public typealias WrappedType = ProtobufFloat
public typealias FloatLiteralType = Float
public init(_ value: WrappedType.BaseType) {
self.init()
self.value = value
}
public init(floatLiteral: FloatLiteralType) {
self.init(floatLiteral)
}
func encodedJSONString() throws -> String {
var encoder = JSONEncoder()
encoder.putFloatValue(value: value)
return encoder.stringResult
}
mutating func decodeJSON(from decoder: inout JSONDecoder) throws {
var v: WrappedType.BaseType?
try WrappedType.decodeSingular(value: &v, from: &decoder)
value = v ?? WrappedType.proto3DefaultValue
}
}
extension Google_Protobuf_Int64Value:
ProtobufWrapper, ExpressibleByIntegerLiteral, _CustomJSONCodable {
public typealias WrappedType = ProtobufInt64
public typealias IntegerLiteralType = WrappedType.BaseType
public init(_ value: WrappedType.BaseType) {
self.init()
self.value = value
}
public init(integerLiteral: IntegerLiteralType) {
self.init(integerLiteral)
}
func encodedJSONString() throws -> String {
var encoder = JSONEncoder()
encoder.putInt64(value: value)
return encoder.stringResult
}
mutating func decodeJSON(from decoder: inout JSONDecoder) throws {
var v: WrappedType.BaseType?
try WrappedType.decodeSingular(value: &v, from: &decoder)
value = v ?? WrappedType.proto3DefaultValue
}
}
extension Google_Protobuf_UInt64Value:
ProtobufWrapper, ExpressibleByIntegerLiteral, _CustomJSONCodable {
public typealias WrappedType = ProtobufUInt64
public typealias IntegerLiteralType = WrappedType.BaseType
public init(_ value: WrappedType.BaseType) {
self.init()
self.value = value
}
public init(integerLiteral: IntegerLiteralType) {
self.init(integerLiteral)
}
func encodedJSONString() throws -> String {
var encoder = JSONEncoder()
encoder.putUInt64(value: value)
return encoder.stringResult
}
mutating func decodeJSON(from decoder: inout JSONDecoder) throws {
var v: WrappedType.BaseType?
try WrappedType.decodeSingular(value: &v, from: &decoder)
value = v ?? WrappedType.proto3DefaultValue
}
}
extension Google_Protobuf_Int32Value:
ProtobufWrapper, ExpressibleByIntegerLiteral, _CustomJSONCodable {
public typealias WrappedType = ProtobufInt32
public typealias IntegerLiteralType = WrappedType.BaseType
public init(_ value: WrappedType.BaseType) {
self.init()
self.value = value
}
public init(integerLiteral: IntegerLiteralType) {
self.init(integerLiteral)
}
func encodedJSONString() throws -> String {
return String(value)
}
mutating func decodeJSON(from decoder: inout JSONDecoder) throws {
var v: WrappedType.BaseType?
try WrappedType.decodeSingular(value: &v, from: &decoder)
value = v ?? WrappedType.proto3DefaultValue
}
}
extension Google_Protobuf_UInt32Value:
ProtobufWrapper, ExpressibleByIntegerLiteral, _CustomJSONCodable {
public typealias WrappedType = ProtobufUInt32
public typealias IntegerLiteralType = WrappedType.BaseType
public init(_ value: WrappedType.BaseType) {
self.init()
self.value = value
}
public init(integerLiteral: IntegerLiteralType) {
self.init(integerLiteral)
}
func encodedJSONString() throws -> String {
return String(value)
}
mutating func decodeJSON(from decoder: inout JSONDecoder) throws {
var v: WrappedType.BaseType?
try WrappedType.decodeSingular(value: &v, from: &decoder)
value = v ?? WrappedType.proto3DefaultValue
}
}
extension Google_Protobuf_BoolValue:
ProtobufWrapper, ExpressibleByBooleanLiteral, _CustomJSONCodable {
public typealias WrappedType = ProtobufBool
public typealias BooleanLiteralType = Bool
public init(_ value: WrappedType.BaseType) {
self.init()
self.value = value
}
public init(booleanLiteral: Bool) {
self.init(booleanLiteral)
}
func encodedJSONString() throws -> String {
return value ? "true" : "false"
}
mutating func decodeJSON(from decoder: inout JSONDecoder) throws {
var v: WrappedType.BaseType?
try WrappedType.decodeSingular(value: &v, from: &decoder)
value = v ?? WrappedType.proto3DefaultValue
}
}
extension Google_Protobuf_StringValue:
ProtobufWrapper, ExpressibleByStringLiteral, _CustomJSONCodable {
public typealias WrappedType = ProtobufString
public typealias StringLiteralType = String
public typealias ExtendedGraphemeClusterLiteralType = String
public typealias UnicodeScalarLiteralType = String
public init(_ value: WrappedType.BaseType) {
self.init()
self.value = value
}
public init(stringLiteral: String) {
self.init(stringLiteral)
}
public init(extendedGraphemeClusterLiteral: String) {
self.init(extendedGraphemeClusterLiteral)
}
public init(unicodeScalarLiteral: String) {
self.init(unicodeScalarLiteral)
}
func encodedJSONString() throws -> String {
var encoder = JSONEncoder()
encoder.putStringValue(value: value)
return encoder.stringResult
}
mutating func decodeJSON(from decoder: inout JSONDecoder) throws {
var v: WrappedType.BaseType?
try WrappedType.decodeSingular(value: &v, from: &decoder)
value = v ?? WrappedType.proto3DefaultValue
}
}
extension Google_Protobuf_BytesValue: ProtobufWrapper, _CustomJSONCodable {
public typealias WrappedType = ProtobufBytes
public init(_ value: WrappedType.BaseType) {
self.init()
self.value = value
}
func encodedJSONString() throws -> String {
var encoder = JSONEncoder()
encoder.putBytesValue(value: value)
return encoder.stringResult
}
mutating func decodeJSON(from decoder: inout JSONDecoder) throws {
var v: WrappedType.BaseType?
try WrappedType.decodeSingular(value: &v, from: &decoder)
value = v ?? WrappedType.proto3DefaultValue
}
}
| gpl-3.0 | 86ffbed103cd694043eadb566d41ebe4 | 27.183746 | 103 | 0.726179 | 4.926498 | false | false | false | false |
hyp/NUIGExam | NUIGExam/LoginViewController.swift | 1 | 2078 | import UIKit
import Foundation
// Controls the login and timetable fetching process.
class LoginViewController: UIViewController {
@IBOutlet weak var studentNumber: UITextField!
@IBOutlet weak var password: UITextField!
var dataProvider: NUIGWebsiteExamDataProvider? = nil
func error(msg: String) {
let alertView = UIAlertView()
alertView.title = "Sign in Failed!"
alertView.message = msg
alertView.delegate = self
alertView.addButtonWithTitle("OK")
alertView.show()
}
@IBAction func onSignIn() {
if studentNumber.text.isEmpty || password.text.isEmpty {
self.error("Please enter Username and Password")
return
}
UIApplication.sharedApplication().networkActivityIndicatorVisible = true
dataProvider = NUIGWebsiteExamDataProvider()
dataProvider!.onIncorrectPassword = {
self.error("Incorrect Password")
}
dataProvider!.onIncorrectUsername = {
self.error("Invalid Student ID")
}
dataProvider!.onConnectionError = { (error: NSError) in
self.error(error.localizedDescription)
}
dataProvider!.onParseError = {
self.error("NUIG exam timetable isn't accessible.\nTry using the NUIG website.")
}
let studentID = studentNumber.text
let pwd = password.text
dataProvider!.fetchTimetable(studentID, password: pwd) { (examSession: String) in
// Save login details and preferences
let prefs = NSUserDefaults.standardUserDefaults()
prefs.setBool(true, forKey: "isLoggedIn")
prefs.setObject(examSession, forKey: "examSession")
prefs.synchronize()
KeychainService.save("studentID", studentID)
KeychainService.save("password", pwd)
UIApplication.sharedApplication().networkActivityIndicatorVisible = false
self.dismissViewControllerAnimated(true, completion: nil)
}
}
} | mit | 2ed1728534de37c8faa8a02ce4098fde | 35.473684 | 92 | 0.637632 | 5.48285 | false | false | false | false |
willpowell8/UIDesignKit_iOS | UIDesignKit/Classes/Extensions/UIButton+UIDesign.swift | 1 | 2195 | //
// UIButton+UIDesign.swift
// Pods
//
// Created by Will Powell on 26/11/2016.
//
//
import Foundation
import SDWebImage
extension UIButton{
override open func updateDesign(type:String, data:[AnyHashable: Any]) {
super.updateDesign(type:type, data: data);
self.applyData(data: data, property: "tintColor", targetType: .color, apply: { (value) in
if let v = value as? UIColor {
self.tintColor = v
}
})
self.applyData(data: data, property: "textColorNormal", targetType: .color, apply: { (value) in
if let v = value as? UIColor {
self.setTitleColor(v, for: .normal)
}
})
self.applyData(data: data, property: "font", targetType: .font) { (value) in
if let v = value as? UIFont {
self.titleLabel?.font = v
}
}
}
override open func getDesignProperties(data:[String:Any]) -> [String:Any]{
var dataReturn = super.getDesignProperties(data: data);
if #available(iOS 13.0, *) {
let lightColor = colorForTrait(color: self.tintColor, trait: .light)
let darkColor = colorForTrait(color: self.tintColor, trait: .dark)
dataReturn["tintColor"] = ["type":"COLOR", "value":lightColor?.toHexString()]
dataReturn["tintColor-dark"] = ["type":"COLOR", "value":darkColor?.toHexString()]
}else{
dataReturn["tintColor"] = ["type":"COLOR", "value":self.tintColor.toHexString()]
}
self.titleColor(for: .normal)
if let textNormalColor = self.titleColor(for: .normal) {
dataReturn["textColorNormal"] = ["type":"COLOR", "value":textNormalColor.toHexString()];
}else{
dataReturn["textColorNormal"] = ["type":"COLOR"]
}
if let fontString = titleLabel?.font.toDesignString() {
dataReturn["font"] = ["type":"FONT", "value":fontString];
}else{
dataReturn["font"] = ["type":"FONT"]
}
return dataReturn;
}
override public func getDesignType() -> String{
return "BUTTON";
}
}
| mit | f3eb683b34558fee833087c5cb4a551b | 34.403226 | 103 | 0.564009 | 4.295499 | false | false | false | false |
yangxiaodongcn/iOSAppBase | iOSAppBase/Carthage/Checkouts/ObjectMapper/Tests/DataTransformTests.swift | 17 | 2027 | //
// NSDataTransformTests.swift
// ObjectMapper
//
// Created by Yagrushkin, Evgeny on 8/30/16.
//
// The MIT License (MIT)
//
// Copyright (c) 2014-2016 Hearst
//
// 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 ObjectMapper
class DataTransformTests: XCTestCase {
let mapper = Mapper<DataType>()
func testDataTransform() {
let dataLength = 20
let bytes = malloc(dataLength)
let data = Data(bytes: bytes!, count: dataLength)
let dataString = data.base64EncodedString()
let JSONString = "{\"data\" : \"\(dataString)\"}"
let mappedObject = mapper.map(JSONString: JSONString)
XCTAssertNotNil(mappedObject)
XCTAssertEqual(mappedObject?.stringData, dataString)
XCTAssertEqual(mappedObject?.data, data)
}
}
class DataType: Mappable {
var data: Data?
var stringData: String?
init(){
}
required init?(map: Map){
}
func mapping(map: Map) {
stringData <- map["data"]
data <- (map["data"], DataTransform())
}
}
| mit | 20916b84ea892ff87de84516c0e62876 | 27.549296 | 81 | 0.721263 | 4.021825 | false | true | false | false |
aronse/Hero | Examples/Resources/UIKit+HeroExamples.swift | 2 | 2530 | // The MIT License (MIT)
//
// Copyright (c) 2016 Luke Zhao <[email protected]>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import UIKit
public extension UIView {
@IBInspectable public var cornerRadius: CGFloat {
get {
return layer.cornerRadius
}
set {
layer.cornerRadius = newValue
}
}
@IBInspectable public var shadowRadius: CGFloat {
get {
return layer.shadowRadius
}
set {
layer.shadowRadius = newValue
}
}
@IBInspectable public var shadowOpacity: Float {
get {
return layer.shadowOpacity
}
set {
layer.shadowOpacity = newValue
}
}
@IBInspectable public var shadowColor: UIColor? {
get {
return layer.shadowColor != nil ? UIColor(cgColor: layer.shadowColor!) : nil
}
set {
layer.shadowColor = newValue?.cgColor
}
}
@IBInspectable public var shadowOffset: CGSize {
get {
return layer.shadowOffset
}
set {
layer.shadowOffset = newValue
}
}
@IBInspectable public var zPosition: CGFloat {
get {
return layer.zPosition
}
set {
layer.zPosition = newValue
}
}
}
func viewController(forStoryboardName: String) -> UIViewController {
return UIStoryboard(name: forStoryboardName, bundle: nil).instantiateInitialViewController()!
}
class TemplateImageView: UIImageView {
@IBInspectable var templateImage: UIImage? {
didSet {
image = templateImage?.withRenderingMode(.alwaysTemplate)
}
}
}
| mit | 7afc2968adf4174494d97ca5bec1dfa4 | 26.5 | 95 | 0.699209 | 4.685185 | false | false | false | false |
BlenderSleuth/Circles | Circles/SKTUtils/CGVector+Extensions.swift | 1 | 5381 | /*
* Copyright (c) 2013-2014 Razeware LLC
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
import CoreGraphics
import SpriteKit
public extension CGVector {
/**
* Creates a new CGVector given a CGPoint.
*/
public init(point: CGPoint) {
self.init(dx: point.x, dy: point.y)
}
/**
* Given an angle in radians, creates a vector of length 1.0 and returns the
* result as a new CGVector. An angle of 0 is assumed to point to the right.
*/
public init(angle: CGFloat) {
self.init(dx: cos(angle), dy: sin(angle))
}
/**
* Adds (dx, dy) to the vector.
*/
public mutating func offset(_ dx: CGFloat, dy: CGFloat) -> CGVector {
self.dx += dx
self.dy += dy
return self
}
/**
* Returns the length (magnitude) of the vector described by the CGVector.
*/
public func length() -> CGFloat {
return sqrt(dx*dx + dy*dy)
}
/**
* Returns the squared length of the vector described by the CGVector.
*/
public func lengthSquared() -> CGFloat {
return dx*dx + dy*dy
}
/**
* Normalizes the vector described by the CGVector to length 1.0 and returns
* the result as a new CGVector.
public */
func normalized() -> CGVector {
let len = length()
return len>0 ? self / len : CGVector.zero
}
/**
* Normalizes the vector described by the CGVector to length 1.0.
*/
public mutating func normalize() -> CGVector {
self = normalized()
return self
}
/**
* Calculates the distance between two CGVectors. Pythagoras!
*/
public func distanceTo(_ vector: CGVector) -> CGFloat {
return (self - vector).length()
}
/**
* Returns the angle in radians of the vector described by the CGVector.
* The range of the angle is -π to π; an angle of 0 points to the right.
*/
public var angle: CGFloat {
return atan2(dy, dx)
}
}
/**
* Adds two CGVector values and returns the result as a new CGVector.
*/
public func + (left: CGVector, right: CGVector) -> CGVector {
return CGVector(dx: left.dx + right.dx, dy: left.dy + right.dy)
}
/**
* Increments a CGVector with the value of another.
*/
public func += (left: inout CGVector, right: CGVector) {
left = left + right
}
/**
* Subtracts two CGVector values and returns the result as a new CGVector.
*/
public func - (left: CGVector, right: CGVector) -> CGVector {
return CGVector(dx: left.dx - right.dx, dy: left.dy - right.dy)
}
/**
* Decrements a CGVector with the value of another.
*/
public func -= (left: inout CGVector, right: CGVector) {
left = left - right
}
/**
* Multiplies two CGVector values and returns the result as a new CGVector.
*/
public func * (left: CGVector, right: CGVector) -> CGVector {
return CGVector(dx: left.dx * right.dx, dy: left.dy * right.dy)
}
/**
* Multiplies a CGVector with another.
*/
public func *= (left: inout CGVector, right: CGVector) {
left = left * right
}
/**
* Multiplies the x and y fields of a CGVector with the same scalar value and
* returns the result as a new CGVector.
*/
public func * (vector: CGVector, scalar: CGFloat) -> CGVector {
return CGVector(dx: vector.dx * scalar, dy: vector.dy * scalar)
}
/**
* Multiplies the x and y fields of a CGVector with the same scalar value.
*/
public func *= (vector: inout CGVector, scalar: CGFloat) {
vector = vector * scalar
}
/**
* Divides two CGVector values and returns the result as a new CGVector.
*/
public func / (left: CGVector, right: CGVector) -> CGVector {
return CGVector(dx: left.dx / right.dx, dy: left.dy / right.dy)
}
/**
* Divides a CGVector by another.
*/
public func /= (left: inout CGVector, right: CGVector) {
left = left / right
}
/**
* Divides the dx and dy fields of a CGVector by the same scalar value and
* returns the result as a new CGVector.
*/
public func / (vector: CGVector, scalar: CGFloat) -> CGVector {
return CGVector(dx: vector.dx / scalar, dy: vector.dy / scalar)
}
/**
* Divides the dx and dy fields of a CGVector by the same scalar value.
*/
public func /= (vector: inout CGVector, scalar: CGFloat) {
vector = vector / scalar
}
/**
* Performs a linear interpolation between two CGVector values.
*/
public func lerp(_ start: CGVector, end: CGVector, t: CGFloat) -> CGVector {
return CGVector(dx: start.dx + (end.dx - start.dx)*t, dy: start.dy + (end.dy - start.dy)*t)
}
| gpl-3.0 | ce48639f7a93b35b38848c9a90a4912c | 27.460317 | 93 | 0.677635 | 3.831197 | false | false | false | false |
malaonline/iOS | mala-ios/View/Base/Help/MAHelpViewCell.swift | 1 | 2824 | //
// MAHelpViewCell.swift
// mala-ios
//
// Created by 王新宇 on 2017/5/22.
// Copyright © 2017年 Mala Online. All rights reserved.
//
import UIKit
class MAHelpViewCell: UITableViewCell {
var model: IntroductionModel? {
didSet {
guard let model = model else { return }
iconView.image = UIImage(asset: model.image ?? .none)
titleLabel.text = model.title
descLabel.text = model.subTitle
descLabel.textAlignment = ((model.subTitle?.characters.count ?? 0) > 15 ? .justified : .center)
}
}
// MARK: - Components
private lazy var iconView: UIImageView = {
let imageView = UIImageView()
return imageView
}()
private lazy var titleLabel: UILabel = {
let label = UILabel(text: "1.课前",
font: FontFamily.PingFangSC.Regular.font(20),
textColor: UIColor(named: .labelBlack),
textAlignment: .center)
return label
}()
private lazy var descLabel: UILabel = {
let label = UILabel(text: "学生通过pad答题,点击提交.同步App可以根据登录手机号匹配传送给错题本,实时查看.",
font: FontFamily.PingFangSC.Regular.font(14),
textColor: UIColor(named: .protocolGary),
textAlignment: .justified)
label.numberOfLines = 0
return label
}()
// MARK: - Instance Method
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
setup()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func setup() {
contentView.addSubview(iconView)
contentView.addSubview(titleLabel)
contentView.addSubview(descLabel)
iconView.snp.makeConstraints { (maker) in
maker.top.equalTo(contentView).offset(10)
maker.centerX.equalTo(contentView)
maker.height.equalTo(90)
}
titleLabel.snp.makeConstraints { (maker) in
maker.top.equalTo(iconView.snp.bottom).offset(5)
maker.centerX.equalTo(contentView)
maker.left.equalTo(contentView).offset(37)
maker.right.equalTo(contentView).offset(-37)
}
descLabel.snp.makeConstraints { (maker) in
maker.top.equalTo(titleLabel.snp.bottom).offset(5)
maker.centerX.equalTo(contentView)
maker.left.equalTo(contentView).offset(37)
maker.right.equalTo(contentView).offset(-37)
maker.bottom.equalTo(contentView)
}
}
}
| mit | 442fb6cb3c65b6da921e1f34d362fba9 | 32.839506 | 107 | 0.583729 | 4.645763 | false | false | false | false |
malaonline/iOS | mala-ios/View/OrderForm/OrderFormStatusCell.swift | 1 | 13405 | //
// OrderFormStatusCell.swift
// mala-ios
//
// Created by 王新宇 on 16/5/13.
// Copyright © 2016年 Mala Online. All rights reserved.
//
import UIKit
class OrderFormStatusCell: UITableViewCell {
// MARK: - Property
/// 订单详情模型
var model: OrderForm? {
didSet {
guard let model = model else { return }
// 订单状态
changeDisplayMode()
// 课程类型
if let isLive = model.isLiveCourse, isLive == true {
setupLiveCourseOrderInfo()
}else {
setupPrivateTuitionOrderInfo()
}
}
}
// MARK: - Components
/// 布局容器
private lazy var content: UIView = {
let view = UIView(UIColor.white)
return view
}()
/// 标题
private lazy var titleLabel: UILabel = {
let label = UILabel(
text: "订单状态",
fontSize: 15,
textColor: UIColor(named: .ThemeTextBlue)
)
return label
}()
/// 订单状态
private lazy var statusLabel: UILabel = {
let label = UILabel(
text: "状态",
fontSize: 13,
textColor: UIColor(named: .OrderStatusRed)
)
return label
}()
/// 分割线
private lazy var separatorLine: UIView = {
let view = UIView(UIColor(named: .CardBackground))
return view
}()
// MARK: Components for Private Tuition
/// 老师图标
private lazy var teacherIcon: UIImageView = {
let imageView = UIImageView(imageName: "live_teacher")
return imageView
}()
/// 老师标签
private lazy var teacherLabel: UILabel = {
let label = UILabel(
fontSize: 13,
textColor: UIColor(named: .ArticleSubTitle)
)
return label
}()
/// 学科信息图标
private lazy var subjectIcon: UIImageView = {
let imageView = UIImageView(imageName: "live_class")
return imageView
}()
/// 学科信息
private lazy var subjectLabel: UILabel = {
let label = UILabel(
text: "年级-学科",
fontSize: 13,
textColor: UIColor(named: .ArticleSubTitle)
)
return label
}()
/// 上课地点图标
private lazy var schoolIcon: UIImageView = {
let imageView = UIImageView(imageName: "live_location")
return imageView
}()
/// 上课地点
private lazy var schoolLabel: UILabel = {
let label = UILabel(
text: "上课地点",
fontSize: 13,
textColor: UIColor(named: .ArticleSubTitle)
)
label.numberOfLines = 0
return label
}()
/// 老师头像
private lazy var avatarView: UIImageView = {
let imageView = UIImageView(cornerRadius: 55/2, image: "avatar_placeholder")
return imageView
}()
// MARK: Components for LiveCourse
/// 课程图标
private lazy var classIcon: UIImageView = {
let imageView = UIImageView(imageName: "live_class")
return imageView
}()
/// 课程标签
private lazy var classLabel: UILabel = {
let label = UILabel(
fontSize: 13,
textColor: UIColor(named: .ArticleSubTitle)
)
return label
}()
/// 班型
private lazy var roomCapacityIcon: UIImageView = {
let imageView = UIImageView(imageName: "live_students")
return imageView
}()
/// 班型标签
private lazy var roomCapacityLabel: UILabel = {
let label = UILabel(
fontSize: 13,
textColor: UIColor(named: .ArticleText)
)
return label
}()
/// 上课次数
private lazy var courseLessonsIcon: UIImageView = {
let imageView = UIImageView(imageName: "live_times")
return imageView
}()
/// 上课次数标签
private lazy var courseLessonsLabel: UILabel = {
let label = UILabel(
fontSize: 13,
textColor: UIColor(named: .ArticleText)
)
return label
}()
/// 双师直播课程头像
private lazy var liveCourseAvatarView: LiveCourseAvatarView = {
let view = LiveCourseAvatarView()
return view
}()
// MARK: - Instance Method
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
setupUserInterface()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - Private Method
private func setupUserInterface() {
// Style
contentView.backgroundColor = UIColor(named: .CardBackground)
// SubViews
contentView.addSubview(content)
content.addSubview(titleLabel)
content.addSubview(statusLabel)
content.addSubview(separatorLine)
// AutoLayout
content.snp.makeConstraints { (maker) in
maker.top.equalTo(contentView)
maker.left.equalTo(contentView).offset(12)
maker.right.equalTo(contentView).offset(-12)
maker.bottom.equalTo(contentView)
}
titleLabel.snp.updateConstraints { (maker) -> Void in
maker.top.equalTo(content).offset(9.5)
maker.left.equalTo(content).offset(12)
maker.height.equalTo(17)
}
statusLabel.snp.makeConstraints { (maker) in
maker.bottom.equalTo(titleLabel)
maker.right.equalTo(content).offset(-12)
maker.height.equalTo(14)
}
separatorLine.snp.makeConstraints { (maker) in
maker.top.equalTo(content).offset(36)
maker.left.equalTo(content).offset(7)
maker.right.equalTo(content).offset(-7)
maker.height.equalTo(MalaScreenOnePixel)
}
}
/// 加载一对一课程订单数据
private func setupPrivateTuitionOrderInfo() {
// SubViews
content.addSubview(teacherIcon)
content.addSubview(teacherLabel)
content.addSubview(subjectIcon)
content.addSubview(subjectLabel)
content.addSubview(schoolIcon)
content.addSubview(schoolLabel)
content.addSubview(avatarView)
// Autolayout
teacherIcon.snp.makeConstraints { (maker) in
maker.top.equalTo(separatorLine.snp.bottom).offset(10)
maker.left.equalTo(content).offset(12)
maker.height.equalTo(13)
maker.width.equalTo(13)
}
teacherLabel.snp.makeConstraints { (maker) in
maker.centerY.equalTo(teacherIcon)
maker.left.equalTo(teacherIcon.snp.right).offset(10)
maker.height.equalTo(13)
}
subjectIcon.snp.makeConstraints { (maker) in
maker.top.equalTo(teacherIcon.snp.bottom).offset(10)
maker.left.equalTo(content).offset(12)
maker.height.equalTo(13)
maker.width.equalTo(13)
}
subjectLabel.snp.makeConstraints { (maker) in
maker.centerY.equalTo(subjectIcon)
maker.left.equalTo(subjectIcon.snp.right).offset(10)
maker.height.equalTo(13)
}
schoolIcon.snp.makeConstraints { (maker) in
maker.top.equalTo(subjectIcon.snp.bottom).offset(10)
maker.left.equalTo(content).offset(12)
maker.height.equalTo(13)
maker.width.equalTo(13)
}
schoolLabel.snp.makeConstraints { (maker) in
maker.top.equalTo(schoolIcon)
maker.left.equalTo(teacherLabel)
maker.right.equalTo(content).offset(-12)
maker.bottom.equalTo(content).offset(-10)
}
avatarView.snp.makeConstraints { (maker) in
maker.centerY.equalTo(subjectIcon)
maker.centerX.equalTo(statusLabel)
maker.height.equalTo(55)
maker.width.equalTo(55)
}
/// 课程信息
avatarView.setImage(withURL: model?.avatarURL)
teacherLabel.text = model?.teacherName
subjectLabel.text = (model?.gradeName ?? "") + " " + (model?.subjectName ?? "")
schoolLabel.attributedText = model?.attrAddressString
}
/// 加载双师直播课程订单数据
private func setupLiveCourseOrderInfo() {
// SubViews
content.addSubview(teacherIcon)
content.addSubview(teacherLabel)
content.addSubview(classIcon)
content.addSubview(classLabel)
content.addSubview(roomCapacityIcon)
content.addSubview(roomCapacityLabel)
content.addSubview(courseLessonsIcon)
content.addSubview(courseLessonsLabel)
content.addSubview(schoolIcon)
content.addSubview(schoolLabel)
content.addSubview(liveCourseAvatarView)
// Autolayout
teacherIcon.snp.makeConstraints { (maker) in
maker.top.equalTo(separatorLine.snp.bottom).offset(10)
maker.left.equalTo(content).offset(12)
maker.height.equalTo(13)
maker.width.equalTo(13)
}
teacherLabel.snp.makeConstraints { (maker) in
maker.centerY.equalTo(teacherIcon)
maker.left.equalTo(teacherIcon.snp.right).offset(10)
maker.height.equalTo(13)
}
classIcon.snp.makeConstraints { (maker) in
maker.top.equalTo(teacherIcon.snp.bottom).offset(10)
maker.left.equalTo(content).offset(12)
maker.height.equalTo(13)
maker.width.equalTo(13)
}
classLabel.snp.makeConstraints { (maker) in
maker.centerY.equalTo(classIcon)
maker.left.equalTo(teacherLabel)
maker.height.equalTo(13)
}
roomCapacityIcon.snp.makeConstraints { (maker) in
maker.top.equalTo(classIcon.snp.bottom).offset(10)
maker.left.equalTo(content).offset(12)
maker.height.equalTo(13)
maker.width.equalTo(13)
}
roomCapacityLabel.snp.makeConstraints { (maker) in
maker.centerY.equalTo(roomCapacityIcon)
maker.left.equalTo(teacherLabel)
maker.height.equalTo(13)
}
courseLessonsIcon.snp.makeConstraints { (maker) in
maker.top.equalTo(roomCapacityIcon.snp.bottom).offset(10)
maker.left.equalTo(content).offset(12)
maker.height.equalTo(13)
maker.width.equalTo(13)
}
courseLessonsLabel.snp.makeConstraints { (maker) in
maker.centerY.equalTo(courseLessonsIcon)
maker.left.equalTo(teacherLabel)
maker.height.equalTo(13)
}
schoolIcon.snp.makeConstraints { (maker) in
maker.top.equalTo(courseLessonsIcon.snp.bottom).offset(10)
maker.left.equalTo(content).offset(12)
maker.height.equalTo(13)
maker.width.equalTo(13)
}
schoolLabel.snp.makeConstraints { (maker) in
maker.top.equalTo(schoolIcon)
maker.left.equalTo(teacherLabel)
maker.right.equalTo(content).offset(-12)
maker.bottom.equalTo(content).offset(-10)
}
liveCourseAvatarView.snp.makeConstraints { (maker) in
maker.right.equalTo(content).offset(-12)
maker.centerY.equalTo(roomCapacityLabel.snp.bottom)
maker.width.equalTo(72)
maker.height.equalTo(45)
}
/// 课程信息
liveCourseAvatarView.setAvatar(lecturer: model?.liveClass?.lecturerAvatar, assistant: model?.liveClass?.assistantAvatar)
teacherLabel.attributedText = model?.attrTeacherString
classLabel.text = model?.liveClass?.courseName
roomCapacityLabel.text = String(format: "%d人小班", model?.liveClass?.roomCapacity ?? 0)
courseLessonsLabel.text = String(format: "共 %d 次课", model?.liveClass?.courseLessons ?? 0)
schoolLabel.attributedText = model?.attrAddressString
}
/// 根据当前订单状态,渲染对应UI样式
private func changeDisplayMode() {
/// 订单状态
if let status = MalaOrderStatus(rawValue: (model?.status ?? "")) {
switch status {
case .penging:
statusLabel.text = "待支付"
statusLabel.textColor = UIColor(named: .OrderStatusRed)
break
case .paid:
statusLabel.text = "支付成功"
statusLabel.textColor = UIColor(named: .OrderGreen)
break
case .canceled:
statusLabel.text = "已关闭"
statusLabel.textColor = UIColor(named: .HeaderTitle)
break
case .refund:
statusLabel.text = "已退款"
statusLabel.textColor = UIColor(named: .OrderGreen)
break
case .confirm:
statusLabel.text = L10n.confirmOrder
statusLabel.textColor = UIColor(named: .OrderStatusRed)
break
default:
break
}
}
}
}
| mit | 4217e41f8f211d9006b6dff0f0e8eebd | 32.715762 | 128 | 0.580472 | 4.722403 | false | false | false | false |
mennovf/Swift-MathEagle | MathEagle/Source/Functions.swift | 1 | 2965 | //
// Functions.swift
// SwiftMath
//
// Created by Rugen Heidbuchel on 27/01/15.
// Copyright (c) 2015 Jorestha Solutions. All rights reserved.
//
import Foundation
/**
Returns the sign of the given value. Returns -1, 0 or 1.
- parameter x: The value to calculate the sign of
- returns: -1 if the value is smaller than 0, 0 if the value is 0 and 1 if the value is bigger than 0
*/
public func sign <X: protocol<Equatable, Comparable, IntegerLiteralConvertible>> (x: X) -> Int {
if x == 0 { return 0 }
else if x < 0 { return -1 }
else { return 1 }
}
/**
Returns the factorial of the given value, aka x!
- parameter x: The value to caculate the factorial of
- returns: The factorial of the given value
:exceptions: Throws an exception if the given value is not a natural number.
*/
public func factorial <X: protocol<Comparable, Substractable, Multiplicable, SetCompliant, IntegerLiteralConvertible>> (x: X) -> X {
if x < 0 {
NSException(name: "x < 0", reason: "The factorial does not exist for n < 0.", userInfo: nil).raise()
}
if !x.isInteger {
NSException(name: "x not integer", reason: "The factorial only exists for integers.", userInfo: nil).raise()
}
if x <= 1 { return 1 }
return x * factorial(x-1)
}
/**
Returns an array containing the factorials up to the given value. This means it contains the factorial
of all values smaller than or equal to the given value. The index in the array corresponds to the argument
of the factorial, so factorialsUpTo(x)[i] == factorial(i).
:example: factorialsUpTo(5) returns [1, 1, 2, 6, 24, 120]
*/
public func factorialsUpTo <X: protocol<Comparable, Addable, Substractable, Multiplicable, SetCompliant, IntegerLiteralConvertible>> (x: X) -> [X] {
if x < 0 { return [] }
var factorials: [X] = [1]
var i: X = 1
while i <= x {
factorials.append(factorials.last! * i)
i = i + 1
}
return factorials
}
/**
Returns the n'th Fibonacci number, with fib(0) = 0 and fib(1) = 1
*/
public func fib <X: protocol<Hashable, Addable, Substractable, IntegerLiteralConvertible>> (n: X) -> X {
var memo: [X: X] = [0: 0, 1: 1]
return memoFib(n, memo: &memo)
}
private func memoFib <X: protocol<Hashable, Addable, Substractable, IntegerLiteralConvertible>> (n: X, inout memo: [X: X]) -> X {
if let answer = memo[n] { return answer }
let answer = memoFib(n-1, memo: &memo) + memoFib(n-2, memo: &memo)
memo[n] = answer
return answer
}
/**
Returns an array containing the digits of the given number from most to least significant digits.
- parameter number: The number to get the digits of.
*/
public func digits(number: Int) -> [Int] {
//TODO: Benchmark this method.
return "\(abs(number))".characters.map{ Int("\($0)")! }
}
| mit | 5cef932be554146a6caaa07752ca933b | 26.453704 | 148 | 0.626644 | 3.796415 | false | false | false | false |
apple/swift-lldb | packages/Python/lldbsuite/test/lang/swift/expression/equality_operators/two.swift | 2 | 737 | // tow.swift
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
// -----------------------------------------------------------------------------
private func == (lhs : Fooey, rhs : Fooey) -> Bool
{
Fooey.BumpCounter(2)
return lhs.m_var != rhs.m_var // break here for two local operator
}
extension Fooey
{
public class func CompareEm2(_ lhs : Fooey, _ rhs : Fooey) -> Bool
{
return lhs == rhs
}
}
| apache-2.0 | dc54d0792c9c460f30686f2313284e89 | 28.48 | 80 | 0.598372 | 4.094444 | false | false | false | false |
spritekitbook/spritekitbook-swift | Chapter 9/Finish/SpaceRunner/SpaceRunner/Player.swift | 2 | 4842 | //
// Player.swift
// SpaceRunner
//
// Created by Jeremy Novak on 8/31/16.
// Copyright © 2016 Spritekit Book. All rights reserved.
//
import SpriteKit
class Player: SKSpriteNode {
// MARK: - Private class constants
private let touchOffset:CGFloat = 44.0
private let moveFilter:CGFloat = 0.05 // Filter movement by 5%
// MARK: - Private class variables
private var targetPosition = CGPoint()
private var score = 0
private var streak = 0
private var lives = 3
private var immune = false
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override init(texture: SKTexture?, color: UIColor, size: CGSize) {
super.init(texture: texture, color: color, size: size)
}
convenience init() {
let texture = GameTextures.sharedInstance.texture(name: SpriteName.player)
self.init(texture: texture, color: SKColor.white, size: texture.size())
setup()
setupPhysics()
self.name = "Player"
}
private func setup() {
// Initial position is centered horizontally and 20% up the Y axis
self.position = CGPoint(x: kViewSize.width / 2, y: kViewSize.height * 0.2)
targetPosition = self.position
}
private func setupPhysics() {
self.physicsBody = SKPhysicsBody(circleOfRadius: self.size.width / 2, center: self.anchorPoint)
self.physicsBody?.categoryBitMask = Contact.player
self.physicsBody?.collisionBitMask = 0x0
self.physicsBody?.contactTestBitMask = Contact.meteor | Contact.star
}
// MARK: - Update
func update() {
move()
}
// MARK: - Movement
func updateTargetPosition(position: CGPoint) {
targetPosition = CGPoint(x: position.x, y: position.y + touchOffset)
}
private func move() {
let newX = Smooth(startPoint: self.position.x, endPoint: targetPosition.x, percentToMove: moveFilter)
let newY = Smooth(startPoint: self.position.y, endPoint: targetPosition.y, percentToMove: moveFilter)
// "Clamp" the minimum and maximum X value to allow half the ship to go offscreen horizontally
let correctedX = Clamp(value: newX, min: 0 - self.size.width / 2, max: kViewSize.width + self.size.width / 2)
// "Clamp" the minimum and maximum Y value to not allow the ship to go off screen vertically
let correctedY = Clamp(value: newY, min: 0 + self.size.height, max: kViewSize.height - self.size.height)
self.position = CGPoint(x: correctedX, y: correctedY)
rotate()
}
private func rotate() {
if DistanceBetweenPoints(firstPoint: self.position, secondPoint: targetPosition) > 25 {
let angle = AngleBetweenPoints(targetPosition: targetPosition, currentPosition: self.position)
self.run(SKAction.rotate(toAngle: angle, duration: 0.16, shortestUnitArc: true))
} else {
let angle:CGFloat = 0.0
self.run(SKAction.rotate(toAngle: angle, duration: 0.16, shortestUnitArc: true))
}
}
// MARK: - Actions
private func blinkPlayer() {
let blink = SKAction.sequence([SKAction.fadeOut(withDuration: 0.15), SKAction.fadeIn(withDuration: 0.15)])
self.run(SKAction.repeatForever(blink), withKey: "Blink")
}
// MARK: - Contact
func contact(body: String) {
lives -= 1
streak = 0
if lives > 0 {
immune = true
blinkPlayer()
self.run(SKAction.wait(forDuration: 3.0), completion: {
[weak self] in
self?.immune = false
self?.removeAction(forKey: "Blink")
})
}
if kDebug {
print("Player made contact with \(body).")
}
}
func getLives() -> Int {
return lives
}
func getImmunity() -> Bool {
return immune
}
// MARK: - Score
private func increaseScore(bonus: Int) {
score += bonus
if kDebug {
print("Score: \(score)")
}
}
func pickup() {
streak += 1
switch streak {
case 0...5:
increaseScore(bonus: 250)
case 6...10:
increaseScore(bonus: 500)
case 11...15:
increaseScore(bonus: 750)
case 16...20:
increaseScore(bonus: 1000)
default:
increaseScore(bonus: 5000)
}
}
func updateDistanceScore() {
score += 1
if kDebug {
print("Score: \(score)")
}
}
}
| apache-2.0 | 8af09d9705cfbd5b792ca71b1b8dcf5a | 27.988024 | 117 | 0.565586 | 4.579943 | false | false | false | false |
breadwallet/breadwallet | BreadWallet/BRAPIProxy.swift | 2 | 5299 | //
// BRAPIProxy.swift
// BreadWallet
//
// Created by Samuel Sutch on 2/8/16.
// Copyright (c) 2016 breadwallet LLC
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
// Add this middleware to a BRHTTPServer to expose a proxy to the breadwallet HTTP api
// It has all the capabilities of the real API but with the ability to authenticate
// requests using the users private keys stored on device.
//
// Clients should set the "X-Should-Authenticate" to sign requests with the users private authentication key
@objc open class BRAPIProxy: NSObject, BRHTTPMiddleware {
var mountPoint: String
var apiInstance: BRAPIClient
var shouldAuthHeader: String = "x-should-authenticate"
var bannedSendHeaders: [String] {
return [
shouldAuthHeader,
"connection",
"authorization",
"host",
"user-agent"
]
}
var bannedReceiveHeaders: [String] = ["content-length", "content-encoding", "connection"]
init(mountAt: String, client: BRAPIClient) {
mountPoint = mountAt
if mountPoint.hasSuffix("/") {
mountPoint = mountPoint.substring(to: mountPoint.characters.index(mountPoint.endIndex, offsetBy: -1))
}
apiInstance = client
super.init()
}
open func handle(_ request: BRHTTPRequest, next: @escaping (BRHTTPMiddlewareResponse) -> Void) {
if request.path.hasPrefix(mountPoint) {
let idx = request.path.characters.index(request.path.startIndex, offsetBy: mountPoint.characters.count)
var path = request.path.substring(from: idx)
if request.queryString.utf8.count > 0 {
path += "?\(request.queryString)"
}
var nsReq = URLRequest(url: apiInstance.url(path))
nsReq.httpMethod = request.method
// copy body
if request.hasBody {
nsReq.httpBody = request.body()
}
// copy headers
for (hdrName, hdrs) in request.headers {
if bannedSendHeaders.contains(hdrName) { continue }
for hdr in hdrs {
nsReq.setValue(hdr, forHTTPHeaderField: hdrName)
}
}
var auth = false
if let authHeader = request.headers[shouldAuthHeader] , authHeader.count > 0 {
if authHeader[0].lowercased() == "yes" || authHeader[0].lowercased() == "true" {
auth = true
}
}
apiInstance.dataTaskWithRequest(nsReq, authenticated: auth, retryCount: 0, handler:
{ (nsData, nsHttpResponse, nsError) -> Void in
if let httpResp = nsHttpResponse {
var hdrs = [String: [String]]()
for (k, v) in httpResp.allHeaderFields {
if self.bannedReceiveHeaders.contains((k as! String).lowercased()) { continue }
hdrs[k as! String] = [v as! String]
}
var body: [UInt8]? = nil
if let bod = nsData {
let bp = (bod as NSData).bytes.bindMemory(to: UInt8.self, capacity: bod.count)
let b = UnsafeBufferPointer<UInt8>(start: bp, count: bod.count)
body = Array(b)
}
let resp = BRHTTPResponse(
request: request, statusCode: httpResp.statusCode,
statusReason: HTTPURLResponse.localizedString(forStatusCode: httpResp.statusCode),
headers: hdrs, body: body)
return next(BRHTTPMiddlewareResponse(request: request, response: resp))
} else {
print("[BRAPIProxy] error getting response from backend: \(String(describing: nsError))")
return next(BRHTTPMiddlewareResponse(request: request, response: nil))
}
}).resume()
} else {
return next(BRHTTPMiddlewareResponse(request: request, response: nil))
}
}
}
| mit | 8c5498ae3cb71f76d382da485b6c57f7 | 45.482456 | 115 | 0.592942 | 4.906481 | false | false | false | false |
Havi4/actor-platform | actor-apps/app-ios/ActorApp/Controllers/Contacts/ContactsSearchSource.swift | 24 | 1608 | //
// Copyright (c) 2014-2015 Actor LLC. <https://actor.im>
//
import Foundation
class ContactsSearchSource: SearchSource {
override func buildCell(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath, item: AnyObject?) -> UITableViewCell {
let reuseId = "cell_contact";
var cell = tableView.dequeueReusableCellWithIdentifier(reuseId) as! ContactCell?;
if (cell == nil) {
cell = ContactCell(reuseIdentifier:reuseId);
}
return cell!;
}
override func bindCell(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath, item: AnyObject?, cell: UITableViewCell) {
var contact = item as! ACContact;
let isLast = indexPath.row == tableView.numberOfRowsInSection(indexPath.section)-1;
// Building short name
var shortName : String? = nil;
if (indexPath.row == 0) {
shortName = contact.getName().smallValue();
} else {
var prevContact = objectAtIndexPath(NSIndexPath(forRow: indexPath.row-1, inSection: indexPath.section)) as! ACContact;
var prevName = prevContact.getName().smallValue();
var name = contact.getName().smallValue();
if (prevName != name){
shortName = name;
}
}
(cell as! ContactCell).bindContact(contact, shortValue: shortName, isLast: isLast);
}
override func buildDisplayList() -> ARBindedDisplayList {
return Actor.buildContactsDisplayList()
}
} | mit | 23407d9e2891195295b6d39d464de1b4 | 33.978261 | 139 | 0.612562 | 5.187097 | false | false | false | false |
dterana/Pokedex-API | Sources/App/main.swift | 1 | 289 | import Vapor
import VaporPostgreSQL
import Fluent
let drop = Droplet()
try drop.addProvider(VaporPostgreSQL.Provider)
drop.preparations += Pokemon.self
drop.preparations += Type.self
drop.preparations += Pokemon_Type.self
let api = APIController()
api.addRoutes(drop: drop)
drop.run()
| mit | 653d75cfa2e7302095b78d67c9d6dce9 | 18.266667 | 46 | 0.785467 | 3.753247 | false | false | false | false |
Yalantis/DisplaySwitcher | Pod/Classes/Layouts/DisplaySwitchLayout.swift | 1 | 5269 | //
// DisplaySwitchLayout.swift
// YALLayoutTransitioning
//
// Created by Roman on 29.02.16.
// Copyright © 2016 Yalantis. All rights reserved.
//
import UIKit
private let ListLayoutCountOfColumns = 1
private let GridLayoutCountOfColumns = 3
@objc public enum LayoutState: Int {
case list, grid
}
open class DisplaySwitchLayout: UICollectionViewLayout {
fileprivate let numberOfColumns: Int
fileprivate let cellPadding: CGFloat = 6.0
fileprivate let staticCellHeight: CGFloat
fileprivate let nextLayoutStaticCellHeight: CGFloat
fileprivate var previousContentOffset: NSValue?
fileprivate var layoutState: LayoutState
fileprivate var baseLayoutAttributes: [DisplaySwitchLayoutAttributes]!
fileprivate var contentHeight: CGFloat = 0.0
fileprivate var contentWidth: CGFloat {
let insets = collectionView!.contentInset
return collectionView!.bounds.width - insets.left - insets.right
}
// MARK: - Lifecycle
public init(staticCellHeight: CGFloat, nextLayoutStaticCellHeight: CGFloat, layoutState: LayoutState) {
self.staticCellHeight = staticCellHeight
self.numberOfColumns = layoutState == .list ? ListLayoutCountOfColumns : GridLayoutCountOfColumns
self.layoutState = layoutState
self.nextLayoutStaticCellHeight = nextLayoutStaticCellHeight
super.init()
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - UICollectionViewLayout
override open func prepare() {
super.prepare()
baseLayoutAttributes = [DisplaySwitchLayoutAttributes]()
// cells layout
contentHeight = 0
let columnWidth = contentWidth / CGFloat(numberOfColumns)
var xOffsets = [CGFloat]()
for column in 0 ..< numberOfColumns {
xOffsets.append(CGFloat(column) * columnWidth)
}
var column = 0
var yOffset = [CGFloat](repeating: contentHeight, count: numberOfColumns)
if let collectionView = collectionView {
for item in 0 ..< collectionView.numberOfItems(inSection: 0) {
let indexPath = IndexPath(item: item, section: 0)
let height = cellPadding + staticCellHeight
let frame = CGRect(x: xOffsets[column], y: yOffset[column], width: columnWidth, height: height)
let insetFrame = frame.insetBy(dx: cellPadding, dy: cellPadding)
let attributes = DisplaySwitchLayoutAttributes(forCellWith: indexPath)
attributes.frame = insetFrame
baseLayoutAttributes.append(attributes)
contentHeight = max(contentHeight, frame.maxY)
yOffset[column] = yOffset[column] + height
column = column == (numberOfColumns - 1) ? 0 : column + 1
}
}
}
override open var collectionViewContentSize: CGSize {
return CGSize(width: contentWidth, height: contentHeight)
}
override open func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
let layoutAttributes = baseLayoutAttributes.filter { $0.frame.intersects(rect) }
return layoutAttributes
}
override open func layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? {
return baseLayoutAttributes[indexPath.row]
}
override open class var layoutAttributesClass: AnyClass {
return DisplaySwitchLayoutAttributes.self
}
// Fix bug with content offset
override open func targetContentOffset(forProposedContentOffset proposedContentOffset: CGPoint) -> CGPoint {
let previousContentOffsetPoint = previousContentOffset?.cgPointValue
let superContentOffset = super.targetContentOffset(forProposedContentOffset: proposedContentOffset)
if let previousContentOffsetPoint = previousContentOffsetPoint {
if previousContentOffsetPoint.y == 0 {
return previousContentOffsetPoint
}
if layoutState == LayoutState.list {
let offsetY = ceil(previousContentOffsetPoint.y + (staticCellHeight * previousContentOffsetPoint.y / nextLayoutStaticCellHeight) + cellPadding)
return CGPoint(x: superContentOffset.x, y: offsetY)
} else {
let realOffsetY = ceil((previousContentOffsetPoint.y / nextLayoutStaticCellHeight * staticCellHeight / CGFloat(numberOfColumns)) - cellPadding)
let offsetY = floor(realOffsetY / staticCellHeight) * staticCellHeight + cellPadding
return CGPoint(x: superContentOffset.x, y: offsetY)
}
}
return superContentOffset
}
override open func prepareForTransition(from oldLayout: UICollectionViewLayout) {
previousContentOffset = NSValue(cgPoint: collectionView!.contentOffset)
return super.prepareForTransition(from: oldLayout)
}
override open func finalizeLayoutTransition() {
previousContentOffset = nil
super.finalizeLayoutTransition()
}
}
| mit | 262312dd103d7e1ce1cad45a48709b41 | 37.735294 | 159 | 0.672361 | 5.945824 | false | false | false | false |
qmathe/Confetti | Renderer/AppKitRenderer.swift | 1 | 8935 | /**
Copyright (C) 2016 Quentin Mathe
Author: Quentin Mathe <[email protected]>
Date: August 2016
License: MIT
*/
import Foundation
import Tapestry
extension Sequence where Iterator.Element : Equatable {
func contains(_ element: Self.Iterator.Element?) -> Bool {
guard let e = element else {
return false
}
return contains(e)
}
}
/**
* To generate a AppKit UI, do item.render(AppKitRenderer()).
*/
open class AppKitRenderer: Renderer {
public let destination: NSView?
internal var windows = [Item: NSWindow]()
internal var views = [Item: NSView]()
internal var startItem: Item?
public required init(destination: RendererDestination? = nil) {
guard let destination = destination as? NSView? else {
fatalError("Unsupported destination type")
}
self.destination = destination
}
fileprivate func viewForItem(_ item: Item, create: (() -> NSView)) -> NSView {
return nodeForItem(item, in: &views, create: create)
}
fileprivate func nodeForItem<K, V>(_ item: K, in nodes: inout [K: V], create: (() -> V)) -> V {
if let node = nodes[item] {
return node
}
else {
let node = create()
nodes[item] = node
return node
}
}
fileprivate func discardUnusedNodesFor(_ newStartItem: Item, oldStartItem: Item?) {
let existingViews = Set(views.values)
let existingWindowBackedItems = Set(windows.keys)
let keptItems = Set(ItemTreeIterator(item: newStartItem).descendantItems)
for (item, window) in windows {
if keptItems.contains(item) {
precondition(existingViews.contains(window.contentView))
continue
}
windows.removeValue(forKey: item)
window.orderOut(nil)
// FIXME: window.close()
}
for (item, view) in views {
if keptItems.contains(item) {
if let superview = view.superview
, item != oldStartItem && item != newStartItem {
precondition(existingViews.contains(superview) || existingWindowBackedItems.contains(item))
}
else {
precondition(view == destination)
}
continue
}
views.removeValue(forKey: item)
if item == oldStartItem {
view.removeFromSuperview()
}
}
}
/// Initiates a recursive rendering starting at the given item.
///
/// The start item can be a root item or not, but will always correspond to
/// the root rendered node.
///
/// This method is never called recursively.
open func renderItem(_ item: Item) -> RenderedNode {
defer {
discardUnusedNodesFor(item, oldStartItem: startItem)
startItem = item
}
if item.isRoot {
return renderRoot(item)
}
else {
return renderView(item)
}
}
fileprivate func renderRoot(_ item: Item) -> RenderedNode {
if let destination = destination {
views[item] = destination
// Don't resize or move the destination
renderViews(item.items ?? [], intoView: destination)
return destination
}
else {
return AppKitRootNode(windows: item.items?.map { renderWindow($0) as! NSWindow } ?? [])
}
}
fileprivate func renderViews(_ items: [Item], intoView view: NSView) {
view.subviews = items.map { $0.render(self) as! NSView }
precondition(zip(view.subviews, items).reduce(true) { $0 && $1.0.frame.origin.x == $1.1.origin.x && $1.0.frame.origin.y == $1.1.origin.y })
// Adjust the origin to compensate the coordinate system differences
//
// When the view was instantiated, the superview wasn't available
// to determine the correct origin.
view.subviews.forEach { $0.confettiFrame = RectFromCGRect($0.frame) }
}
/// Geometry changes requires the parent item to be rendered in the same pass,
/// otherwise the rendered view won't match the latest size and position.
open func renderView(_ item: Item) -> RenderedNode {
let view = viewForItem(item) { ConfettiView(item) }
renderViews(item.items ?? [], intoView: view)
return view
}
/// For a window unlike a view, we can determine the correct origin
/// immediately, since we can know the screen where it will appear.
fileprivate func renderWindow(_ item: Item) -> RenderedNode {
let styleMask: NSWindow.StyleMask = [NSWindow.StyleMask.titled, NSWindow.StyleMask.closable, NSWindow.StyleMask.miniaturizable, NSWindow.StyleMask.resizable, NSWindow.StyleMask.unifiedTitleAndToolbar]
let window = nodeForItem(item, in: &windows) { NSWindow(contentRect: CGRectFromRect(item.frame), styleMask: styleMask, backing: .buffered, defer: false) }
window.contentView = (item.render(self) as! NSView)
if item.isFrontmost {
window.makeKey()
}
window.orderFront(nil)
// Adjust the origin to compensate coordinate system differences
window.confettiFrame = item.frame
return window
}
open func renderButton(_ item: Item) -> RenderedNode {
let button = viewForItem(item) { NSButton(frame: CGRectFromRect(item.frame)) } as! NSButton
button.setButtonType(.momentaryLight)
button.bezelStyle = .rounded
button.title = (item.controlState as? ButtonState)?.text ?? ""
button.setAction { [weak item = item] (sender: NSButton) in item?.reactTo(sender, isSwitch: false) }
return button
}
open func renderLabel(_ item: Item) -> RenderedNode {
let label = viewForItem(item) { NSTextField(frame: CGRectFromRect(item.frame)) } as! NSTextField
label.stringValue = (item.controlState as? LabelState)?.text ?? ""
label.isBezeled = false
label.drawsBackground = false
label.isEditable = false
label.isSelectable = false
return label
}
open func renderSlider(_ item: Item) -> RenderedNode {
let slider = viewForItem(item) { NSSlider(frame: CGRectFromRect(item.frame)) } as! NSSlider
let state = item.controlState as? SliderState
slider.minValue = Double(state?.minValue ?? 0)
slider.maxValue = Double(state?.maxValue ?? 0)
slider.objectValue = state?.initialValue ?? 0
slider.setAction { [weak item = item] (sender: NSSlider) in item?.reactTo(sender) }
if item.orientation == .horizontal {
slider.frame.size.height = defaultSliderThickness
}
else {
slider.frame.size.width = defaultSliderThickness
}
return slider
}
open func renderSwitch(_ item: Item) -> RenderedNode {
let button = viewForItem(item) { NSButton(frame: CGRectFromRect(item.frame)) } as! NSButton
button.frame.size.height = defaultSwitchHeight
button.title = (item.controlState as? SwitchState)?.text ?? ""
button.state = NSControl.StateValue(rawValue: (item.controlState as? SwitchState)?.status.value.rawValue ?? 0)
button.setButtonType(.switch)
button.setAction { [weak item = item] (sender: NSButton) in item?.reactTo(sender, isSwitch: true) }
return button
}
// MARK: - Position and Size Constants
var defaultSwitchHeight: CGFloat = 18
var defaultSliderThickness: CGFloat = 21
func reactToActionFrom(_ sender: NSObject) {
}
}
// MARK: - Utilities
internal func RectFromCGRect(_ rect: CGRect) -> Rect {
return Rect(x: rect.origin.x, y: rect.origin.y, width: rect.size.width, height: rect.size.height)
}
internal func CGRectFromRect(_ rect: Rect) -> CGRect {
return CGRect(x: rect.origin.x, y: rect.origin.y, width: rect.extent.width, height: rect.extent.height)
}
extension Point {
init(_ point: CGPoint) { self.init(x: point.x, y: point.y) }
}
extension CGPoint {
init(_ point: Point) { self.init(x: point.x, y: point.y) }
}
// MARK: - Rendered Nodes
extension NSView: RendererDestination, RenderedNode {
internal var confettiFrame: Rect {
get {
if let superview = superview , superview.isFlipped == false {
var rect = frame
rect.origin.y = superview.frame.size.height - frame.maxY
return RectFromCGRect(rect)
}
else {
return RectFromCGRect(frame)
}
}
set {
if let superview = superview , superview.isFlipped == false {
var rect = CGRectFromRect(newValue)
rect.origin.y = superview.frame.size.height - rect.maxY
frame = rect
}
else {
frame = CGRectFromRect(newValue)
}
}
}
}
extension NSWindow: RenderedNode {
internal var confettiFrame: Rect {
get {
if let screen = screen {
var rect = frame
rect.origin.y = screen.visibleFrame.size.height - frame.maxY
return RectFromCGRect(contentRect(forFrameRect: rect))
}
else {
return RectFromCGRect(contentRect(forFrameRect: frame))
}
}
set {
if let screen = screen {
var rect = frameRect(forContentRect: CGRectFromRect(newValue))
rect.origin.y = screen.visibleFrame.size.height - rect.maxY
setFrame(rect, display: false)
}
else {
setFrame(frameRect(forContentRect: CGRectFromRect(newValue)), display: false)
}
}
}
internal func point(from point: CGPoint) -> Point {
var confettiPoint = Point(point)
confettiPoint.y = frame.height - confettiPoint.y
return confettiPoint
}
}
/// A dummy node returned when the rendered item is the root item.
class AppKitRootNode: RenderedNode {
let windows: [NSWindow]
init(windows: [NSWindow]) {
self.windows = windows
}
}
| mit | 6e76ffa0edad5152d7d59bda41669950 | 27.18612 | 202 | 0.695803 | 3.642479 | false | false | false | false |
ALiOSDev/ALTableView | ALTableViewSwift/ALTableView/ALTableView/ALTableViewClasses/ALTableView/ALTableViewDelegate.swift | 1 | 4355 | //
// ALTableViewDelegate.swift
// ALTableView
//
// Created by lorenzo villarroel perez on 16/3/18.
// Copyright © 2018 lorenzo villarroel perez. All rights reserved.
//
import UIKit
//MARK: - UITableViewDelegate
extension ALTableView: UITableViewDelegate {
//MARK: - Configuring Rows
public func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return self.getSectionElementAt(index: indexPath.section)?.getRowHeight(at: indexPath.row) ?? 0.0
}
public func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
return self.getSectionElementAt(index: indexPath.section)?.getRowEstimatedHeight(at: indexPath.row) ?? 0.0
}
public func tableView(_ tableView: UITableView, indentationLevelForRowAt indexPath: IndexPath) -> Int {
return 0
}
public func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
//We set up the cellHeight again to avoid stuttering scroll when using automatic dimension with cells
let cellHeight: CGFloat = cell.frame.size.height
self.getSectionElementAt(index: indexPath.section)?.setRowElementHeight(row: indexPath.row, height: cellHeight)
if self.isLastIndexPath(indexPath: indexPath, tableView: tableView) {
//We reached the end of the tableView
self.delegate?.tableViewDidReachEnd?()
}
}
//MARK: - Managing selections
public func tableView(_ tableView: UITableView, willSelectRowAt indexPath: IndexPath) -> IndexPath? {
return indexPath
}
public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
guard let cell: UITableViewCell = tableView.cellForRow(at: indexPath) else {
return
}
self.getSectionElementAt(index: indexPath.section)?.rowElementPressed(row: indexPath.row, viewController: self.viewController, cell: cell)
}
public func tableView(_ tableView: UITableView, willDeselectRowAt indexPath: IndexPath) -> IndexPath? {
return indexPath
}
public func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
guard let cell: UITableViewCell = tableView.cellForRow(at: indexPath) else {
return
}
self.getSectionElementAt(index: indexPath.section)?.rowElementDeselected(row: indexPath.row, cell: cell)
}
//MARK: - Modifying Header and Footer of Sections
public func tableView(_ tableView: UITableView, estimatedHeightForHeaderInSection section: Int) -> CGFloat {
return self.getSectionElementAt(index: section)?.getHeaderEstimatedHeight() ?? 0.0
}
public func tableView(_ tableView: UITableView, estimatedHeightForFooterInSection section: Int) -> CGFloat {
return self.getSectionElementAt(index: section)?.getFooterEstimatedHeight() ?? 0.0
}
public func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
return self.getSectionElementAt(index: section)?.getHeaderFrom(tableView: tableView)
}
public func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
return self.getSectionElementAt(index: section)?.getFooterFrom(tableView: tableView)
}
public func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return self.getSectionElementAt(index: section)?.getHeaderHeight() ?? 0.0
}
public func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
return self.getSectionElementAt(index: section)?.getFooterHeight() ?? 0.0
}
}
//MARK: - Private methods
extension ALTableView {
private func isLastIndexPath (indexPath: IndexPath, tableView: UITableView) -> Bool {
let isLastSection: Bool = indexPath.section == tableView.numberOfSections - 1
let isLastRow: Bool = indexPath.row == tableView.numberOfRows(inSection: indexPath.section) - 1
return isLastSection && isLastRow
}
}
| mit | f23cba5a6f4c06a07517f39c71812ae0 | 35.898305 | 146 | 0.679835 | 5.362069 | false | false | false | false |
rambler-digital-solutions/rambler-it-ios | Carthage/Checkouts/rides-ios-sdk/source/UberRides/Model/PriceEstimate.swift | 1 | 5528 | //
// PriceEstimate.swift
// UberRides
//
// Copyright © 2015 Uber Technologies, Inc. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
// MARK: PriceEstimates
/**
* Internal object that contains a list of price estimates for Uber products.
*/
struct PriceEstimates: Codable {
var list: [PriceEstimate]?
enum CodingKeys: String, CodingKey {
case list = "prices"
}
}
// MARK: PriceEstimate
/**
* Contains information about estimated price range for each Uber product offered at a location.
*/
@objc(UBSDKPriceEstimate) public class PriceEstimate: NSObject, Codable {
/// ISO 4217 currency code.
@objc public private(set) var currencyCode: String?
/// Expected activity distance (in miles).
@nonobjc public private(set) var distance: Double?
/// Expected activity distance (in miles). -1 if not present.
@objc(distance) public var objc_distance: Double {
return distance ?? UBSDKDistanceUnavailable
}
/// Expected activity duration (in seconds).
@nonobjc public private(set) var duration: Int?
/// Expected activity duration (in seconds). UBSDKEstimateUnavailable if not present.
@objc(duration) public var objc_duration: Int {
return duration ?? UBSDKEstimateUnavailable
}
/// A formatted string representing the estimate in local currency. Could be range, single number, or "Metered" for TAXI.
@objc public private(set) var estimate: String?
/// Upper bound of the estimated price.
@nonobjc public private(set) var highEstimate: Int?
/// Upper bound of the estimated price. UBSDKEstimateUnavailable if not present.
@objc(highEstimate) public var objc_highEstimate: Int {
return highEstimate ?? UBSDKEstimateUnavailable
}
/// Lower bound of the estimated price.
@nonobjc public private(set) var lowEstimate: Int?
/// Lower bound of the estimated price. UBSDKEstimateUnavailable if not present.
@objc(lowEstimate) public var objc_lowEstimate: Int {
return lowEstimate ?? UBSDKEstimateUnavailable
}
/// Display name of product. Ex: "UberBLACK".
@objc public private(set) var name: String?
/// Unique identifier representing a specific product for a given latitude & longitude.
@objc public private(set) var productID: String?
/// The unique identifier of the surge session for a user. Nil for no surge.
@objc public private(set) var surgeConfirmationID: String?
/// The URL a user must visit to accept surge pricing.
@objc public private(set) var surgeConfirmationURL: URL?
/// Expected surge multiplier (active if surge is greater than 1).
@objc public private(set) var surgeMultiplier: Double
enum CodingKeys: String, CodingKey {
case currencyCode = "currency_code"
case distance = "distance"
case duration = "duration"
case estimate = "estimate"
case highEstimate = "high_estimate"
case lowEstimate = "low_estimate"
case name = "display_name"
case productID = "product_id"
case surgeConfirmationID = "surge_confirmation_id"
case surgeConfirmationURL = "surge_confirmation_href"
case surgeMultiplier = "surge_multiplier"
}
public required init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
currencyCode = try container.decodeIfPresent(String.self, forKey: .currencyCode)
distance = try container.decodeIfPresent(Double.self, forKey: .distance)
duration = try container.decodeIfPresent(Int.self, forKey: .duration)
estimate = try container.decodeIfPresent(String.self, forKey: .estimate)
highEstimate = try container.decodeIfPresent(Int.self, forKey: .highEstimate)
lowEstimate = try container.decodeIfPresent(Int.self, forKey: .lowEstimate)
name = try container.decodeIfPresent(String.self, forKey: .name)
productID = try container.decodeIfPresent(String.self, forKey: .productID)
surgeConfirmationID = try container.decodeIfPresent(String.self, forKey: .surgeConfirmationID)
surgeConfirmationURL = try container.decodeIfPresent(URL.self, forKey: .surgeConfirmationURL)
surgeMultiplier = try container.decodeIfPresent(Double.self, forKey: .surgeMultiplier) ?? 1.0
}
}
| mit | 27c8a105cc52d2f380a2f61b53fbab7b | 42.865079 | 125 | 0.698752 | 4.756454 | false | false | false | false |
RMizin/PigeonMessenger-project | FalconMessenger/ChatsControllers/AttachCollectionViewCell+TimerHandlers.swift | 1 | 1427 | //
// AttachCollectionViewCell+TimerHandlers.swift
// Pigeon-project
//
// Created by Roman Mizin on 11/26/17.
// Copyright © 2017 Roman Mizin. All rights reserved.
//
import UIKit
extension AttachCollectionViewCell {
typealias CompletionHandler = (_ success: Bool) -> Void
func runTimer() {
playerView.timer = Timer.scheduledTimer(timeInterval: 1,
target: self,
selector: (#selector(updateTimer)),
userInfo: nil,
repeats: true)
}
@objc func updateTimer() {
if playerView.seconds < 1 {
resetTimer()
} else {
playerView.seconds -= 1
playerView.timerLabel.text = timeString(time: TimeInterval(playerView.seconds))
}
}
func resetTimer() {
playerView.timer?.invalidate()
playerView.seconds = playerView.startingTime
playerView.timerLabel.text = timeString(time: TimeInterval(playerView.seconds))
UIView.animate(withDuration: 0.2, animations: {
self.playerView.alpha = 0.85
self.playerView.backgroundColor = .black
})
}
func timeString(time: TimeInterval) -> String {
let hours = Int(time) / 3600
let minutes = Int(time) / 60 % 60
let seconds = Int(time) % 60
return String(format: "%02i:%02i:%02i", hours, minutes, seconds)
}
}
| gpl-3.0 | d198bb5c9647a95f4fc046b143e777d8 | 28.102041 | 85 | 0.590463 | 4.644951 | false | false | false | false |
warnerbros/cpe-manifest-ios-experience | Source/In-Movie Experience/ShoppingSceneDetailCollectionViewCell.swift | 1 | 4625 | //
// ShoppingSceneDetailCollectionViewCell.swift
//
import Foundation
import UIKit
import CPEData
enum ShoppingProductImageType {
case product
case scene
}
class ShoppingSceneDetailCollectionViewCell: SceneDetailCollectionViewCell {
static let NibName = "ShoppingSceneDetailCollectionViewCell"
static let ReuseIdentifier = "ShoppingSceneDetailCollectionViewCellReuseIdentifier"
@IBOutlet weak private var imageView: UIImageView!
@IBOutlet weak private var bullseyeImageView: UIImageView!
@IBOutlet weak private var extraDescriptionLabel: UILabel!
var productImageType = ShoppingProductImageType.product
private var extraDescription: String? {
set {
extraDescriptionLabel?.text = newValue
}
get {
return extraDescriptionLabel?.text
}
}
private var currentProduct: ProductItem? {
didSet {
if currentProduct != oldValue {
descriptionText = currentProduct?.brand
extraDescription = currentProduct?.name
if productImageType == .scene {
setImageURL(currentProduct?.sceneImageURL ?? currentProduct?.productImageURL)
} else {
setImageURL(currentProduct?.productImageURL)
}
}
if currentProduct == nil {
currentProductFrameTime = -1
}
}
}
private var currentProductFrameTime = -1.0
private var currentProductSessionDataTask: URLSessionDataTask?
var products: [ProductItem]? {
didSet {
currentProduct = products?.first
}
}
override func currentTimeDidChange() {
if let timedEvent = timedEvent, timedEvent.isType(.product) {
if let product = timedEvent.product {
products = [product]
} else {
DispatchQueue.global(qos: .userInteractive).async {
if let productAPIUtil = CPEXMLSuite.Settings.productAPIUtil {
let newFrameTime = productAPIUtil.closestFrameTime(self.currentTime)
if newFrameTime != self.currentProductFrameTime {
self.currentProductFrameTime = newFrameTime
if let currentTask = self.currentProductSessionDataTask {
currentTask.cancel()
}
self.currentProductSessionDataTask = productAPIUtil.getFrameProducts(self.currentProductFrameTime, completion: { [weak self] (products) -> Void in
self?.currentProductSessionDataTask = nil
DispatchQueue.main.async {
self?.products = products
}
})
}
}
}
}
}
}
override func prepareForReuse() {
super.prepareForReuse()
products = nil
bullseyeImageView.isHidden = true
if let task = currentProductSessionDataTask {
task.cancel()
currentProductSessionDataTask = nil
}
}
override func layoutSubviews() {
super.layoutSubviews()
if productImageType == .scene, let product = currentProduct, product.bullseyePoint != CGPoint.zero {
var bullseyeFrame = bullseyeImageView.frame
let bullseyePoint = CGPoint(x: imageView.frame.width * product.bullseyePoint.x, y: imageView.frame.height * product.bullseyePoint.y)
bullseyeFrame.origin = CGPoint(x: bullseyePoint.x + imageView.frame.minX - (bullseyeFrame.width / 2), y: bullseyePoint.y + imageView.frame.minY - (bullseyeFrame.height / 2))
bullseyeImageView.frame = bullseyeFrame
bullseyeImageView.layer.shadowColor = UIColor.black.cgColor
bullseyeImageView.layer.shadowOffset = CGSize(width: 1, height: 1)
bullseyeImageView.layer.shadowOpacity = 0.75
bullseyeImageView.layer.shadowRadius = 2
bullseyeImageView.clipsToBounds = false
bullseyeImageView.isHidden = false
} else {
bullseyeImageView.isHidden = true
}
}
private func setImageURL(_ imageURL: URL?) {
if let url = imageURL {
imageView.contentMode = .scaleAspectFit
imageView.sd_setImage(with: url)
} else {
imageView.sd_cancelCurrentImageLoad()
imageView.image = nil
}
}
}
| apache-2.0 | 74e4c4ee3e5a90fed1e77576a1c173d8 | 34.305344 | 185 | 0.594162 | 5.998703 | false | false | false | false |
webim/webim-client-sdk-ios | Example/WebimClientLibrary/AppearanceSettings/ColourConstants.swift | 1 | 7465 | //
// ColourConstants.swift
// WebimClientLibrary_Example
//
// Created by Eugene Ilyin on 15.10.2019.
// Copyright © 2019 Webim. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
import Foundation
import UIKit
// MARK: - Colours
fileprivate let CLEAR = #colorLiteral(red: 0, green: 0, blue: 0, alpha: 0)
fileprivate let WHITE = #colorLiteral(red: 0.9999960065, green: 1, blue: 1, alpha: 1)
fileprivate let BLACK = #colorLiteral(red: 0, green: 0, blue: 0, alpha: 1)
fileprivate let LIGHT_GREY = #colorLiteral(red: 0.8823529412, green: 0.8901960784, blue: 0.9176470588, alpha: 1)
fileprivate let GREY = #colorLiteral(red: 0.4901960784, green: 0.4980392157, blue: 0.5843137255, alpha: 1)
fileprivate let NO_CONNECTION_GREY = #colorLiteral(red: 0.4784313725, green: 0.4941176471, blue: 0.5803921569, alpha: 1)
fileprivate let TRANSLUCENT_GREY = #colorLiteral(red: 1, green: 1, blue: 1, alpha: 0.5)
fileprivate let WEBIM_CYAN = #colorLiteral(red: 0.08675732464, green: 0.6737991571, blue: 0.8237424493, alpha: 1)
fileprivate let WEBIM_PUPRLE = #colorLiteral(red: 0.2235294118, green: 0.2470588235, blue: 0.4196078431, alpha: 1)
fileprivate let WEBIM_DARK_PUPRLE = #colorLiteral(red: 0.1529411765, green: 0.1647058824, blue: 0.3058823529, alpha: 1)
fileprivate let WEBIM_LIGHT_PURPLE = #colorLiteral(red: 0.4117647059, green: 0.4235294118, blue: 0.568627451, alpha: 1)
fileprivate let WEBIM_RED = #colorLiteral(red: 1, green: 0.1491314173, blue: 0, alpha: 1)
fileprivate let WEBIM_GREY = #colorLiteral(red: 0, green: 0, blue: 0, alpha: 0.5)
fileprivate let WEBIM_LIGHT_BLUE = #colorLiteral(red: 0.9411764706, green: 0.9725490196, blue: 0.9843137255, alpha: 1)
fileprivate let WEBIM_LIGHT_CYAN = #colorLiteral(red: 0.02352941176, green: 0.5411764706, blue: 0.7058823529, alpha: 0.15)
// MARK: - Views' colour properties
// FlexibleTableViewCell.swift
let flexibleTableViewCellBackgroundColour = CLEAR
/// System
let messageBodyLabelColourSystem = WEBIM_LIGHT_PURPLE
let messageBackgroundViewColourSystem = LIGHT_GREY
let messageBackgroundViewColourClear = CLEAR
/// Visitor
let messageBodyLabelColourVisitor = WHITE
let messageBackgroundViewColourVisitor = WEBIM_CYAN
let documentFileNameLabelColourVisitor = WHITE
let documentFileDescriptionLabelColourVisitor = LIGHT_GREY
let quoteLineViewColourVisitor = WHITE
let quoteUsernameLabelColourVisitor = WHITE
let quoteBodyLabelColourVisitor = LIGHT_GREY
/// Operator
let messageUsernameLabelColourOperator = WEBIM_CYAN
let messageBodyLabelColourOperator = WEBIM_DARK_PUPRLE
let messageBackgroundViewColourOperator = WHITE
let documentFileNameLabelColourOperator = WEBIM_DARK_PUPRLE
let documentFileDescriptionLabelColourOperator = GREY
let imageUsernameLabelColourOperator = WHITE
let imageUsernameLabelBackgroundViewColourOperator = WEBIM_GREY
let quoteLineViewColourOperator = WEBIM_CYAN
let quoteUsernameLabelColourOperator = WEBIM_DARK_PUPRLE
/// Other
let quoteBodyLabelColourOperator = GREY
let quoteBackgroundColor = WEBIM_LIGHT_BLUE
let dateLabelColour = GREY
let timeLabelColour = GREY
let messageStatusIndicatorColour = WEBIM_DARK_PUPRLE.cgColor
let documentFileStatusPercentageIndicatorColour = WEBIM_CYAN.cgColor
let buttonDefaultBackgroundColour = WHITE
let buttonChoosenBackgroundColour = WEBIM_CYAN
let buttonCanceledBackgroundColour = WHITE
let buttonDefaultTitleColour = WEBIM_CYAN
let buttonChoosenTitleColour = WHITE
let buttonCanceledTitleColour = WEBIM_GREY
// RateStarsViewController.swift
let cosmosViewFilledColour = WEBIM_CYAN
let cosmosViewFilledBorderColour = WEBIM_CYAN
let cosmosViewEmptyColour = LIGHT_GREY
let cosmosViewEmptyBorderColour = LIGHT_GREY
// PopupActionTableViewCell.swift
let actionColourCommon = WHITE
let actionColourDelete = WEBIM_RED
// ChatViewController.swift
/// Separator
let bottomBarSeparatorColour = TRANSLUCENT_GREY
/// Bottom bar
let bottomBarBackgroundViewColour = WHITE
let bottomBarQuoteLineViewColour = WEBIM_CYAN
let textInputBackgroundViewBorderColour = LIGHT_GREY.cgColor
/// Bottom bar for edit/reply
let textInputViewPlaceholderLabelTextColour = GREY
let textInputViewPlaceholderLabelBackgroundColour = CLEAR
let wmCoral = #colorLiteral(red: 0.7882352941, green: 0.3411764706, blue: 0.2196078431, alpha: 1)
// ChatTableViewController.swift
let refreshControlTextColour = WEBIM_DARK_PUPRLE
let refreshControlTintColour = WEBIM_DARK_PUPRLE
// ImageViewController.swift
// FileViewController.swift
let topBarTintColourDefault = WEBIM_DARK_PUPRLE
let topBarTintColourClear = CLEAR
let webimCyan = WEBIM_CYAN.cgColor
// PopupActionViewController.swift
let popupBackgroundColour = CLEAR
let actionsTableViewBackgroundColour = BLACK
let actionsTableViewCellBackgroundColour = CLEAR
// SettingsViewController.swift
let backgroundViewColour = WHITE
let saveButtonBackgroundColour = WEBIM_CYAN
let saveButtonTitleColour = WHITE
let saveButtonBorderColour = BLACK.cgColor
// SettingsTableViewController.swift
let tableViewBackgroundColour = WHITE
let labelTextColour = WEBIM_DARK_PUPRLE
let textFieldTextColour = WEBIM_DARK_PUPRLE
let textFieldTintColour = WEBIM_DARK_PUPRLE
let editViewBackgroundColourEditing = WEBIM_CYAN
let editViewBackgroundColourError = WEBIM_RED
let editViewBackgroundColourDefault = GREY
// StartViewController.swift
let startViewBackgroundColour = WEBIM_DARK_PUPRLE
let navigationBarBarTintColour = WEBIM_DARK_PUPRLE
let navigationBarNoConnectionColour = NO_CONNECTION_GREY
let navigationBarTintColour = WHITE
let welcomeLabelTextColour = WHITE
let welcomeTextViewTextColour = WHITE
let welcomeTextViewForegroundColour = WEBIM_CYAN
let startChatButtonBackgroundColour = WEBIM_CYAN
let startChatButtonBorderColour = WEBIM_CYAN.cgColor
let startChatTitleColour = WHITE
let settingsButtonTitleColour = WHITE
let settingButtonBorderColour = GREY.cgColor
// UITableView extension
let textMainColour = WEBIM_DARK_PUPRLE
// SurveyCommentViewController
let WMSurveyCommentPlaceholderColor = #colorLiteral(red: 0.6116228104, green: 0.6236780286, blue: 0.7096156478, alpha: 1)
// CircleProgressIndicator
let WMCircleProgressIndicatorLightGrey = LIGHT_GREY
let WMCircleProgressIndicatorCyan = WEBIM_CYAN
let wmGreyMessage = #colorLiteral(red: 0.6116228104, green: 0.6236780286, blue: 0.7096156478, alpha: 1).cgColor
let wmLayerColor = #colorLiteral(red: 0.1490196078, green: 0.1960784314, blue: 0.2196078431, alpha: 1).cgColor
let wmInfoCell = WEBIM_LIGHT_CYAN.cgColor
| mit | 3609a5372370d5b095b84decd7a99934 | 44.791411 | 122 | 0.810021 | 4.116933 | false | false | false | false |
ManueGE/Raccoon | raccoon/source/Client.swift | 1 | 6290 | //
// Client.swift
// raccoon
//
// Created by Manuel García-Estañ on 8/10/16.
// Copyright © 2016 manuege. All rights reserved.
//
import Foundation
import CoreData
import AlamofireCoreData
import PromiseKit
import Alamofire
/**
An object which encapsulate a promise that can be cancelled at any time.
*/
public struct Cancellable<T> {
/// The promise of the cancellable object
public let promise: Promise<T>
/// The method to call if the request must be cancelled
public let cancel: () -> Void
}
/**
Clients are instances that can send network requests. The requests are built using `Endpoints`.
The responses of this endpoints will be inserted in the given managed object context.
*/
public protocol Client {
// MARK: Required
/// The base url which will be used to build the reqeusts
var baseURL: String { get }
/// The managed object context where all the responses will be inserted.
var context: NSManagedObjectContext { get }
// MARK: Optionals
/**
The DataResponseSerializer<Any> which will transform the original response to the JSON which will be used to insert the responses.
By default it is `DataRequest.jsonResponseSerializer()`
*/
var jsonSerializer: DataResponseSerializer<Any> { get }
/**
Use this method to perform any last minute changes on the DataRequest to send.
Here you can add some validations, log the requests, or whatever thing you need.
By default, it returns the request itself, without any addition
- parameter request: The request that will be sent
- parameter endpoint: The endpoint which launched the reqeust
- returns: the modified request
*/
func prepare(_ request: DataRequest, for endpoint: Endpoint) -> DataRequest
/**
Use this method to perform any last minute changes on the Promise created when a request is sent.
Here you can add some common `recover` or `then` to all the promise
By default, it returns the promise itself, without any addition
- parameter request: The `Promise`
- parameter endpoint: The `Endpoint` that launched the request
- returns: the modified request
*/
func process<T>(_ promise: Promise<T>, for endpoint: Endpoint) -> Promise<T>
}
public extension Client {
// MARK: - Default methods
public var jsonSerializer: DataResponseSerializer<Any> {
return DataRequest.jsonResponseSerializer()
}
public func prepare(_ request: DataRequest, for endpoint: Endpoint) -> DataRequest {
return request
}
func process<T>(_ promise: Promise<T>, for endpoint: Endpoint) -> Promise<T> {
return promise
}
}
public extension Client {
/**
Enqueues the request generated by the endpoint and insert it using the generic type.
It returns a Cancellable to inform if the request has finished succesfully or not.
The request can be cancelled at any time by calling `cancel()` in the cancellable object.
- parameter endpoint: The endpoint
- returns: The Cancellable object
*/
public func cancellableEnqueue<T: Insertable>(_ endpoint: Endpoint) -> Cancellable<T> {
let request = endpoint.request(withBaseURL: baseURL)
let promise = Promise<T> { fulfill, reject in
prepare(request, for: endpoint)
.responseInsert(
queue: nil,
jsonSerializer: jsonSerializer,
context: context,
type: T.self) { response in
switch response.result {
case let .success(value):
fulfill(value)
case let .failure(error):
reject(error)
}
}
}
let finalPromise = process(promise, for: endpoint)
let cancel = request.cancel
return Cancellable(promise: finalPromise, cancel: cancel)
}
/**
Enqueues the request generated by the endpoint and insert it using the generic type.
It returns a Promise to inform if the request has finished succesfully or not
- parameter endpoint: The endpoint
- returns: The promise
*/
public func enqueue<T: Insertable>(_ endpoint: Endpoint) -> Promise<T> {
return cancellableEnqueue(endpoint).promise
}
/**
Enqueues the request generated by the endpoint.
It returns a Cancellable to inform if the request has finished succesfully or not
The request can be cancelled at any time by calling `cancel()` in the cancellable object.
- parameter endpoint: The endpoint
- returns: The cancellable object
*/
public func cancellableEnqueue(_ endpoint: Endpoint) -> Cancellable<Void> {
let request = endpoint.request(withBaseURL: baseURL)
let promise = Promise<Void> { fulfill, reject in
prepare(request, for: endpoint)
.responseInsert(
jsonSerializer: jsonSerializer,
context: context,
type: Empty.self) { response in
switch response.result {
case .success:
fulfill(())
case let .failure(error):
reject(error)
}
}
}
let finalPromise = process(promise, for: endpoint)
let cancel = request.cancel
return Cancellable(promise: finalPromise, cancel: cancel)
}
/**
Enqueues the request generated by the endpoint.
It returns an empty promise to inform if the request has finished succesfully or not
- parameter endpoint: The endpoint
- returns: The promise
*/
public func enqueue(_ endpoint: Endpoint) -> Promise<Void> {
return cancellableEnqueue(endpoint).promise
}
}
private struct Empty {}
extension Empty: Insertable {
public static func insert(from json: Any, in context: NSManagedObjectContext) throws -> Empty {
return Empty()
}
}
| mit | b594931e42b9a82e88c76cb52d1735e7 | 32.620321 | 135 | 0.62001 | 5.265494 | false | false | false | false |
adamgraham/STween | STween/STween/Easing/Ease.swift | 1 | 10458 | //
// Ease.swift
// STween
//
// Created by Adam Graham on 7/9/16.
// Copyright © 2016 Adam Graham. All rights reserved.
//
/**
A type of easing function, described from an algorithmic classification and acceleration
pattern, providing the sense of motion.
> "Nothing in nature moves linearly from one point to another. In reality, things tend to
> accelerate or decelerate as they move. Our brains are wired to expect this kind of
> motion, so when animating you should use this to your advantage. Natural motion
> makes your users feel more comfortable with your apps, which in turn leads to a better
> overall experience."
> \- [Paul Lewis](https://developers.google.com/web/fundamentals/design-and-ux/animations/the-basics-of-easing)
*/
public struct Ease {
// MARK: Properties
/// The algorithmic classification of the ease.
public let classification: EaseClassification
/// The acceleration pattern of the ease.
public let curve: EaseCurve
/// The timing function, f(x), of the ease.
public let function: (Double) -> Double
// MARK: Initialization
/// Initializes an ease with a classification, curve, and timing function.
/// - parameter classification: The algorithmic classification of the ease.
/// - parameter curve: The acceleration pattern of the ease.
/// - parameter function: The timing function, f(x), of the ease.
internal init(classification: EaseClassification, curve: EaseCurve, function: @escaping ((Double) -> Double)) {
self.classification = classification
self.curve = curve
self.function = function
}
}
/// :nodoc:
extension Ease: Equatable {
public static func ==(lhs: Ease, rhs: Ease) -> Bool {
return lhs.classification == rhs.classification &&
lhs.curve == rhs.curve &&
lhs.classification != .custom &&
lhs.curve != .custom
}
}
// MARK: -
extension Ease {
// MARK: Linear
/// An ease with a `linear` classification.
///
/// [Visual Reference](http://easings.net/)
public static let linear = Ease(classification: .linear, curve: .none, function: EaseFunction.linear)
// MARK: Sinusoidal
/// An ease with a `sine` classification and `in` acceleration pattern.
///
/// [Visual Reference](http://easings.net/#easeInSine)
public static let sineIn = Ease(classification: .sine, curve: .in, function: EaseFunction.sineIn)
/// An ease with a `sine` classification and `out` acceleration pattern.
///
/// [Visual Reference](http://easings.net/#easeOutSine)
public static let sineOut = Ease(classification: .sine, curve: .out, function: EaseFunction.sineOut)
/// An ease with a `sine` classification and `inOut` acceleration pattern.
///
/// [Visual Reference](http://easings.net/#easeInOutSine)
public static let sineInOut = Ease(classification: .sine, curve: .inOut, function: EaseFunction.sineInOut)
// MARK: Cubic
/// An ease with a `cubic` classification and `in` acceleration pattern.
///
/// [Visual Reference](http://easings.net/#easeInCubic)
public static let cubicIn = Ease(classification: .cubic, curve: .in, function: EaseFunction.cubicIn)
/// An ease with a `cubic` classification and `out` acceleration pattern.
///
/// [Visual Reference](http://easings.net/#easeOutCubic)
public static let cubicOut = Ease(classification: .cubic, curve: .out, function: EaseFunction.cubicOut)
/// An ease with a `cubic` classification and `inOut` acceleration pattern.
///
/// [Visual Reference](http://easings.net/#easeInOutCubic)
public static let cubicInOut = Ease(classification: .cubic, curve: .inOut, function: EaseFunction.cubicInOut)
// MARK: Quadratic
/// An ease with a `quad` classification and `in` acceleration pattern.
///
/// [Visual Reference](http://easings.net/#easeInQuad)
public static let quadIn = Ease(classification: .quad, curve: .in, function: EaseFunction.quadIn)
/// An ease with a `quad` classification and `out` acceleration pattern.
///
/// [Visual Reference](http://easings.net/#easeOutQuad)
public static let quadOut = Ease(classification: .quad, curve: .out, function: EaseFunction.quadOut)
/// An ease with a `quad` classification and `inOut` acceleration pattern.
///
/// [Visual Reference](http://easings.net/#easeInOutQuad)
public static let quadInOut = Ease(classification: .quad, curve: .inOut, function: EaseFunction.quadInOut)
// MARK: Quartic
/// An ease with a `quart` classification and `in` acceleration pattern.
///
/// [Visual Reference](http://easings.net/#easeInQuart)
public static let quartIn = Ease(classification: .quart, curve: .in, function: EaseFunction.quartIn)
/// An ease with a `quart` classification and `out` acceleration pattern.
///
/// [Visual Reference](http://easings.net/#easeOutQuart)
public static let quartOut = Ease(classification: .quart, curve: .out, function: EaseFunction.quartOut)
/// An ease with a `quart` classification and `inOut` acceleration pattern.
///
/// [Visual Reference](http://easings.net/#easeInOutQuart)
public static let quartInOut = Ease(classification: .quart, curve: .inOut, function: EaseFunction.quartInOut)
// MARK: Quintic
/// An ease with a `quint` classification and `in` acceleration pattern.
///
/// [Visual Reference](http://easings.net/#easeInQuint)
public static let quintIn = Ease(classification: .quint, curve: .in, function: EaseFunction.quintIn)
/// An ease with a `quint` classification and `out` acceleration pattern.
///
/// [Visual Reference](http://easings.net/#easeOutQuint)
public static let quintOut = Ease(classification: .quint, curve: .out, function: EaseFunction.quintOut)
/// An ease with a `quint` classification and `inOut` acceleration pattern.
///
/// [Visual Reference](http://easings.net/#easeInOutQuint)
public static let quintInOut = Ease(classification: .quint, curve: .inOut, function: EaseFunction.quintInOut)
// MARK: Exponential
/// An ease with an `expo` classification and `in` acceleration pattern.
///
/// [Visual Reference](http://easings.net/#easeInExpo)
public static let expoIn = Ease(classification: .expo, curve: .in, function: EaseFunction.expoIn)
/// An ease with an `expo` classification and `out` acceleration pattern.
///
/// [Visual Reference](http://easings.net/#easeOutExpo)
public static let expoOut = Ease(classification: .expo, curve: .out, function: EaseFunction.expoOut)
/// An ease with an `expo` classification and `inOut` acceleration pattern.
///
/// [Visual Reference](http://easings.net/#easeInOutExpo)
public static let expoInOut = Ease(classification: .expo, curve: .inOut, function: EaseFunction.expoOut)
// MARK: Circular
/// An ease with a `circ` classification and `in` acceleration pattern.
///
/// [Visual Reference](http://easings.net/#easeInCirc)
public static let circIn = Ease(classification: .circ, curve: .in, function: EaseFunction.circIn)
/// An ease with a `circ` classification and `out` acceleration pattern.
///
/// [Visual Reference](http://easings.net/#easeOutCirc)
public static let circOut = Ease(classification: .circ, curve: .out, function: EaseFunction.circOut)
/// An ease with a `circ` classification and `inOut` acceleration pattern.
///
/// [Visual Reference](http://easings.net/#easeInOutCirc)
public static let circInOut = Ease(classification: .circ, curve: .inOut, function: EaseFunction.circInOut)
// MARK: Back
/// An ease with a `back` classification and `in` acceleration pattern.
///
/// [Visual Reference](http://easings.net/#easeInBack)
public static let backIn = Ease(classification: .back, curve: .in, function: EaseFunction.backIn)
/// An ease with a `back` classification and `out` acceleration pattern.
///
/// [Visual Reference](http://easings.net/#easeOutBack)
public static let backOut = Ease(classification: .back, curve: .out, function: EaseFunction.backOut)
/// An ease with a `back` classification and `inOut` acceleration pattern.
///
/// [Visual Reference](http://easings.net/#easeInOutBack)
public static let backInOut = Ease(classification: .back, curve: .inOut, function: EaseFunction.backInOut)
// MARK: Elastic
/// An ease with an `elastic` classification and `in` acceleration pattern.
///
/// [Visual Reference](http://easings.net/#easeInElastic)
public static let elasticIn = Ease(classification: .elastic, curve: .in, function: EaseFunction.elasticIn)
/// An ease with an `elastic` classification and `out` acceleration pattern.
///
/// [Visual Reference](http://easings.net/#easeOutElastic)
public static let elasticOut = Ease(classification: .elastic, curve: .out, function: EaseFunction.elasticOut)
/// An ease with an `elastic` classification and `inOut` acceleration pattern.
///
/// [Visual Reference](http://easings.net/#easeInOutElastic)
public static let elasticInOut = Ease(classification: .elastic, curve: .inOut, function: EaseFunction.elasticInOut)
// MARK: Bounce
/// An ease with a `bounce` classification and `in` acceleration pattern.
///
/// [Visual Reference](http://easings.net/#easeInBounce)
public static let bounceIn = Ease(classification: .bounce, curve: .in, function: EaseFunction.bounceIn)
/// An ease with a `bounce` classification and `out` acceleration pattern.
///
/// [Visual Reference](http://easings.net/#easeOutBounce)
public static let bounceOut = Ease(classification: .bounce, curve: .out, function: EaseFunction.bounceOut)
/// An ease with a `bounce` classification and `inOut` acceleration pattern.
///
/// [Visual Reference](http://easings.net/#easeInOutBounce)
public static let bounceInOut = Ease(classification: .bounce, curve: .inOut, function: EaseFunction.bounceInOut)
// MARK: Custom
/// An ease with a custom timing function.
/// - parameter function: The custom timing function of the ease.
/// - returns: The custom ease.
public static func custom(function: @escaping (Double) -> Double) -> Ease {
return Ease(classification: .custom, curve: .custom, function: function)
}
}
| mit | 462d5783736566203af3131d4502f1ce | 41.336032 | 119 | 0.686621 | 4.292693 | false | false | false | false |
ioan-chera/DoomMakerSwift | DoomMakerSwift/ThingConfig.swift | 1 | 2490 | /*
DoomMaker
Copyright (C) 2017 Ioan Chera
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 AppKit
import Foundation
//
// Thing definition for editor's view
//
struct ThingType {
let category: String
let name: String
let id: Int
let radius: Int
let color: NSColor
static let unknown = ThingType(category: "Unknown", name: "Unknown", id: 0, radius: 20, color: NSColor.gray)
}
// Maps doomednums to thing definitions
var idThingMap: [Int: ThingType] = [:]
//
// Loads the id-thing map from a JSON config
//
func loadIdThingMap(jsonConfig: NSDictionary) {
idThingMap = [:] // always clear it
guard let categories = jsonConfig["thingCategories"] as? NSArray else {
return
}
for categoryObject in categories {
guard let category = categoryObject as? NSDictionary else {
continue
}
guard let things = category["things"] as? NSArray else {
continue
}
let categoryName = category["category"] as? String
let radius = category["radius"] as? Int
let colorString = category["color"] as? String
for thingObject in things {
guard let thing = thingObject as? NSDictionary else {
continue
}
guard let id = thing["id"] as? Int else {
continue
}
let thingRadius = thing["radius"] as? Int
let name = thing["name"] as? String
let thingColorString = thing["color"] as? String
idThingMap[id] = ThingType(category: categoryName ?? "Others",
name: name ?? "Unknown",
id: id,
radius: thingRadius ?? radius ?? 20,
color: NSColor(hex: thingColorString ?? colorString ?? "#808080"))
}
}
}
| gpl-3.0 | 93579773ae0c930b9cd79c431b65d943 | 33.109589 | 112 | 0.610442 | 4.662921 | false | false | false | false |
jejefcgb/ProjetS9-iOS | Projet S9/Session.swift | 1 | 873 | //
// Session.swift
// Projet S9
//
// Created by Jérémie Foucault on 30/11/2014.
// Copyright (c) 2014 Jérémie Foucault. All rights reserved.
//
import Foundation
/**
Data entity that represents a Session.
Subclasses NSObject to enable Obj-C instantiation.
*/
class Session : NSObject, Equatable
{
let
id: Int,
start_ts: Int,
end_ts: Int,
room_id: Int,
talks: [Talk]
init(
id: Int,
start_ts: Int,
end_ts: Int,
room_id: Int,
talks: [Talk])
{
self.id = id
self.start_ts = start_ts
self.end_ts = end_ts
self.room_id = room_id
self.talks = talks
}
}
// Required for Equatable protocol conformance
func == (lhs: Session, rhs: Session) -> Bool {
return lhs.id == rhs.id
} | apache-2.0 | 990db8977b01f95c3cbf315e35fefb62 | 19.232558 | 61 | 0.531646 | 3.448413 | false | false | false | false |
JGiola/swift-corelibs-foundation | Foundation/HTTPCookie.swift | 1 | 25050 | // 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
//
public struct HTTPCookiePropertyKey : RawRepresentable, Equatable, Hashable {
public private(set) var rawValue: String
public init(_ rawValue: String) {
self.rawValue = rawValue
}
public init(rawValue: String) {
self.rawValue = rawValue
}
public var hashValue: Int {
return self.rawValue.hashValue
}
public static func ==(_ lhs: HTTPCookiePropertyKey, _ rhs: HTTPCookiePropertyKey) -> Bool {
return lhs.rawValue == rhs.rawValue
}
}
extension HTTPCookiePropertyKey {
/// Key for cookie name
public static let name = HTTPCookiePropertyKey(rawValue: "Name")
/// Key for cookie value
public static let value = HTTPCookiePropertyKey(rawValue: "Value")
/// Key for cookie origin URL
public static let originURL = HTTPCookiePropertyKey(rawValue: "OriginURL")
/// Key for cookie version
public static let version = HTTPCookiePropertyKey(rawValue: "Version")
/// Key for cookie domain
public static let domain = HTTPCookiePropertyKey(rawValue: "Domain")
/// Key for cookie path
public static let path = HTTPCookiePropertyKey(rawValue: "Path")
/// Key for cookie secure flag
public static let secure = HTTPCookiePropertyKey(rawValue: "Secure")
/// Key for cookie expiration date
public static let expires = HTTPCookiePropertyKey(rawValue: "Expires")
/// Key for cookie comment text
public static let comment = HTTPCookiePropertyKey(rawValue: "Comment")
/// Key for cookie comment URL
public static let commentURL = HTTPCookiePropertyKey(rawValue: "CommentURL")
/// Key for cookie discard (session-only) flag
public static let discard = HTTPCookiePropertyKey(rawValue: "Discard")
/// Key for cookie maximum age (an alternate way of specifying the expiration)
public static let maximumAge = HTTPCookiePropertyKey(rawValue: "Max-Age")
/// Key for cookie ports
public static let port = HTTPCookiePropertyKey(rawValue: "Port")
// For Cocoa compatibility
internal static let created = HTTPCookiePropertyKey(rawValue: "Created")
}
/// `HTTPCookie` represents an http cookie.
///
/// An `HTTPCookie` instance represents a single http cookie. It is
/// an immutable object initialized from a dictionary that contains
/// the various cookie attributes. It has accessors to get the various
/// attributes of a cookie.
open class HTTPCookie : NSObject {
let _comment: String?
let _commentURL: URL?
let _domain: String
let _expiresDate: Date?
let _HTTPOnly: Bool
let _secure: Bool
let _sessionOnly: Bool
let _name: String
let _path: String
let _portList: [NSNumber]?
let _value: String
let _version: Int
var _properties: [HTTPCookiePropertyKey : Any]
// See: https://tools.ietf.org/html/rfc2616#section-3.3.1
// Sun, 06 Nov 1994 08:49:37 GMT ; RFC 822, updated by RFC 1123
static let _formatter1: DateFormatter = {
let formatter = DateFormatter()
formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.dateFormat = "EEE, dd MMM yyyy HH:mm:ss O"
formatter.timeZone = TimeZone(abbreviation: "GMT")
return formatter
}()
// Sun Nov 6 08:49:37 1994 ; ANSI C's asctime() format
static let _formatter2: DateFormatter = {
let formatter = DateFormatter()
formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.dateFormat = "EEE MMM d HH:mm:ss yyyy"
formatter.timeZone = TimeZone(abbreviation: "GMT")
return formatter
}()
// Sun, 06-Nov-1994 08:49:37 GMT ; Tomcat servers sometimes return cookies in this format
static let _formatter3: DateFormatter = {
let formatter = DateFormatter()
formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.dateFormat = "EEE, dd-MMM-yyyy HH:mm:ss O"
formatter.timeZone = TimeZone(abbreviation: "GMT")
return formatter
}()
static let _allFormatters: [DateFormatter]
= [_formatter1, _formatter2, _formatter3]
static let _attributes: [HTTPCookiePropertyKey]
= [.name, .value, .originURL, .version, .domain,
.path, .secure, .expires, .comment, .commentURL,
.discard, .maximumAge, .port]
/// Initialize a HTTPCookie object with a dictionary of parameters
///
/// - Parameter properties: The dictionary of properties to be used to
/// initialize this cookie.
///
/// Supported dictionary keys and value types for the
/// given dictionary are as follows.
///
/// All properties can handle an NSString value, but some can also
/// handle other types.
///
/// <table border=1 cellspacing=2 cellpadding=4>
/// <tr>
/// <th>Property key constant</th>
/// <th>Type of value</th>
/// <th>Required</th>
/// <th>Description</th>
/// </tr>
/// <tr>
/// <td>HTTPCookiePropertyKey.comment</td>
/// <td>NSString</td>
/// <td>NO</td>
/// <td>Comment for the cookie. Only valid for version 1 cookies and
/// later. Default is nil.</td>
/// </tr>
/// <tr>
/// <td>HTTPCookiePropertyKey.commentURL</td>
/// <td>NSURL or NSString</td>
/// <td>NO</td>
/// <td>Comment URL for the cookie. Only valid for version 1 cookies
/// and later. Default is nil.</td>
/// </tr>
/// <tr>
/// <td>HTTPCookiePropertyKey.domain</td>
/// <td>NSString</td>
/// <td>Special, a value for either .originURL or
/// HTTPCookiePropertyKey.domain must be specified.</td>
/// <td>Domain for the cookie. Inferred from the value for
/// HTTPCookiePropertyKey.originURL if not provided.</td>
/// </tr>
/// <tr>
/// <td>HTTPCookiePropertyKey.discard</td>
/// <td>NSString</td>
/// <td>NO</td>
/// <td>A string stating whether the cookie should be discarded at
/// the end of the session. String value must be either "TRUE" or
/// "FALSE". Default is "FALSE", unless this is cookie is version
/// 1 or greater and a value for HTTPCookiePropertyKey.maximumAge is not
/// specified, in which case it is assumed "TRUE".</td>
/// </tr>
/// <tr>
/// <td>HTTPCookiePropertyKey.expires</td>
/// <td>NSDate or NSString</td>
/// <td>NO</td>
/// <td>Expiration date for the cookie. Used only for version 0
/// cookies. Ignored for version 1 or greater.</td>
/// </tr>
/// <tr>
/// <td>HTTPCookiePropertyKey.maximumAge</td>
/// <td>NSString</td>
/// <td>NO</td>
/// <td>A string containing an integer value stating how long in
/// seconds the cookie should be kept, at most. Only valid for
/// version 1 cookies and later. Default is "0".</td>
/// </tr>
/// <tr>
/// <td>HTTPCookiePropertyKey.name</td>
/// <td>NSString</td>
/// <td>YES</td>
/// <td>Name of the cookie</td>
/// </tr>
/// <tr>
/// <td>HTTPCookiePropertyKey.originURL</td>
/// <td>NSURL or NSString</td>
/// <td>Special, a value for either HTTPCookiePropertyKey.originURL or
/// HTTPCookiePropertyKey.domain must be specified.</td>
/// <td>URL that set this cookie. Used as default for other fields
/// as noted.</td>
/// </tr>
/// <tr>
/// <td>HTTPCookiePropertyKey.path</td>
/// <td>NSString</td>
/// <td>YES</td>
/// <td>Path for the cookie</td>
/// </tr>
/// <tr>
/// <td>HTTPCookiePropertyKey.port</td>
/// <td>NSString</td>
/// <td>NO</td>
/// <td>comma-separated integer values specifying the ports for the
/// cookie. Only valid for version 1 cookies and later. Default is
/// empty string ("").</td>
/// </tr>
/// <tr>
/// <td>HTTPCookiePropertyKey.secure</td>
/// <td>NSString</td>
/// <td>NO</td>
/// <td>A string stating whether the cookie should be transmitted
/// only over secure channels. String value must be either "TRUE"
/// or "FALSE". Default is "FALSE".</td>
/// </tr>
/// <tr>
/// <td>HTTPCookiePropertyKey.value</td>
/// <td>NSString</td>
/// <td>YES</td>
/// <td>Value of the cookie</td>
/// </tr>
/// <tr>
/// <td>HTTPCookiePropertyKey.version</td>
/// <td>NSString</td>
/// <td>NO</td>
/// <td>Specifies the version of the cookie. Must be either "0" or
/// "1". Default is "0".</td>
/// </tr>
/// </table>
///
/// All other keys are ignored.
///
/// - Returns: An initialized `HTTPCookie`, or nil if the set of
/// dictionary keys is invalid, for example because a required key is
/// missing, or a recognized key maps to an illegal value.
///
/// - Experiment: This is a draft API currently under consideration for official import into Foundation as a suitable alternative
/// - Note: Since this API is under consideration it may be either removed or revised in the near future
public init?(properties: [HTTPCookiePropertyKey : Any]) {
guard
let path = properties[.path] as? String,
let name = properties[.name] as? String,
let value = properties[.value] as? String
else {
return nil
}
let canonicalDomain: String
if let domain = properties[.domain] as? String {
canonicalDomain = domain
} else if
let originURL = properties[.originURL] as? URL,
let host = originURL.host
{
canonicalDomain = host
} else {
return nil
}
_path = path
_name = name
_value = value
_domain = canonicalDomain.lowercased()
if let
secureString = properties[.secure] as? String, !secureString.isEmpty
{
_secure = true
} else {
_secure = false
}
let version: Int
if let
versionString = properties[.version] as? String, versionString == "1"
{
version = 1
} else {
version = 0
}
_version = version
if let portString = properties[.port] as? String {
let portList = portString.split(separator: ",")
.compactMap { Int(String($0)) }
.map { NSNumber(value: $0) }
if version == 1 {
_portList = portList
} else {
// Version 0 only stores a single port number
_portList = portList.count > 0 ? [portList[0]] : nil
}
} else {
_portList = nil
}
var expDate: Date? = nil
// Maximum-Age is prefered over expires-Date but only version 1 cookies use Maximum-Age
if let maximumAge = properties[.maximumAge] as? String,
let secondsFromNow = Int(maximumAge) {
if version == 1 {
expDate = Date(timeIntervalSinceNow: Double(secondsFromNow))
}
} else {
let expiresProperty = properties[.expires]
if let date = expiresProperty as? Date {
expDate = date
} else if let dateString = expiresProperty as? String {
let results = HTTPCookie._allFormatters.compactMap { $0.date(from: dateString) }
expDate = results.first
}
}
_expiresDate = expDate
if let discardString = properties[.discard] as? String {
_sessionOnly = discardString == "TRUE"
} else {
_sessionOnly = properties[.maximumAge] == nil && version >= 1
}
_comment = properties[.comment] as? String
if let commentURL = properties[.commentURL] as? URL {
_commentURL = commentURL
} else if let commentURL = properties[.commentURL] as? String {
_commentURL = URL(string: commentURL)
} else {
_commentURL = nil
}
_HTTPOnly = false
_properties = [
.created : Date().timeIntervalSinceReferenceDate, // Cocoa Compatibility
.discard : _sessionOnly,
.domain : _domain,
.name : _name,
.path : _path,
.secure : _secure,
.value : _value,
.version : _version
]
if let comment = properties[.comment] {
_properties[.comment] = comment
}
if let commentURL = properties[.commentURL] {
_properties[.commentURL] = commentURL
}
if let expires = properties[.expires] {
_properties[.expires] = expires
}
if let maximumAge = properties[.maximumAge] {
_properties[.maximumAge] = maximumAge
}
if let originURL = properties[.originURL] {
_properties[.originURL] = originURL
}
if let _portList = _portList {
_properties[.port] = _portList
}
}
/// Return a dictionary of header fields that can be used to add the
/// specified cookies to the request.
///
/// - Parameter cookies: The cookies to turn into request headers.
/// - Returns: A dictionary where the keys are header field names, and the values
/// are the corresponding header field values.
open class func requestHeaderFields(with cookies: [HTTPCookie]) -> [String : String] {
var cookieString = cookies.reduce("") { (sum, next) -> String in
return sum + "\(next._name)=\(next._value); "
}
//Remove the final trailing semicolon and whitespace
if ( cookieString.length > 0 ) {
cookieString.removeLast()
cookieString.removeLast()
}
if cookieString == "" {
return [:]
} else {
return ["Cookie": cookieString]
}
}
/// Return an array of cookies parsed from the specified response header fields and URL.
///
/// This method will ignore irrelevant header fields so
/// you can pass a dictionary containing data other than cookie data.
/// - Parameter headerFields: The response header fields to check for cookies.
/// - Parameter URL: The URL that the cookies came from - relevant to how the cookies are interpeted.
/// - Returns: An array of HTTPCookie objects
open class func cookies(withResponseHeaderFields headerFields: [String : String], for URL: URL) -> [HTTPCookie] {
//HTTP Cookie parsing based on RFC 6265: https://tools.ietf.org/html/rfc6265
//Though RFC6265 suggests that multiple cookies cannot be folded into a single Set-Cookie field, this is
//pretty common. It also suggests that commas and semicolons among other characters, cannot be a part of
// names and values. This implementation takes care of multiple cookies in the same field, however it doesn't
//support commas and semicolons in names and values(except for dates)
guard let cookies: String = headerFields["Set-Cookie"] else { return [] }
let nameValuePairs = cookies.components(separatedBy: ";") //split the name/value and attribute/value pairs
.map({$0.trim()}) //trim whitespaces
.map({removeCommaFromDate($0)}) //get rid of commas in dates
.flatMap({$0.components(separatedBy: ",")}) //cookie boundaries are marked by commas
.map({$0.trim()}) //trim again
.filter({$0.caseInsensitiveCompare("HTTPOnly") != .orderedSame}) //we don't use HTTPOnly, do we?
.flatMap({createNameValuePair(pair: $0)}) //create Name and Value properties
//mark cookie boundaries in the name-value array
var cookieIndices = (0..<nameValuePairs.count).filter({nameValuePairs[$0].hasPrefix("Name")})
cookieIndices.append(nameValuePairs.count)
//bake the cookies
var httpCookies: [HTTPCookie] = []
for i in 0..<cookieIndices.count-1 {
if let aCookie = createHttpCookie(url: URL, pairs: nameValuePairs[cookieIndices[i]..<cookieIndices[i+1]]) {
httpCookies.append(aCookie)
}
}
return httpCookies
}
//Bake a cookie
private class func createHttpCookie(url: URL, pairs: ArraySlice<String>) -> HTTPCookie? {
var properties: [HTTPCookiePropertyKey : Any] = [:]
for pair in pairs {
let name = pair.components(separatedBy: "=")[0]
var value = pair.components(separatedBy: "\(name)=")[1] //a value can have an "="
if canonicalize(name) == .expires {
value = value.unmaskCommas() //re-insert the comma
}
properties[canonicalize(name)] = value
}
// If domain wasn't provided, extract it from the URL
if properties[.domain] == nil {
properties[.domain] = url.host
}
//the default Path is "/"
if properties[.path] == nil {
properties[.path] = "/"
}
return HTTPCookie(properties: properties)
}
//we pass this to a map()
private class func removeCommaFromDate(_ value: String) -> String {
if value.hasPrefix("Expires") || value.hasPrefix("expires") {
return value.maskCommas()
}
return value
}
//These cookie attributes are defined in RFC 6265 and 2965(which is obsolete)
//HTTPCookie supports these
private class func isCookieAttribute(_ string: String) -> Bool {
return _attributes.first(where: {$0.rawValue.caseInsensitiveCompare(string) == .orderedSame}) != nil
}
//Cookie attribute names are case-insensitive as per RFC6265: https://tools.ietf.org/html/rfc6265
//but HTTPCookie needs only the first letter of each attribute in uppercase
private class func canonicalize(_ name: String) -> HTTPCookiePropertyKey {
let idx = _attributes.index(where: {$0.rawValue.caseInsensitiveCompare(name) == .orderedSame})!
return _attributes[idx]
}
//A name=value pair should be translated to two properties, Name=name and Value=value
private class func createNameValuePair(pair: String) -> [String] {
if pair.caseInsensitiveCompare(HTTPCookiePropertyKey.secure.rawValue) == .orderedSame {
return ["Secure=TRUE"]
}
let name = pair.components(separatedBy: "=")[0]
let value = pair.components(separatedBy: "\(name)=")[1]
if !isCookieAttribute(name) {
return ["Name=\(name)", "Value=\(value)"]
}
return [pair]
}
/// Returns a dictionary representation of the receiver.
///
/// This method returns a dictionary representation of the
/// `HTTPCookie` which can be saved and passed to
/// `init(properties:)` later to reconstitute an equivalent cookie.
///
/// See the `HTTPCookie` `init(properties:)` method for
/// more information on the constraints imposed on the dictionary, and
/// for descriptions of the supported keys and values.
///
/// - Experiment: This is a draft API currently under consideration for official import into Foundation as a suitable alternative
/// - Note: Since this API is under consideration it may be either removed or revised in the near future
open var properties: [HTTPCookiePropertyKey : Any]? {
return _properties
}
/// The version of the receiver.
///
/// Version 0 maps to "old-style" Netscape cookies.
/// Version 1 maps to RFC2965 cookies. There may be future versions.
open var version: Int {
return _version
}
/// The name of the receiver.
open var name: String {
return _name
}
/// The value of the receiver.
open var value: String {
return _value
}
/// Returns The expires date of the receiver.
///
/// The expires date is the date when the cookie should be
/// deleted. The result will be nil if there is no specific expires
/// date. This will be the case only for *session-only* cookies.
/*@NSCopying*/ open var expiresDate: Date? {
return _expiresDate
}
/// Whether the receiver is session-only.
///
/// `true` if this receiver should be discarded at the end of the
/// session (regardless of expiration date), `false` if receiver need not
/// be discarded at the end of the session.
open var isSessionOnly: Bool {
return _sessionOnly
}
/// The domain of the receiver.
///
/// This value specifies URL domain to which the cookie
/// should be sent. A domain with a leading dot means the cookie
/// should be sent to subdomains as well, assuming certain other
/// restrictions are valid. See RFC 2965 for more detail.
open var domain: String {
return _domain
}
/// The path of the receiver.
///
/// This value specifies the URL path under the cookie's
/// domain for which this cookie should be sent. The cookie will also
/// be sent for children of that path, so `"/"` is the most general.
open var path: String {
return _path
}
/// Whether the receiver should be sent only over secure channels
///
/// Cookies may be marked secure by a server (or by a javascript).
/// Cookies marked as such must only be sent via an encrypted connection to
/// trusted servers (i.e. via SSL or TLS), and should not be delievered to any
/// javascript applications to prevent cross-site scripting vulnerabilities.
open var isSecure: Bool {
return _secure
}
/// Whether the receiver should only be sent to HTTP servers per RFC 2965
///
/// Cookies may be marked as HTTPOnly by a server (or by a javascript).
/// Cookies marked as such must only be sent via HTTP Headers in HTTP Requests
/// for URL's that match both the path and domain of the respective Cookies.
/// Specifically these cookies should not be delivered to any javascript
/// applications to prevent cross-site scripting vulnerabilities.
open var isHTTPOnly: Bool {
return _HTTPOnly
}
/// The comment of the receiver.
///
/// This value specifies a string which is suitable for
/// presentation to the user explaining the contents and purpose of this
/// cookie. It may be nil.
open var comment: String? {
return _comment
}
/// The comment URL of the receiver.
///
/// This value specifies a URL which is suitable for
/// presentation to the user as a link for further information about
/// this cookie. It may be nil.
/*@NSCopying*/ open var commentURL: URL? {
return _commentURL
}
/// The list ports to which the receiver should be sent.
///
/// This value specifies an NSArray of NSNumbers
/// (containing integers) which specify the only ports to which this
/// cookie should be sent.
///
/// The array may be nil, in which case this cookie can be sent to any
/// port.
open var portList: [NSNumber]? {
return _portList
}
open override var description: String {
var str = "<\(type(of: self)) "
str += "version:\(self._version) name:\"\(self._name)\" value:\"\(self._value)\" expiresDate:"
if let expires = self._expiresDate {
str += "\(expires)"
} else {
str += "nil"
}
str += " sessionOnly:\(self._sessionOnly) domain:\"\(self._domain)\" path:\"\(self._path)\" isSecure:\(self._secure) comment:"
if let comments = self._comment {
str += "\(comments)"
} else {
str += "nil"
}
str += " ports:{ "
if let ports = self._portList {
str += "\(NSArray(array: (ports)).componentsJoined(by: ","))"
} else {
str += "0"
}
str += " }>"
return str
}
}
//utils for cookie parsing
fileprivate extension String {
func trim() -> String {
return self.trimmingCharacters(in: .whitespacesAndNewlines)
}
func maskCommas() -> String {
return self.replacingOccurrences(of: ",", with: "&comma")
}
func unmaskCommas() -> String {
return self.replacingOccurrences(of: "&comma", with: ",")
}
}
| apache-2.0 | e5cee7148a6b2577cdd26dec2bceec78 | 36.839879 | 134 | 0.598004 | 4.570334 | false | false | false | false |
yichizhang/YZBasicCells | BasicCells-Demo/BasicCells-Demo/AppDelegate.swift | 1 | 4072 | /*
Copyright (c) 2015 Yichi Zhang
https://github.com/yichizhang
[email protected]
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
if window == nil {
window = UIWindow(frame: UIScreen.mainScreen().bounds)
}
let tabVC = UITabBarController()
let vc1 = DemoCollectionViewController()
vc1.tabBarItem = UITabBarItem(title: "Demo A", image: DemoStyleKit.imageOf(string: "A"), tag: 0)
let vc2 = DemoCollectionViewController()
vc2.mode = 1
vc2.tabBarItem = UITabBarItem(title: "Demo B", image: DemoStyleKit.imageOf(string: "B"), tag: 0)
let vc3 = CrazyHorizontalCellViewController()
vc3.tabBarItem = UITabBarItem(title: "Demo C", image: DemoStyleKit.imageOf(string: "C"), tag: 0)
let vc4 = CrazyDemoViewController()
vc4.tabBarItem = UITabBarItem(title: "Demo D", image: DemoStyleKit.imageOf(string: "D"), tag: 0)
tabVC.viewControllers = [
UINavigationController(rootViewController: vc1),
UINavigationController(rootViewController: vc2),
UINavigationController(rootViewController: vc3),
UINavigationController(rootViewController: vc4)
]
window?.rootViewController = tabVC
window?.makeKeyAndVisible()
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| mit | 60aba810c046de2e3996e5b38300022e | 49.271605 | 461 | 0.777505 | 4.779343 | false | false | false | false |
flypaper0/ethereum-wallet | ethereum-wallet/Classes/BusinessLayer/Services/BalanceUpdater/BalanceIndexerService.swift | 1 | 2296 | // Copyright © 2018 Conicoin LLC. All rights reserved.
// Created by Artur Guseinov
import Foundation
protocol BalanceIndexer {
var viewModel: BalanceViewModel! { get }
func start(id: Identifier, callback: @escaping (BalanceViewModel) -> Void)
func removeObserver(id: Identifier)
}
class BalanceIndexerService: BalanceIndexer {
let id = Identifier()
var viewModel: BalanceViewModel!
let channel: Channel<BalanceViewModel>
let rateSource: RateSource
let transactionRepository: TransactionRepository
let rateRepository: RateRepositoryService
init(channel: Channel<BalanceViewModel>,
rateSource: RateSource,
transactionRepository: TransactionRepository,
rateRepository: RateRepositoryService) {
self.channel = channel
self.rateSource = rateSource
self.transactionRepository = transactionRepository
self.rateRepository = rateRepository
transactionRepository.addObserver(id: id, fire: true) { _ in
let viewModel = self.calculate()
self.viewModel = viewModel
channel.send(viewModel)
}
}
// MARK: BalanceIndexer
func start(id: Identifier, callback: @escaping (BalanceViewModel) -> Void) {
callback(viewModel)
let observer = Observer<BalanceViewModel>(id: id, callback: callback)
channel.addObserver(observer)
rateRepository.addObserver(id: id, fire: false) { _ in
// Just ask to update ui
callback(self.viewModel)
}
}
func removeObserver(id: Identifier) {
transactionRepository.removeObserver(id: id)
}
// MARK: Privates
private func calculate() -> BalanceViewModel {
var amount: Decimal = 0
let transactions = transactionRepository.transactions
for tx in transactions {
if !tx.isIncoming && tx.isNormal {
amount -= (tx.gasUsed * tx.gasPrice)
}
guard !tx.isTokenTransfer && tx.error == nil else {
continue
}
// TODO: Token transfers with amount
// TODO: Contract creation transfer
if tx.isIncoming {
amount += tx.amount.raw
} else {
amount -= tx.amount.raw
}
}
amount = max(amount, 0)
let ether = Ether(weiValue: amount)
return BalanceViewModel(currency: ether, rateSource: rateSource)
}
}
| gpl-3.0 | 2cf944dc047a0dcba498e9abf6e2215a | 25.686047 | 78 | 0.677996 | 4.731959 | false | false | false | false |
tkremenek/swift | test/Concurrency/Runtime/actor_counters.swift | 1 | 2535 | // RUN: %target-run-simple-swift(-Xfrontend -enable-experimental-concurrency -Xfrontend -disable-availability-checking %import-libdispatch -parse-as-library)
// REQUIRES: executable_test
// REQUIRES: concurrency
// REQUIRES: libdispatch
// rdar://76038845
// UNSUPPORTED: use_os_stdlib
// UNSUPPORTED: back_deployment_runtime
@available(SwiftStdlib 5.5, *)
actor Counter {
private var value = 0
private let scratchBuffer: UnsafeMutableBufferPointer<Int>
init(maxCount: Int) {
scratchBuffer = .allocate(capacity: maxCount)
scratchBuffer.initialize(repeating: 0)
}
func next() -> Int {
let current = value
// Make sure we haven't produced this value before
assert(scratchBuffer[current] == 0)
scratchBuffer[current] = 1
value = value + 1
return current
}
deinit {
for i in 0..<value {
assert(scratchBuffer[i] == 1)
}
}
}
@available(SwiftStdlib 5.5, *)
func worker(identity: Int, counters: [Counter], numIterations: Int) async {
for i in 0..<numIterations {
let counterIndex = Int.random(in: 0 ..< counters.count)
let counter = counters[counterIndex]
let nextValue = await counter.next()
print("Worker \(identity) calling counter \(counterIndex) produced \(nextValue)")
}
}
@available(SwiftStdlib 5.5, *)
func runTest(numCounters: Int, numWorkers: Int, numIterations: Int) async {
// Create counter actors.
var counters: [Counter] = []
for i in 0..<numCounters {
counters.append(Counter(maxCount: numWorkers * numIterations))
}
// Create a bunch of worker threads.
var workers: [Task.Handle<Void, Error>] = []
for i in 0..<numWorkers {
workers.append(
detach { [counters] in
await Task.sleep(UInt64.random(in: 0..<100) * 1_000_000)
await worker(identity: i, counters: counters, numIterations: numIterations)
}
)
}
// Wait until all of the workers have finished.
for worker in workers {
try! await worker.get()
}
print("DONE!")
}
@available(SwiftStdlib 5.5, *)
@main struct Main {
static func main() async {
// Useful for debugging: specify counter/worker/iteration counts
let args = CommandLine.arguments
let counters = args.count >= 2 ? Int(args[1])! : 10
let workers = args.count >= 3 ? Int(args[2])! : 100
let iterations = args.count >= 4 ? Int(args[3])! : 1000
print("counters: \(counters), workers: \(workers), iterations: \(iterations)")
await runTest(numCounters: counters, numWorkers: workers, numIterations: iterations)
}
}
| apache-2.0 | 26d9db20b71f65a3d6c3cb68f2e665bc | 27.806818 | 157 | 0.672584 | 3.876147 | false | false | false | false |
aschwaighofer/swift | test/Driver/Dependencies/fail-simple-fine.swift | 2 | 1683 | /// bad ==> main | bad --> other
// RUN: %empty-directory(%t)
// RUN: cp -r %S/Inputs/fail-simple-fine/* %t
// RUN: touch -t 201401240005 %t/*
// RUN: cd %t && %swiftc_driver -c -driver-use-frontend-path "%{python};%S/Inputs/update-dependencies.py" -output-file-map %t/output.json -incremental -driver-always-rebuild-dependents ./main.swift ./bad.swift ./other.swift -module-name main -j1 -v 2>&1 | %FileCheck -check-prefix=CHECK-FIRST %s
// CHECK-FIRST-NOT: warning
// CHECK-FIRST: Handled main.swift
// CHECK-FIRST: Handled bad.swift
// CHECK-FIRST: Handled other.swift
// RUN: touch -t 201401240006 %t/bad.swift
// RUN: cd %t && not %swiftc_driver -c -driver-use-frontend-path "%{python};%S/Inputs/update-dependencies-bad.py" -output-file-map %t/output.json -incremental -driver-always-rebuild-dependents ./bad.swift ./main.swift ./other.swift -module-name main -j1 -v 2>&1 | %FileCheck -check-prefix=CHECK-SECOND %s
// RUN: %FileCheck -check-prefix=CHECK-RECORD %s < %t/main~buildrecord.swiftdeps
// CHECK-SECOND: Handled bad.swift
// CHECK-SECOND-NOT: Handled main.swift
// CHECK-SECOND-NOT: Handled other.swift
// CHECK-RECORD-DAG: "./bad.swift": !private [
// CHECK-RECORD-DAG: "./main.swift": !private [
// CHECK-RECORD-DAG: "./other.swift": !private [
// RUN: cd %t && %swiftc_driver -c -driver-use-frontend-path "%{python};%S/Inputs/update-dependencies.py" -output-file-map %t/output.json -incremental -driver-always-rebuild-dependents ./bad.swift ./main.swift ./other.swift -module-name main -j1 -v 2>&1 | %FileCheck -check-prefix=CHECK-THIRD %s
// CHECK-THIRD-DAG: Handled main.swift
// CHECK-THIRD-DAG: Handled bad.swift
// CHECK-THIRD-DAG: Handled other.swift
| apache-2.0 | b223f665ea4fcbf17254eacf489f6933 | 55.1 | 304 | 0.703506 | 3.09375 | false | false | false | false |
Allow2CEO/browser-ios | brave/src/page-hooks/BraveContextMenu.swift | 1 | 6371 | /* This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. */
// Using suggestions from: http://www.icab.de/blog/2010/07/11/customize-the-contextual-menu-of-uiwebview/
let kNotificationMainWindowTapAndHold = "kNotificationMainWindowTapAndHold"
class BraveContextMenu {
fileprivate var tapLocation = CGPoint.zero
fileprivate var tappedElement: ContextMenuHelper.Elements?
fileprivate var timer1_cancelDefaultMenu = Timer()
fileprivate var timer2_showMenuIfStillPressed = Timer()
static let initialDelayToCancelBuiltinMenu = 0.25 // seconds, must be <0.3 or built-in menu can't be cancelled
static let totalDelayToShowContextMenu = 0.35 - initialDelayToCancelBuiltinMenu
fileprivate let fingerMovedTolerance = Float(5.0)
fileprivate func reset() {
timer1_cancelDefaultMenu.invalidate()
timer2_showMenuIfStillPressed.invalidate()
tappedElement = nil
tapLocation = CGPoint.zero
}
fileprivate func isActive() -> Bool {
return tapLocation != CGPoint.zero && (timer1_cancelDefaultMenu.isValid || timer2_showMenuIfStillPressed.isValid)
}
fileprivate func isBrowserTopmostAndNoPanelsOpen() -> Bool {
guard let top = getApp().rootViewController.visibleViewController as? BraveTopViewController else {
return false
}
return top.mainSidePanel.view.isHidden && top.rightSidePanel.view.isHidden
}
fileprivate func fingerMovedTooFar(_ touch: UITouch, window: UIView) -> Bool {
let p1 = touch.location(in: window)
let p2 = tapLocation
let distance = hypotf(Float(p1.x) - Float(p2.x), Float(p1.y) - Float(p2.y))
return distance > fingerMovedTolerance
}
func sendEvent(_ event: UIEvent, window: UIWindow) {
if !isBrowserTopmostAndNoPanelsOpen() {
reset()
return
}
guard let braveWebView = BraveApp.getCurrentWebView() else { return }
if let touches = event.touches(for: window), let touch = touches.first, touches.count == 1 {
braveWebView.lastTappedTime = Date()
switch touch.phase {
case .began: // A finger touched the screen
reset()
guard let touchView = event.allTouches?.first?.view, touchView.isDescendant(of: braveWebView) else {
return
}
tapLocation = touch.location(in: window)
timer1_cancelDefaultMenu = Timer.scheduledTimer(timeInterval: BraveContextMenu.initialDelayToCancelBuiltinMenu, target: self, selector: #selector(BraveContextMenu.cancelDefaultMenuAndFindTappedItem), userInfo: nil, repeats: false)
case .moved, .stationary:
if isActive() && fingerMovedTooFar(touch, window: window) {
// my test for this: tap with edge of finger, then roll to opposite edge while holding finger down, is 5-10 px of movement; Should still show context menu, don't want this to trigger a reset()
reset()
}
case .ended, .cancelled:
if isActive() {
if let url = tappedElement?.link, !fingerMovedTooFar(touch, window: window) {
BraveApp.getCurrentWebView()?.loadRequest(URLRequest(url: url as URL))
}
reset()
}
}
} else {
reset()
}
}
@objc func showContextMenu() {
func showContextMenuForElement(_ tappedElement: ContextMenuHelper.Elements) {
let info = ["point": NSValue(cgPoint: tapLocation)]
NotificationCenter.default.post(name: Notification.Name(rawValue: kNotificationMainWindowTapAndHold), object: self, userInfo: info)
guard let bvc = getApp().browserViewController else { return }
if bvc.urlBar.inSearchMode {
return
}
bvc.showContextMenu(tappedElement, touchPoint: tapLocation)
reset()
}
if let tappedElement = tappedElement {
showContextMenuForElement(tappedElement)
}
}
// This is called 2x, once at .25 seconds to ensure the native context menu is cancelled,
// then again at .5 seconds to show our context menu. (This code was borne of frustration, not ideal flow)
@objc func cancelDefaultMenuAndFindTappedItem() {
if !isBrowserTopmostAndNoPanelsOpen() {
reset()
return
}
guard let webView = BraveApp.getCurrentWebView() else { return }
let hit: (url: String?, image: String?, urlTarget: String?)?
if [".jpg", ".png", ".gif"].filter({ webView.URL?.absoluteString.endsWith($0) ?? false }).count > 0 {
// web view is just showing an image
hit = (url:nil, image:webView.URL!.absoluteString, urlTarget:nil)
} else {
hit = ElementAtPoint().getHit(tapLocation)
}
if hit == nil {
// No link or image found, not for this class to handle
reset()
return
}
tappedElement = ContextMenuHelper.Elements(link: hit!.url != nil ? URL(string: hit!.url!) : nil, image: hit!.image != nil ? URL(string: hit!.image!) : nil, folder: nil)
func blockOtherGestures(_ views: [UIView]?) {
guard let views = views else { return }
for view in views {
if let gestures = view.gestureRecognizers as [UIGestureRecognizer]! {
for gesture in gestures {
if gesture is UILongPressGestureRecognizer {
// toggling gets the gesture to ignore this long press
gesture.isEnabled = false
gesture.isEnabled = true
}
}
}
}
}
blockOtherGestures(BraveApp.getCurrentWebView()?.scrollView.subviews)
timer2_showMenuIfStillPressed = Timer.scheduledTimer(timeInterval: BraveContextMenu.totalDelayToShowContextMenu, target: self, selector: #selector(BraveContextMenu.showContextMenu), userInfo: nil, repeats: false)
}
}
| mpl-2.0 | 095e821dddd44759204f01ece6b7fbd6 | 42.636986 | 246 | 0.619055 | 5.028414 | false | false | false | false |
bignerdranch/DeferredTCPSocket | DeferredTCPSocket/DeferredTCPSocket/WriteOperations.swift | 1 | 2713 | //
// WriteOperations.swift
// DeferredIO
//
// Created by John Gallagher on 9/12/14.
// Copyright (c) 2014 Big Nerd Ranch. All rights reserved.
//
import Foundation
#if os(iOS)
import Deferred
import Result
#else
import DeferredMac
import ResultMac
#endif
public enum WriteError: ErrorType {
case Cancelled
case Timeout
case WriteFailedWithErrno(Int32)
public var description: String {
switch (self) {
case Cancelled: return "WriteError.Cancelled"
case Timeout: return "WriteError.Timeout"
case WriteFailedWithErrno(let errno): return "WriteError.ReadFailedWithErrno(\(errno))"
}
}
}
public typealias WriteResult = Result<Void>
class DeferredWriteOperation: DeferredIOOperation {
let deferred = Deferred<WriteResult>()
let data: NSData
var written = 0
override var finished: Bool { return deferred.isFilled }
init(data: NSData, queue: dispatch_queue_t, source: dispatch_source_t, timerSource: dispatch_source_t, timeout: NSTimeInterval? = nil) {
self.data = data
super.init(queue: queue, source: source, timerSource: timerSource, timeout: timeout)
}
deinit {
// NSLog("DEINIT \(self)")
}
func complete(result: WriteResult) {
if executing {
suspendSources()
executing = false
}
self.willChangeValueForKeyFinished()
deferred.fill(result)
self.didChangeValueForKeyFinished()
}
override func cancel() {
super.cancel()
dispatch_async(queue) { [weak self] in
if let s = self {
if s.executing {
s.complete(Result(failure: WriteError.Cancelled))
}
}
}
}
override func handleTimeout() {
complete(Result(failure: WriteError.Timeout))
}
override func start() {
dispatch_sync(queue) {
self.realStart()
}
}
private func realStart() {
if self.cancelled {
complete(Result(failure: WriteError.Cancelled))
return
}
if !finished {
executing = true
resumeSources()
}
}
override func handleEvent() {
let fd = Int32(dispatch_source_get_handle(source))
let remaining = data.length - written
let actualWritten = write(fd, advance(data.bytes, written), UInt(remaining))
if actualWritten > 0 {
written += actualWritten
if written == data.length {
complete(Result(success: ()))
}
} else {
complete(Result(failure: WriteError.WriteFailedWithErrno(errno)))
}
}
} | mit | 4c094899658d5e8e04e569b3b7e4a39b | 23.672727 | 140 | 0.598231 | 4.536789 | false | false | false | false |
xivol/MCS-V3-Mobile | examples/uiKit/UIKitCatalog.playground/Sources/String+Image.swift | 1 | 746 | import UIKit
import Foundation
//http://stackoverflow.com/questions/38809425/convert-apple-emoji-string-to-uiimage
public extension String {
public var image: UIImage {
let size = CGSize(width: 30, height: 35)
UIGraphicsBeginImageContextWithOptions(size, false, 0)
let rect = CGRect(origin: CGPoint.zero, size: size)
UIColor.clear.setFill()
UIRectFill(rect)
let nsString = self as NSString
let font = UIFont.systemFont(ofSize: size.width)
nsString.draw(in: rect, withAttributes: [NSAttributedStringKey.font: font])
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image!
}
}
| mit | f7b37bfc6d49ec00f4e06b9b1bceac6f | 31.434783 | 83 | 0.662198 | 4.907895 | false | false | false | false |
httpswift/swifter | Xcode/Sources/String+SHA1.swift | 1 | 4413 | //
// String+SHA1.swift
// Swifter
//
// Copyright 2014-2016 Damian Kołakowski. All rights reserved.
//
import Foundation
// swiftlint:disable identifier_name function_body_length
public struct SHA1 {
public static func hash(_ input: [UInt8]) -> [UInt8] {
// Alghorithm from: https://en.wikipedia.org/wiki/SHA-1
var message = input
var h0 = UInt32(littleEndian: 0x67452301)
var h1 = UInt32(littleEndian: 0xEFCDAB89)
var h2 = UInt32(littleEndian: 0x98BADCFE)
var h3 = UInt32(littleEndian: 0x10325476)
var h4 = UInt32(littleEndian: 0xC3D2E1F0)
// ml = message length in bits (always a multiple of the number of bits in a character).
let ml = UInt64(message.count * 8)
// append the bit '1' to the message e.g. by adding 0x80 if message length is a multiple of 8 bits.
message.append(0x80)
// append 0 ≤ k < 512 bits '0', such that the resulting message length in bits is congruent to −64 ≡ 448 (mod 512)
let padBytesCount = ( message.count + 8 ) % 64
message.append(contentsOf: [UInt8](repeating: 0, count: 64 - padBytesCount))
// append ml, in a 64-bit big-endian integer. Thus, the total length is a multiple of 512 bits.
var mlBigEndian = ml.bigEndian
withUnsafePointer(to: &mlBigEndian) {
message.append(contentsOf: Array(UnsafeBufferPointer<UInt8>(start: UnsafePointer(OpaquePointer($0)), count: 8)))
}
// Process the message in successive 512-bit chunks ( 64 bytes chunks ):
for chunkStart in 0..<message.count/64 {
var words = [UInt32]()
let chunk = message[chunkStart*64..<chunkStart*64+64]
// break chunk into sixteen 32-bit big-endian words w[i], 0 ≤ i ≤ 15
for index in 0...15 {
let value = chunk.withUnsafeBufferPointer({ UnsafePointer<UInt32>(OpaquePointer($0.baseAddress! + (index*4))).pointee})
words.append(value.bigEndian)
}
// Extend the sixteen 32-bit words into eighty 32-bit words:
for index in 16...79 {
let value: UInt32 = ((words[index-3]) ^ (words[index-8]) ^ (words[index-14]) ^ (words[index-16]))
words.append(rotateLeft(value, 1))
}
// Initialize hash value for this chunk:
var a = h0
var b = h1
var c = h2
var d = h3
var e = h4
for i in 0..<80 {
var f = UInt32(0)
var k = UInt32(0)
switch i {
case 0...19:
f = (b & c) | ((~b) & d)
k = 0x5A827999
case 20...39:
f = b ^ c ^ d
k = 0x6ED9EBA1
case 40...59:
f = (b & c) | (b & d) | (c & d)
k = 0x8F1BBCDC
case 60...79:
f = b ^ c ^ d
k = 0xCA62C1D6
default: break
}
let temp = (rotateLeft(a, 5) &+ f &+ e &+ k &+ words[i]) & 0xFFFFFFFF
e = d
d = c
c = rotateLeft(b, 30)
b = a
a = temp
}
// Add this chunk's hash to result so far:
h0 = ( h0 &+ a ) & 0xFFFFFFFF
h1 = ( h1 &+ b ) & 0xFFFFFFFF
h2 = ( h2 &+ c ) & 0xFFFFFFFF
h3 = ( h3 &+ d ) & 0xFFFFFFFF
h4 = ( h4 &+ e ) & 0xFFFFFFFF
}
// Produce the final hash value (big-endian) as a 160 bit number:
var digest = [UInt8]()
[h0, h1, h2, h3, h4].forEach { value in
var bigEndianVersion = value.bigEndian
withUnsafePointer(to: &bigEndianVersion) {
digest.append(contentsOf: Array(UnsafeBufferPointer<UInt8>(start: UnsafePointer(OpaquePointer($0)), count: 4)))
}
}
return digest
}
private static func rotateLeft(_ v: UInt32, _ n: UInt32) -> UInt32 {
return ((v << n) & 0xFFFFFFFF) | (v >> (32 - n))
}
}
extension String {
public func sha1() -> [UInt8] {
return SHA1.hash([UInt8](self.utf8))
}
public func sha1() -> String {
return self.sha1().reduce("") { $0 + String(format: "%02x", $1) }
}
}
| bsd-3-clause | 1023b17450d3c7321cb1b47135f8df96 | 31.131387 | 135 | 0.510677 | 3.871592 | false | false | false | false |
ReactiveX/RxSwift | RxSwift/Observables/Map.swift | 1 | 2493 | //
// Map.swift
// RxSwift
//
// Created by Krunoslav Zaher on 3/15/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
extension ObservableType {
/**
Projects each element of an observable sequence into a new form.
- seealso: [map operator on reactivex.io](http://reactivex.io/documentation/operators/map.html)
- parameter transform: A transform function to apply to each source element.
- returns: An observable sequence whose elements are the result of invoking the transform function on each element of source.
*/
public func map<Result>(_ transform: @escaping (Element) throws -> Result)
-> Observable<Result> {
Map(source: self.asObservable(), transform: transform)
}
}
final private class MapSink<SourceType, Observer: ObserverType>: Sink<Observer>, ObserverType {
typealias Transform = (SourceType) throws -> ResultType
typealias ResultType = Observer.Element
private let transform: Transform
init(transform: @escaping Transform, observer: Observer, cancel: Cancelable) {
self.transform = transform
super.init(observer: observer, cancel: cancel)
}
func on(_ event: Event<SourceType>) {
switch event {
case .next(let element):
do {
let mappedElement = try self.transform(element)
self.forwardOn(.next(mappedElement))
}
catch let e {
self.forwardOn(.error(e))
self.dispose()
}
case .error(let error):
self.forwardOn(.error(error))
self.dispose()
case .completed:
self.forwardOn(.completed)
self.dispose()
}
}
}
final private class Map<SourceType, ResultType>: Producer<ResultType> {
typealias Transform = (SourceType) throws -> ResultType
private let source: Observable<SourceType>
private let transform: Transform
init(source: Observable<SourceType>, transform: @escaping Transform) {
self.source = source
self.transform = transform
}
override func run<Observer: ObserverType>(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == ResultType {
let sink = MapSink(transform: self.transform, observer: observer, cancel: cancel)
let subscription = self.source.subscribe(sink)
return (sink: sink, subscription: subscription)
}
}
| mit | caf05fd34358d338fcc5a4a856809c35 | 31.789474 | 174 | 0.649679 | 4.773946 | false | false | false | false |
proversity-org/edx-app-ios | Source/DiscussionResponsesViewController.swift | 1 | 40350 | //
// DiscussionResponsesViewController.swift
// edX
//
// Created by Lim, Jake on 5/12/15.
// Copyright (c) 2015 edX. All rights reserved.
//
import Foundation
private let GeneralPadding: CGFloat = 8.0
private let cellButtonStyle = OEXTextStyle(weight:.normal, size:.base, color: OEXStyles.shared().neutralDark())
private let cellIconSelectedStyle = cellButtonStyle.withColor(OEXStyles.shared().primaryBaseColor())
private let responseMessageStyle = OEXTextStyle(weight: .normal, size: .base, color: OEXStyles.shared().neutralDark())
private let disabledCommentStyle = OEXTextStyle(weight: .normal, size: .base, color: OEXStyles.shared().neutralBase())
class DiscussionCellButton: UIButton {
var indexPath: IndexPath?
}
class DiscussionPostCell: UITableViewCell {
static let identifier = "DiscussionPostCell"
@IBOutlet fileprivate var titleLabel: UILabel!
@IBOutlet fileprivate var bodyTextLabel: UILabel!
@IBOutlet fileprivate var visibilityLabel: UILabel!
@IBOutlet fileprivate var authorButton: UIButton!
@IBOutlet fileprivate var responseCountLabel:UILabel!
@IBOutlet fileprivate var voteButton: DiscussionCellButton!
@IBOutlet fileprivate var followButton: DiscussionCellButton!
@IBOutlet fileprivate var reportButton: DiscussionCellButton!
@IBOutlet fileprivate var separatorLine: UIView!
@IBOutlet fileprivate var separatorLineHeightConstraint: NSLayoutConstraint!
@IBOutlet weak var authorProfileImage: UIImageView!
@IBOutlet weak var authorNameLabel: UILabel!
@IBOutlet weak var dateLabel: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
self.selectionStyle = .none
for (button, icon, text) in [
(voteButton!, Icon.UpVote, ""),
(followButton!, Icon.FollowStar, Strings.discussionFollow),
(reportButton!, Icon.ReportFlag, Strings.discussionReport)
]
{
let buttonText = NSAttributedString.joinInNaturalLayout(attributedStrings: [icon.attributedTextWithStyle(style: cellButtonStyle, inline: true),
cellButtonStyle.attributedString(withText: text )])
button.setAttributedTitle(buttonText, for:.normal)
}
separatorLine.backgroundColor = OEXStyles.shared().standardDividerColor
separatorLineHeightConstraint.constant = OEXStyles.dividerSize()
voteButton.localizedHorizontalContentAlignment = .Leading
followButton.localizedHorizontalContentAlignment = .Center
reportButton.localizedHorizontalContentAlignment = .Trailing
authorButton.localizedHorizontalContentAlignment = .Leading
DiscussionHelper.styleAuthorProfileImageView(imageView: authorProfileImage)
}
func setAccessibility(thread: DiscussionThread) {
var accessibilityString = ""
let sentenceSeparator = ", "
if let title = thread.title {
accessibilityString.append(title + sentenceSeparator)
}
if let body = thread.rawBody {
accessibilityString.append(body + sentenceSeparator)
}
if let date = dateLabel.text {
accessibilityString.append(Strings.Accessibility.discussionPostedOn(date: date) + sentenceSeparator)
}
if let author = authorNameLabel.text {
accessibilityString.append(Strings.accessibilityBy + " " + author + sentenceSeparator)
}
if let visibility = visibilityLabel.text {
accessibilityString.append(visibility)
}
if let responseCount = responseCountLabel.text {
accessibilityString.append(responseCount)
}
self.accessibilityLabel = accessibilityString
if let authorName = authorNameLabel.text {
self.authorButton.accessibilityLabel = authorName
self.authorButton.accessibilityHint = Strings.accessibilityShowUserProfileHint
}
}
}
class DiscussionResponseCell: UITableViewCell {
static let identifier = "DiscussionResponseCell"
private static let margin : CGFloat = 8.0
@IBOutlet private var containerView: UIView!
@IBOutlet fileprivate var bodyTextView: UITextView!
@IBOutlet fileprivate var authorButton: UIButton!
@IBOutlet fileprivate var voteButton: DiscussionCellButton!
@IBOutlet fileprivate var reportButton: DiscussionCellButton!
@IBOutlet fileprivate var commentButton: DiscussionCellButton!
@IBOutlet fileprivate var commentBox: UIView!
@IBOutlet fileprivate var endorsedLabel: UILabel!
@IBOutlet fileprivate var separatorLine: UIView!
@IBOutlet fileprivate var separatorLineHeightConstraint: NSLayoutConstraint!
@IBOutlet fileprivate var endorsedByButton: UIButton!
@IBOutlet weak var authorProfileImage: UIImageView!
@IBOutlet weak var authorNameLabel: UILabel!
@IBOutlet weak var dateLabel: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
self.selectionStyle = .none
for (button, icon, text) in [
(reportButton!, Icon.ReportFlag, Strings.discussionReport)]
{
let iconString = icon.attributedTextWithStyle(style: cellButtonStyle, inline: true)
let buttonText = NSAttributedString.joinInNaturalLayout(attributedStrings: [iconString,
cellButtonStyle.attributedString(withText: text)])
button.setAttributedTitle(buttonText, for:.normal)
}
commentBox.backgroundColor = OEXStyles.shared().neutralXXLight()
separatorLine.backgroundColor = OEXStyles.shared().standardDividerColor
separatorLineHeightConstraint.constant = OEXStyles.dividerSize()
voteButton.localizedHorizontalContentAlignment = .Leading
reportButton.localizedHorizontalContentAlignment = .Trailing
authorButton.localizedHorizontalContentAlignment = .Leading
endorsedByButton.localizedHorizontalContentAlignment = .Leading
containerView.applyBorderStyle(style: BorderStyle())
accessibilityTraits = UIAccessibilityTraits.header
bodyTextView.isAccessibilityElement = false
endorsedByButton.isAccessibilityElement = false
}
var endorsed : Bool = false {
didSet {
endorsedLabel.isHidden = !endorsed
endorsedByButton.isHidden = !endorsed
}
}
var endorsedTextStyle : OEXTextStyle {
return OEXTextStyle(weight: .normal, size: .small, color: OEXStyles.shared().utilitySuccessBase())
}
override func updateConstraints() {
if endorsedByButton.isHidden {
bodyTextView.snp.remakeConstraints { make in
make.bottom.equalTo(separatorLine.snp.top).offset(-StandardVerticalMargin)
}
}
super.updateConstraints()
}
func setAccessibility(response: DiscussionComment) {
var accessibilityString = ""
let sentenceSeparator = ", "
let body = bodyTextView.attributedText.string
accessibilityString.append(body + sentenceSeparator)
if let date = dateLabel.text {
accessibilityString.append(Strings.Accessibility.discussionPostedOn(date: date) + sentenceSeparator)
}
if let author = authorNameLabel.text {
accessibilityString.append(Strings.accessibilityBy + " " + author + sentenceSeparator)
}
if endorsedByButton.isHidden == false {
if let endorsed = endorsedByButton.attributedTitle(for: .normal)?.string {
accessibilityString.append(endorsed + sentenceSeparator)
}
}
if response.childCount > 0 {
accessibilityString.append(Strings.commentsToResponse(count: response.childCount))
}
self.accessibilityLabel = accessibilityString
if let authorName = authorNameLabel.text {
self.authorButton.accessibilityLabel = authorName
self.authorButton.accessibilityHint = Strings.accessibilityShowUserProfileHint
}
}
}
class DiscussionResponsesViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, DiscussionNewCommentViewControllerDelegate, DiscussionCommentsViewControllerDelegate, InterfaceOrientationOverriding {
typealias Environment = NetworkManagerProvider & OEXRouterProvider & OEXConfigProvider & OEXAnalyticsProvider & DataManagerProvider
enum TableSection : Int {
case Post = 0
case EndorsedResponses = 1
case Responses = 2
}
var environment: Environment!
var courseID: String!
var isDiscussionBlackedOut: Bool = false
var loadController : LoadStateViewController?
var paginationController : PaginationController<DiscussionComment>?
@IBOutlet var tableView: UITableView!
@IBOutlet var contentView: UIView!
private let addResponseButton = UIButton(type: .system)
private let responsesDataController = DiscussionResponsesDataController()
var thread: DiscussionThread?
var threadID: String? // this will be use for deep linking
var postFollowing = false
var profileFeed: Feed<UserProfile>?
var tempComment: DiscussionComment? // this will be used for injecting user info to added comment
func loadContent() {
loadResponses()
let styles = OEXStyles.shared()
let footerStyle = OEXTextStyle(weight: .normal, size: .base, color: OEXStyles.shared().neutralWhite())
let icon = postClosed ? Icon.Closed : Icon.Create
let text = postClosed ? Strings.responsesClosed : Strings.addAResponse
let buttonTitle = NSAttributedString.joinInNaturalLayout(attributedStrings: [icon.attributedTextWithStyle(style: footerStyle.withSize(.xSmall)),
footerStyle.attributedString(withText: text)])
addResponseButton.setAttributedTitle(buttonTitle, for: .normal)
let postingEnabled = (postClosed || isDiscussionBlackedOut)
addResponseButton.backgroundColor = postingEnabled ? styles.neutralBase() : styles.primaryXDarkColor()
addResponseButton.isEnabled = !postingEnabled
addResponseButton.oex_removeAllActions()
if !(thread?.closed ?? true){
addResponseButton.oex_addAction({ [weak self] (action : AnyObject!) -> Void in
if let owner = self, let thread = owner.thread {
owner.environment.router?.showDiscussionNewCommentFromController(controller: owner, courseID: owner.courseID, thread: thread, context: .Thread(thread))
}
}, for: UIControl.Event.touchUpInside)
}
if let thread = thread {
self.navigationItem.title = navigationItemTitleForThread(thread: thread)
}
tableView.reloadSections(NSIndexSet(index: TableSection.Post.rawValue) as IndexSet , with: .fade)
}
var titleTextStyle : OEXTextStyle {
return OEXTextStyle(weight: .normal, size: .large, color: OEXStyles.shared().neutralXDark())
}
var detailTextStyle : OEXTextStyle {
return OEXTextStyle(weight: .normal, size: .base, color: OEXStyles.shared().neutralXDark())
}
var infoTextStyle : OEXTextStyle {
return OEXTextStyle(weight: .normal, size: .base, color: OEXStyles.shared().neutralDark())
}
override func viewDidLoad() {
assert(environment != nil)
assert(courseID != nil)
super.viewDidLoad()
self.view.backgroundColor = OEXStyles.shared().discussionsBackgroundColor
self.contentView.backgroundColor = OEXStyles.shared().neutralXLight()
tableView.backgroundColor = UIColor.clear
tableView.delegate = self
tableView.dataSource = self
loadController = LoadStateViewController()
addResponseButton.contentVerticalAlignment = .center
view.addSubview(addResponseButton)
addResponseButton.snp.makeConstraints{ make in
make.leading.equalTo(safeLeading)
make.trailing.equalTo(safeTrailing)
make.height.equalTo(OEXStyles.shared().standardFooterHeight)
make.bottom.equalTo(safeBottom)
make.top.equalTo(tableView.snp.bottom)
}
tableView.estimatedRowHeight = 160.0
tableView.rowHeight = UITableView.automaticDimension
loadController?.setupInController(controller: self, contentView: contentView)
self.navigationItem.backBarButtonItem = UIBarButtonItem(title: " ", style: .plain, target: nil, action: nil)
markThreadAsRead()
setupProfileLoader()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
logScreenEvent()
}
override var shouldAutorotate: Bool {
return true
}
override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
return .allButUpsideDown
}
private func logScreenEvent(){
if let thread = thread {
self.environment.analytics.trackDiscussionScreen(withName: AnalyticsScreenName.ViewThread, courseId: self.courseID, value: thread.title, threadId: thread.threadID, topicId: thread.topicId, responseID: nil, author: thread.author)
}
}
func navigationItemTitleForThread(thread : DiscussionThread) -> String {
switch thread.type {
case .Discussion:
return Strings.discussion
case .Question:
return thread.hasEndorsed ? Strings.answeredQuestion : Strings.unansweredQuestion
}
}
private var postClosed : Bool {
return thread?.closed ?? false
}
private func markThreadAsRead() {
if let thread = thread {
threadID = thread.threadID
}
let apiRequest = DiscussionAPI.readThread(read: true, threadID: threadID ?? "")
self.environment.networkManager.taskForRequest(apiRequest) {[weak self] result in
if let thread = result.data {
self?.patchThread(thread: thread)
self?.loadContent()
}
}
}
private func refreshTableData() {
tableView.reloadSections(NSIndexSet(index: TableSection.Post.rawValue) as IndexSet , with: .fade)
}
private func patchThread(thread: DiscussionThread) {
var injectedThread = thread
injectedThread.hasProfileImage = self.thread?.hasProfileImage ?? false
injectedThread.imageURL = self.thread?.imageURL ?? ""
self.thread = injectedThread
refreshTableData()
}
private func loadResponses() {
if let thread = thread {
if thread.type == .Question {
// load answered responses
loadAnsweredResponses()
}
else {
loadUnansweredResponses()
}
}
}
private func loadAnsweredResponses() {
guard let thread = thread else { return }
postFollowing = thread.following
let paginator = WrappedPaginator(networkManager: self.environment.networkManager) { page in
return DiscussionAPI.getResponses(environment: self.environment.router?.environment, threadID: thread.threadID, threadType: thread.type, endorsedOnly: true, pageNumber: page)
}
paginationController = PaginationController (paginator: paginator, tableView: self.tableView)
paginationController?.stream.listen(self, success:
{ [weak self] responses in
self?.loadController?.state = .Loaded
self?.responsesDataController.endorsedResponses = responses
self?.tableView.reloadData()
UIAccessibility.post(notification: UIAccessibility.Notification.layoutChanged, argument: nil)
if self?.paginationController?.hasNext ?? false { }
else {
// load unanswered responses
self?.loadUnansweredResponses()
}
}, failure: { [weak self] (error) -> Void in
self?.loadController?.state = LoadState.failed(error: error)
})
paginationController?.loadMore()
}
private func loadUnansweredResponses() {
guard let thread = thread else { return }
let paginator = WrappedPaginator(networkManager: self.environment.networkManager) { page in
return DiscussionAPI.getResponses(environment: self.environment.router?.environment, threadID: thread.threadID, threadType: thread.type, pageNumber: page)
}
paginationController = PaginationController (paginator: paginator, tableView: self.tableView)
paginationController?.stream.listen(self, success:
{ [weak self] responses in
self?.loadController?.state = .Loaded
self?.responsesDataController.responses = responses
self?.tableView.reloadData()
UIAccessibility.post(notification: UIAccessibility.Notification.layoutChanged, argument: nil)
}, failure: { [weak self] (error) -> Void in
// endorsed responses are loaded in separate request and also populated in different section
if self?.responsesDataController.endorsedResponses.count ?? 0 <= 0 {
self?.loadController?.state = LoadState.failed(error: error)
}
else {
self?.loadController?.state = .Loaded
}
})
paginationController?.loadMore()
}
@IBAction func commentTapped(sender: AnyObject) {
if let button = sender as? DiscussionCellButton, let indexPath = button.indexPath {
let aResponse:DiscussionComment?
switch TableSection(rawValue: indexPath.section) {
case .some(.EndorsedResponses):
aResponse = responsesDataController.endorsedResponses[indexPath.row]
case .some(.Responses):
aResponse = responsesDataController.responses[indexPath.row]
default:
aResponse = nil
}
if let response = aResponse {
if response.childCount == 0{
if !postClosed {
guard let thread = thread else { return }
environment.router?.showDiscussionNewCommentFromController(controller: self, courseID: courseID, thread:thread, context: .Comment(response))
}
} else {
guard let thread = thread else { return }
environment.router?.showDiscussionCommentsFromViewController(controller: self, courseID : courseID, response: response, closed : postClosed, thread: thread, isDiscussionBlackedOut: isDiscussionBlackedOut)
}
}
}
}
// Mark - tableview delegate methods
public func numberOfSections(in tableView: UITableView) -> Int {
return 3
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
switch TableSection(rawValue: section) {
case .some(.Post): return 1
case .some(.EndorsedResponses): return responsesDataController.endorsedResponses.count
case .some(.Responses): return responsesDataController.responses.count
case .none:
assert(false, "Unknown table section")
return 0
}
}
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
switch TableSection(rawValue: indexPath.section) {
case .some(.Post):
cell.backgroundColor = UIColor.white
case .some(.EndorsedResponses):
cell.backgroundColor = UIColor.clear
case .some(.Responses):
cell.backgroundColor = UIColor.clear
default:
assert(false, "Unknown table section")
}
}
func applyThreadToCell(cell: DiscussionPostCell) -> UITableViewCell {
if let thread = self.thread {
cell.titleLabel.attributedText = titleTextStyle.attributedString(withText: thread.title)
cell.bodyTextLabel.attributedText = detailTextStyle.attributedString(withText: thread.rawBody)
let visibilityString : String
if let cohortName = thread.groupName {
visibilityString = Strings.postVisibility(cohort: cohortName)
}
else {
visibilityString = Strings.postVisibilityEveryone
}
cell.visibilityLabel.attributedText = infoTextStyle.attributedString(withText: visibilityString)
DiscussionHelper.styleAuthorDetails(author: thread.author, authorLabel: thread.authorLabel, createdAt: thread.createdAt, hasProfileImage: thread.hasProfileImage, imageURL: thread.imageURL, authoNameLabel: cell.authorNameLabel, dateLabel: cell.dateLabel, authorButton: cell.authorButton, imageView: cell.authorProfileImage, viewController: self, router: environment.router)
if let responseCount = thread.responseCount {
let icon = Icon.Comment.attributedTextWithStyle(style: infoTextStyle)
let countLabelText = infoTextStyle.attributedString(withText: Strings.response(count: responseCount))
let labelText = NSAttributedString.joinInNaturalLayout(attributedStrings: [icon,countLabelText])
cell.responseCountLabel.attributedText = labelText
}
else {
cell.responseCountLabel.attributedText = nil
}
updateVoteText(button: cell.voteButton, voteCount: thread.voteCount, voted: thread.voted)
updateFollowText(button: cell.followButton, following: thread.following)
}
// vote a post (thread) - User can only vote on post and response not on comment.
cell.voteButton.oex_removeAllActions()
cell.voteButton.oex_addAction({[weak self] (action : AnyObject!) -> Void in
if let owner = self, let button = action as? DiscussionCellButton, let thread = owner.thread {
button.isEnabled = false
let apiRequest = DiscussionAPI.voteThread(voted: thread.voted, threadID: thread.threadID)
owner.environment.networkManager.taskForRequest(apiRequest) {[weak self] result in
button.isEnabled = true
if let thread: DiscussionThread = result.data {
self?.patchThread(thread: thread)
owner.updateVoteText(button: cell.voteButton, voteCount: thread.voteCount, voted: thread.voted)
}
else {
self?.showOverlay(withMessage: DiscussionHelper.messageForError(error: result.error))
}
}
}
}, for: UIControl.Event.touchUpInside)
// follow a post (thread) - User can only follow original post, not response or comment.
cell.followButton.oex_removeAllActions()
cell.followButton.oex_addAction({[weak self] (sender : AnyObject!) -> Void in
if let owner = self, let thread = owner.thread {
let apiRequest = DiscussionAPI.followThread(following: owner.postFollowing, threadID: thread.threadID)
owner.environment.networkManager.taskForRequest(apiRequest) { result in
if let thread: DiscussionThread = result.data {
owner.updateFollowText(button: cell.followButton, following: thread.following)
owner.postFollowing = thread.following
}
else {
self?.showOverlay(withMessage: DiscussionHelper.messageForError(error: result.error))
}
}
}
}, for: UIControl.Event.touchUpInside)
if let item = self.thread {
updateVoteText(button: cell.voteButton, voteCount: item.voteCount, voted: item.voted)
updateFollowText(button: cell.followButton, following: item.following)
updateReportText(button: cell.reportButton, report: thread!.abuseFlagged)
}
// report (flag) a post (thread) - User can report on post, response, or comment.
cell.reportButton.oex_removeAllActions()
cell.reportButton.oex_addAction({[weak self] (action : AnyObject!) -> Void in
if let owner = self, let item = owner.thread {
let apiRequest = DiscussionAPI.flagThread(abuseFlagged: !item.abuseFlagged, threadID: item.threadID)
owner.environment.networkManager.taskForRequest(apiRequest) { result in
if let thread = result.data {
self?.thread?.abuseFlagged = thread.abuseFlagged
owner.updateReportText(button: cell.reportButton, report: thread.abuseFlagged)
}
else {
self?.showOverlay(withMessage: DiscussionHelper.messageForError(error: result.error))
}
}
}
}, for: UIControl.Event.touchUpInside)
if let thread = self.thread {
cell.setAccessibility(thread: thread)
}
return cell
}
func cellForResponseAtIndexPath(indexPath : IndexPath, response: DiscussionComment) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: DiscussionResponseCell.identifier, for: indexPath) as! DiscussionResponseCell
cell.bodyTextView.attributedText = detailTextStyle.markdownString(withText: response.renderedBody)
if let thread = thread {
let formatedTitle = response.formattedUserLabel(name: response.endorsedBy, date: response.endorsedAt,label: response.endorsedByLabel ,endorsedLabel: true, threadType: thread.type, textStyle: infoTextStyle)
cell.endorsedByButton.setAttributedTitle(formatedTitle, for: .normal)
cell.endorsedByButton.snp.updateConstraints { make in
make.width.equalTo(formatedTitle.singleLineWidth() + StandardHorizontalMargin)
}
}
DiscussionHelper.styleAuthorDetails(author: response.author, authorLabel: response.authorLabel, createdAt: response.createdAt, hasProfileImage: response.hasProfileImage, imageURL: response.imageURL, authoNameLabel: cell.authorNameLabel, dateLabel: cell.dateLabel, authorButton: cell.authorButton, imageView: cell.authorProfileImage, viewController: self, router: environment.router)
DiscussionHelper.styleAuthorProfileImageView(imageView: cell.authorProfileImage)
let profilesEnabled = self.environment.config.profilesEnabled
if profilesEnabled && response.endorsed {
cell.endorsedByButton.oex_removeAllActions()
cell.endorsedByButton.oex_addAction({ [weak self] _ in
guard let endorsedBy = response.endorsedBy else { return }
self?.environment.router?.showProfileForUsername(controller: self, username: endorsedBy, editable: false)
}, for: .touchUpInside)
}
let prompt : String
let icon : Icon
let commentStyle : OEXTextStyle
if response.childCount == 0 {
prompt = postClosed ? Strings.commentsClosed : Strings.addAComment
icon = postClosed ? Icon.Closed : Icon.Comment
commentStyle = isDiscussionBlackedOut ? disabledCommentStyle : responseMessageStyle
cell.commentButton.isEnabled = !isDiscussionBlackedOut
}
else {
prompt = Strings.commentsToResponse(count: response.childCount)
icon = Icon.Comment
commentStyle = responseMessageStyle
}
let iconText = icon.attributedTextWithStyle(style: commentStyle, inline : true)
let styledPrompt = commentStyle.attributedString(withText: prompt)
let title = NSAttributedString.joinInNaturalLayout(attributedStrings: [iconText,styledPrompt])
UIView.performWithoutAnimation {
cell.commentButton.setAttributedTitle(title, for: .normal)
}
let voteCount = response.voteCount
let voted = response.voted
cell.commentButton.indexPath = indexPath
updateVoteText(button: cell.voteButton, voteCount: voteCount, voted: voted)
updateReportText(button: cell.reportButton, report: response.abuseFlagged)
cell.voteButton.indexPath = indexPath
// vote/unvote a response - User can vote on post and response not on comment.
cell.voteButton.oex_removeAllActions()
cell.voteButton.oex_addAction({[weak self] (action : AnyObject!) -> Void in
let apiRequest = DiscussionAPI.voteResponse(voted: response.voted, responseID: response.commentID)
self?.environment.networkManager.taskForRequest(apiRequest) { result in
if let comment: DiscussionComment = result.data {
self?.responsesDataController.updateResponsesWithComment(comment: comment)
self?.updateVoteText(button: cell.voteButton, voteCount: comment.voteCount, voted: comment.voted)
self?.tableView.reloadData()
}
else {
self?.showOverlay(withMessage: DiscussionHelper.messageForError(error: result.error))
}
}
}, for: UIControl.Event.touchUpInside)
cell.reportButton.indexPath = indexPath
// report (flag)/unflag a response - User can report on post, response, or comment.
cell.reportButton.oex_removeAllActions()
cell.reportButton.oex_addAction({[weak self] (action : AnyObject!) -> Void in
let apiRequest = DiscussionAPI.flagComment(abuseFlagged: !response.abuseFlagged, commentID: response.commentID)
self?.environment.networkManager.taskForRequest(apiRequest) { result in
if let comment = result.data {
self?.responsesDataController.updateResponsesWithComment(comment: comment)
self?.updateReportText(button: cell.reportButton, report: comment.abuseFlagged)
self?.tableView.reloadData()
}
else {
self?.showOverlay(withMessage: DiscussionHelper.messageForError(error: result.error))
}
}
}, for: UIControl.Event.touchUpInside)
cell.endorsed = response.endorsed
if let thread = thread {
DiscussionHelper.updateEndorsedTitle(thread: thread, label: cell.endorsedLabel, textStyle: cell.endorsedTextStyle)
cell.setAccessibility(response: response)
}
return cell
}
internal func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
switch TableSection(rawValue: indexPath.section) {
case .some(.Post):
let cell = tableView.dequeueReusableCell(withIdentifier: DiscussionPostCell.identifier, for: indexPath as IndexPath) as! DiscussionPostCell
return applyThreadToCell(cell: cell)
case .some(.EndorsedResponses):
return cellForResponseAtIndexPath(indexPath: indexPath, response: responsesDataController.endorsedResponses[indexPath.row])
case .some(.Responses):
return cellForResponseAtIndexPath(indexPath: indexPath, response: responsesDataController.responses[indexPath.row])
case .none:
assert(false, "Unknown table section")
return UITableViewCell()
}
}
private func updateVoteText(button: DiscussionCellButton, voteCount: Int, voted: Bool) {
// TODO: show upvote and downvote depending on voted?
let iconStyle = voted ? cellIconSelectedStyle : cellButtonStyle
let buttonText = NSAttributedString.joinInNaturalLayout(attributedStrings: [
Icon.UpVote.attributedTextWithStyle(style: iconStyle, inline : true),
cellButtonStyle.attributedString(withText: Strings.vote(count: voteCount))])
button.setAttributedTitle(buttonText, for:.normal)
button.accessibilityHint = voted ? Strings.Accessibility.discussionUnvoteHint : Strings.Accessibility.discussionVoteHint
}
private func updateFollowText(button: DiscussionCellButton, following: Bool) {
let iconStyle = following ? cellIconSelectedStyle : cellButtonStyle
let buttonText = NSAttributedString.joinInNaturalLayout(attributedStrings: [Icon.FollowStar.attributedTextWithStyle(style: iconStyle, inline : true),
cellButtonStyle.attributedString(withText: following ? Strings.discussionUnfollow : Strings.discussionFollow )])
button.setAttributedTitle(buttonText, for:.normal)
button.accessibilityHint = following ? Strings.Accessibility.discussionUnfollowHint : Strings.Accessibility.discussionFollowHint
}
private func updateReportText(button: DiscussionCellButton, report: Bool) {
let iconStyle = report ? cellIconSelectedStyle : cellButtonStyle
let buttonText = NSAttributedString.joinInNaturalLayout(attributedStrings: [Icon.ReportFlag.attributedTextWithStyle(style: iconStyle, inline : true),
cellButtonStyle.attributedString(withText: report ? Strings.discussionUnreport : Strings.discussionReport )])
button.setAttributedTitle(buttonText, for:.normal)
button.accessibilityHint = report ? Strings.Accessibility.discussionUnreportHint : Strings.Accessibility.discussionReportHint
}
func increaseResponseCount() {
let count = thread?.responseCount ?? 0
thread?.responseCount = count + 1
}
private func showAddedResponse(comment: DiscussionComment) {
responsesDataController.responses.append(comment)
tableView.reloadData()
// Basically the reload happens during the next layout pass, which normally happens when you return control to the run loop (after, say, your button action or whatever returns) So one way to run something after the table view reloads is simply to force the table view to perform layout immediately
tableView.layoutIfNeeded()
let indexPath = IndexPath(row: responsesDataController.responses.count - 1, section: TableSection.Responses.rawValue)
if tableView.hasRow(at: indexPath) {
tableView.scrollToRow(at: indexPath, at: .top, animated: false)
}
}
private func setupProfileLoader() {
guard environment.config.profilesEnabled else { return }
profileFeed = self.environment.dataManager.userProfileManager.feedForCurrentUser()
profileFeed?.output.listen(self, success: { [weak self] profile in
if var comment = self?.tempComment {
comment.hasProfileImage = !((profile.imageURL?.isEmpty) ?? true )
comment.imageURL = profile.imageURL ?? ""
self?.showAddedResponse(comment: comment)
self?.tempComment = nil
}
}, failure : { _ in
Logger.logError("Profiles", "Unable to fetch profile")
})
}
// MARK:- DiscussionNewCommentViewControllerDelegate method
func newCommentController(controller: DiscussionNewCommentViewController, addedComment comment: DiscussionComment) {
switch controller.currentContext() {
case .Thread(_):
if !(paginationController?.hasNext ?? false) {
self.tempComment = comment
profileFeed?.refresh()
}
increaseResponseCount()
showOverlay(withMessage: Strings.discussionThreadPosted)
case .Comment(_):
responsesDataController.addedChildComment(comment: comment)
self.showOverlay(withMessage:Strings.discussionCommentPosted)
}
self.tableView.reloadData()
}
// MARK:- DiscussionCommentsViewControllerDelegate
func discussionCommentsView(controller: DiscussionCommentsViewController, updatedComment comment: DiscussionComment) {
responsesDataController.updateResponsesWithComment(comment: comment)
self.tableView.reloadData()
}
}
extension NSDate {
private var shouldDisplayTimeSpan : Bool {
let currentDate = NSDate()
return currentDate.days(from: self as Date?) < 7
}
public var displayDate : String {
return shouldDisplayTimeSpan ? self.timeAgoSinceNow() : DateFormatting.format(asDateMonthYearString: self)
}
}
protocol AuthorLabelProtocol {
var createdAt : NSDate? { get }
var author : String? { get }
var authorLabel : String? { get }
}
extension DiscussionComment : AuthorLabelProtocol {}
extension DiscussionThread : AuthorLabelProtocol {}
extension AuthorLabelProtocol {
func formattedUserLabel(textStyle: OEXTextStyle) -> NSAttributedString {
return formattedUserLabel(name: author, date: createdAt, label: authorLabel, threadType: nil, textStyle: textStyle)
}
func formattedUserLabel(name: String?, date: NSDate?, label: String?, endorsedLabel:Bool = false, threadType:DiscussionThreadType?, textStyle : OEXTextStyle) -> NSAttributedString {
var attributedStrings = [NSAttributedString]()
if let threadType = threadType {
switch threadType {
case .Question where endorsedLabel:
attributedStrings.append(textStyle.attributedString(withText: Strings.markedAnswer))
case .Discussion where endorsedLabel:
attributedStrings.append(textStyle.attributedString(withText: Strings.endorsed))
default: break
}
}
if let displayDate = date {
attributedStrings.append(textStyle.attributedString(withText: displayDate.displayDate))
}
let highlightStyle = OEXMutableTextStyle(textStyle: textStyle)
if let _ = name, OEXConfig.shared().profilesEnabled {
highlightStyle.color = OEXStyles.shared().primaryBaseColor()
highlightStyle.weight = .semiBold
}
else {
highlightStyle.color = OEXStyles.shared().neutralBase()
highlightStyle.weight = textStyle.weight
}
let formattedUserName = highlightStyle.attributedString(withText: name ?? Strings.anonymous.oex_lowercaseStringInCurrentLocale())
let byAuthor = textStyle.attributedString(withText: Strings.byAuthorLowerCase(authorName: formattedUserName.string))
attributedStrings.append(byAuthor)
if let authorLabel = label {
attributedStrings.append(textStyle.attributedString(withText: Strings.parenthesis(text: authorLabel)))
}
return NSAttributedString.joinInNaturalLayout(attributedStrings: attributedStrings)
}
}
extension UITableView {
func hasRow(at indexPath: IndexPath) -> Bool {
return indexPath.section < numberOfSections && indexPath.row < numberOfRows(inSection: indexPath.section)
}
}
| apache-2.0 | 5b93f7e354e42daea628941bc51f4ae9 | 43.389439 | 390 | 0.651499 | 5.849522 | false | false | false | false |
wordpress-mobile/WordPress-iOS | WordPress/Classes/ViewRelated/Media/ImageCropOverlayView.swift | 2 | 1656 | import Foundation
import UIKit
@objc enum ImageCropOverlayMaskShape: Int {
case circle
case square
}
// Renders an "Outer Ellipse or Square Overlay", to be used on top of the Image
// Defaults to an Ellipse
//
class ImageCropOverlayView: UIView {
// MARK: - Public Properties
@objc var borderWidth = CGFloat(3)
@objc var borderColor: UIColor?
@objc var outerColor: UIColor?
var maskShape: ImageCropOverlayMaskShape = .circle
// MARK: - Overriden Methods
override func layoutSubviews() {
super.layoutSubviews()
setNeedsDisplay()
}
override func draw(_ rect: CGRect) {
super.draw(rect)
let context = UIGraphicsGetCurrentContext()!
// Setup
context.saveGState()
context.setLineWidth(borderWidth)
context.setAllowsAntialiasing(true)
context.setShouldAntialias(true)
// Outer
outerColor?.setFill()
context.addRect(bounds)
// Prevent from clipping
let delta = borderWidth - 1.0
switch maskShape {
case .square:
let squareRect = bounds.insetBy(dx: delta, dy: delta)
context.addRect(squareRect)
context.fillPath(using: .evenOdd)
context.addRect(squareRect)
case .circle:
let ellipseRect = bounds.insetBy(dx: delta, dy: delta)
context.addEllipse(in: ellipseRect)
context.fillPath(using: .evenOdd)
context.addEllipse(in: ellipseRect)
}
// Border
borderColor?.setStroke()
context.strokePath()
// Wrap Up
context.restoreGState()
}
}
| gpl-2.0 | d459544aeafbff0e730f837d1af80f8d | 27.067797 | 79 | 0.620773 | 4.8 | false | false | false | false |
wordpress-mobile/WordPress-iOS | WordPress/Classes/ViewRelated/Blog/Blog Dashboard/Cards/Ghost/DashboardGhostCardCell.swift | 1 | 1772 | import Foundation
import UIKit
class DashboardGhostCardCell: UICollectionViewCell, Reusable, BlogDashboardCardConfigurable {
private lazy var contentStackView: UIStackView = {
let contentStackView = UIStackView()
contentStackView.axis = .vertical
contentStackView.translatesAutoresizingMaskIntoConstraints = false
contentStackView.spacing = Constants.spacing
return contentStackView
}()
override init(frame: CGRect) {
super.init(frame: frame)
for _ in 0..<Constants.numberOfCards {
contentStackView.addArrangedSubview(ghostCard())
}
contentView.addSubview(contentStackView)
contentView.pinSubviewToAllEdges(contentStackView, insets: Constants.insets,
priority: Constants.constraintPriority)
isAccessibilityElement = false
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func configure(blog: Blog, viewController: BlogDashboardViewController?, apiResponse: BlogDashboardRemoteEntity?) {
startGhostAnimation(style: GhostCellStyle.muriel)
}
private func ghostCard() -> BlogDashboardCardFrameView {
let frameView = BlogDashboardCardFrameView()
let content = DashboardGhostCardContent.loadFromNib()
frameView.hideHeader()
frameView.add(subview: content)
return frameView
}
private enum Constants {
static let spacing: CGFloat = 20
static let numberOfCards = 5
static let insets = UIEdgeInsets(top: 0, left: 0, bottom: 20, right: 0)
static let constraintPriority = UILayoutPriority(999)
}
}
class DashboardGhostCardContent: UIView, NibLoadable { }
| gpl-2.0 | c48ca3405963c5a2d6e784cafc5848e4 | 32.433962 | 119 | 0.688488 | 5.625397 | false | false | false | false |
tomkowz/TSTextMapper | Classes/TSTextMapper.swift | 1 | 4715 | //
// TSTextMapper.swift
//
// Created by Tomasz Szulc on 28/10/14.
// Copyright (c) 2014 Tomasz Szulc. All rights reserved.
//
import Foundation
import UIKit
class TSTextProxy {
let value: String
init(_ text: TSText) {
self.value = text.value
}
init(_ text: String) {
self.value = text
}
}
class TSTextMapper {
private enum Method {
case All
case Ranges
}
/// font of text
private let font: UIFont
/// size of view where text is presented
private let viewSize: CGSize
/**
Internal view where analyzed text is drawed,
Coordinates of taps are used to detect which text is tapped
*/
private var view: TSTextSceneView?
/// lines of analyzed text. Lines contain words
private var lines: [TSTextLine] = [TSTextLine]()
/// ranges specified by user. Text in ranges is able to be selected
private var ranges: [NSRange] = [NSRange]()
/// specifies which method is used
private var method: Method = .All
private var texts: [TSText] {
var objects = [TSText]()
for line in lines {
for text in line.texts {
objects.append(text)
}
}
return objects
}
init(_ view: UILabel) {
self.font = view.font
self.viewSize = view.bounds.size
}
func mapTextAndMakeAllTappable(text: String) {
self.method = .All
self.map(text)
}
func mapTextWithTappableRanges(ranges: [NSRange], text: String) {
self.method = .Ranges
self.map(text)
self.ranges = ranges
}
private func map(text: String) {
let analyzer = TSTextAnalyzer(text: text, font: self.font, size: self.viewSize)
self.lines = analyzer.analize()
// self.debug()
}
private func debug() {
let debugView = TSTextSceneView(size: self.viewSize, texts: self.texts, font: self.font)
debugView.prepare()
let debugImage = debugView.snapshot()
println("debug")
}
func textForPoint(point: CGPoint) -> TSTextProxy? {
if self.texts.count == 0 {
return nil
}
if self.view == nil {
self.view = TSTextSceneView(size: self.viewSize, texts: self.texts, font: self.font)
self.view!.prepare()
}
if let node = self.view!.nodeForPoint(point) {
// println("node = \(node.text.value), \(node.text.range.location), \(node.text.range.length)")
switch self.method {
case .All:
return TSTextProxy(node.text) /// if .All method is selected return tapped text
case .Ranges:
/// Find range contained inside tapped node
var selectedRange: NSRange?
for r in self.ranges {
if node.text.range.containsRange(r) {
selectedRange = r
break
}
}
if let range = selectedRange {
/// range matches the node, get text, translate selected range to match range in the node.
let text = (node.text.value as NSString)
let location = range.location - node.text.range.location
let length = range.length - location
if length > 0 {
/// get the text with the new range
let textInRange = text.substringWithRange(NSMakeRange(location, length))
let textSize = TSTextSize.size(textInRange, font: self.font, size: self.viewSize)
/// simulate frame of node with `textInRange` and check if it contains touched point
let textInRangeNodeFrame = CGRectMake(node.frame.minX, node.frame.minY, textSize.width, textSize.height)
if CGRectContainsPoint(textInRangeNodeFrame, point) {
return TSTextProxy(textInRange)
}
}
}
return nil
}
}
return nil
}
}
public func == (lhs: NSRange, rhs: NSRange) -> Bool {
return lhs.location == rhs.location && lhs.length == rhs.length
}
extension NSRange: Equatable {
func containsRange(r: NSRange) -> Bool {
let start = self.location
let end = start + self.length
return (r.location >= start) && ((r.location + r.length) <= end)
}
}
| apache-2.0 | 8ba929d128af42bc9609ad1727cde842 | 29.419355 | 128 | 0.533404 | 4.762626 | false | false | false | false |
shijinliang/KSMoney | Sources/App/Models/TokenMiddleware.swift | 1 | 1884 | //
// TokenMiddleware.swift
// NHServer
//
// Created by niuhui on 2017/5/9.
//
//
import Vapor
import HTTP
import Foundation
var session_caches = [String : Session]()
var user_caches = [String:User]()
final class TokenMiddleware: Middleware {
var user : User?
func respond(to request: Request, chainingTo next: Responder) throws -> Response {
var session : Session
guard let token = request.data["access_token"]?.string else{
return try JSON([
code: 1,
msg : "未登录"
]).makeResponse()
}
if let session_cach = session_caches[token] {
session = session_cach
} else {
guard let temp_session = try Session.makeQuery().filter("token", token).first() else {
return try JSON([
code: 1,
msg : "未登录"
]).makeResponse()
}
session = temp_session
}
guard session.expire_at >= Int(Date().timeIntervalSince1970) else {
try session.delete()
session_caches.removeValue(forKey: token)
return try JSON([
code: 1,
msg : "登录过期"
]).makeResponse()
}
session_caches[token] = session
if let _ = user_caches[session.uuid.string] {
} else {
guard let user = try User.makeQuery().filter("id", session.user_id).first() else {
try session.delete()
session_caches.removeValue(forKey: token)
return try JSON([
code: 1,
msg : "登录过期"
]).makeResponse()
}
user_caches[user.uuid.string] = user
}
return try next.respond(to: request)
}
}
| mit | 95e608d7c27834a032da1e62caac9f74 | 28.460317 | 98 | 0.498384 | 4.605459 | false | false | false | false |
bignerdranch/Deferred | Tests/DeferredTests/ExistentialFutureTests.swift | 1 | 4871 | //
// ExistentialFutureTests.swift
// DeferredTests
//
// Created by Zachary Waldowski on 9/3/15.
// Copyright © 2014-2018 Big Nerd Ranch. Licensed under MIT.
//
import XCTest
import Deferred
class ExistentialFutureTests: XCTestCase {
static let allTests: [(String, (ExistentialFutureTests) -> () throws -> Void)] = [
("testPeekWhenFilled", testPeekWhenFilled),
("testPeekWhenUnfilled", testPeekWhenUnfilled),
("testAnyWaitWithTimeout", testAnyWaitWithTimeout),
("testFilledAnyFutureUpon", testFilledAnyFutureUpon),
("testUnfilledAnyUponCalledWhenFilled", testUnfilledAnyUponCalledWhenFilled),
("testFillAndIsFilledPostcondition", testFillAndIsFilledPostcondition),
("testDebugDescriptionUnfilled", testDebugDescriptionUnfilled),
("testDebugDescriptionFilled", testDebugDescriptionFilled),
("testDebugDescriptionFilledWhenValueIsVoid", testDebugDescriptionFilledWhenValueIsVoid),
("testReflectionUnfilled", testReflectionUnfilled),
("testReflectionFilled", testReflectionFilled),
("testReflectionFilledWhenValueIsVoid", testReflectionFilledWhenValueIsVoid)
]
var anyFuture: Future<Int>!
override func tearDown() {
anyFuture = nil
super.tearDown()
}
func testPeekWhenFilled() {
anyFuture = Future(value: 42)
let peek = anyFuture.peek()
XCTAssertNotNil(peek)
}
func testPeekWhenUnfilled() {
anyFuture = Future<Int>.never
let peek = anyFuture.peek()
XCTAssertNil(peek)
}
func testAnyWaitWithTimeout() {
let deferred = Deferred<Int>()
anyFuture = deferred.eraseToFuture()
let expect = expectation(description: "value blocks while unfilled")
afterShortDelay {
deferred.fill(with: 42)
expect.fulfill()
}
XCTAssertNil(anyFuture.shortWait())
wait(for: [ expect ], timeout: shortTimeout)
}
func testFilledAnyFutureUpon() {
let future = Future(value: 1)
let allExpectations = (0 ..< 10).map { (iteration) -> XCTestExpectation in
let expect = expectation(description: "upon block #\(iteration) called with correct value")
future.upon { value in
XCTAssertEqual(value, 1)
expect.fulfill()
}
return expect
}
wait(for: allExpectations, timeout: longTimeout)
}
func testUnfilledAnyUponCalledWhenFilled() {
let deferred = Deferred<Int>()
anyFuture = deferred.eraseToFuture()
let allExpectations = (0 ..< 10).map { (iteration) -> XCTestExpectation in
let expect = expectation(description: "upon block #\(iteration) not called while deferred is unfilled")
anyFuture.upon { value in
XCTAssertEqual(value, 1)
XCTAssertEqual(deferred.value, value)
expect.fulfill()
}
return expect
}
deferred.fill(with: 1)
wait(for: allExpectations, timeout: longTimeout)
}
func testFillAndIsFilledPostcondition() {
let deferred = Deferred<Int>()
anyFuture = deferred.eraseToFuture()
XCTAssertNil(anyFuture.peek())
XCTAssertFalse(anyFuture.isFilled)
deferred.fill(with: 42)
XCTAssertNotNil(anyFuture.peek())
XCTAssertTrue(anyFuture.isFilled)
}
func testDebugDescriptionUnfilled() {
let future = Future<Int>.never
XCTAssertEqual("\(future)", "Future(not filled)")
}
func testDebugDescriptionFilled() {
let future = Future<Int>(value: 42)
XCTAssertEqual("\(future)", "Future(42)")
}
func testDebugDescriptionFilledWhenValueIsVoid() {
let future = Future<Void>(value: ())
XCTAssertEqual("\(future)", "Future(filled)")
}
func testReflectionUnfilled() {
let future = Future<Int>.never
let magicMirror = Mirror(reflecting: future)
XCTAssertEqual(magicMirror.displayStyle, .optional)
XCTAssertNil(magicMirror.superclassMirror)
XCTAssertEqual(magicMirror.descendant("isFilled") as? Bool, false)
}
func testReflectionFilled() {
let future = Future<Int>(value: 42)
let magicMirror = Mirror(reflecting: future)
XCTAssertEqual(magicMirror.displayStyle, .optional)
XCTAssertNil(magicMirror.superclassMirror)
XCTAssertEqual(magicMirror.descendant(0) as? Int, 42)
}
func testReflectionFilledWhenValueIsVoid() {
let future = Future<Void>(value: ())
let magicMirror = Mirror(reflecting: future)
XCTAssertEqual(magicMirror.displayStyle, .optional)
XCTAssertNil(magicMirror.superclassMirror)
XCTAssertEqual(magicMirror.descendant("isFilled") as? Bool, true)
}
}
| mit | af82475d3cfb1ed68c43f71b755ce061 | 32.356164 | 115 | 0.650308 | 5.175345 | false | true | false | false |
gssdromen/KcptunMac | LaunchHelper/LaunchHelper/AppDelegate.swift | 1 | 1513 | //
// AppDelegate.swift
// LaunchHelper
//
// Created by 邱宇舟 on 2017/1/12.
// Copyright © 2017年 qiuyuzhou. All rights reserved.
//
import Cocoa
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
@IBOutlet weak var window: NSWindow!
func applicationDidFinishLaunching(_ aNotification: Notification) {
// Insert code here to initialize your application
let mainBundleId = "com.qiuyuzhou.ShadowsocksX-NG"
var alreadyRunning = false;
for app in NSWorkspace.shared().runningApplications {
if app.bundleIdentifier == mainBundleId {
alreadyRunning = true
break
}
}
if (!alreadyRunning) {
let helperPath: NSString = Bundle.main.bundlePath as NSString;
var pathComponents = helperPath.pathComponents;
pathComponents.removeLast(3);
let mainBundlePath = NSString.path(withComponents: pathComponents);
if !NSWorkspace.shared().launchApplication(mainBundlePath) {
NSLog("Launch app \(mainBundleId) failed.")
}
// if !NSWorkspace.shared().launchApplication("/Applications/ShadowsocksX-NG.app") {
// NSLog("Launch app \(mainBundleId) failed.")
// }
}
NSApp.terminate(nil);
}
func applicationWillTerminate(_ aNotification: Notification) {
// Insert code here to tear down your application
}
}
| gpl-3.0 | f0e9f2c283f5cc09ac56fb7df32970a5 | 30.333333 | 95 | 0.619016 | 5.168385 | false | false | false | false |
AboutCXJ/30DaysOfSwift | Project 14 - EmojiSlotMachine/Project 14 - EmojiSlotMachine/ViewController.swift | 1 | 4254 | //
// ViewController.swift
// Project 14 - EmojiSlotMachine
//
// Created by sfzx on 2017/11/1.
// Copyright © 2017年 陈鑫杰. All rights reserved.
//
import UIKit
let screenWidth = UIScreen.main.bounds.size.width
let screenHeight = UIScreen.main.bounds.size.height
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
self.setupUI()
}
override var preferredStatusBarStyle: UIStatusBarStyle {
return .lightContent
}
//MARK: - handle
func setupUI() {
self.view.addSubview(self.backImageView)
self.view.addSubview(self.pickView)
self.view.addSubview(self.resultLB)
self.view.addSubview(self.rollingBtn)
}
@objc func rollingBtnClick() {
let random1 = Int(arc4random()) % self.datas.count
let random2 = Int(arc4random()) % self.datas.count
let random3 = Int(arc4random()) % self.datas.count
self.pickView.selectRow(random1, inComponent: 0, animated: true)
self.pickView.selectRow(random2, inComponent: 1, animated: true)
self.pickView.selectRow(random3, inComponent: 2, animated: true)
if self.datas[random1] == self.datas[random2] && self.datas[random2] == self.datas[random3] {
self.resultLB.text = "Bingo"
}else{
self.resultLB.text = "💔"
}
}
//MARK: - 懒加载
lazy var backImageView: UIImageView = {
let backImageView = UIImageView(frame: self.view.bounds)
backImageView.image = UIImage(named: "backGround")
return backImageView
}()
lazy var pickView: UIPickerView = {
let pickView = UIPickerView(frame: CGRect(x: 0, y: (screenHeight - 300)*0.3, width: screenWidth, height: 300))
pickView.isUserInteractionEnabled = false
pickView.delegate = self
pickView.dataSource = self
return pickView
}()
lazy var resultLB: UILabel = {
let resultLB = UILabel(frame: CGRect(x: (screenWidth-100)*0.5, y: screenHeight - 200, width: 100, height: 30))
resultLB.font = UIFont.systemFont(ofSize: 25)
resultLB.textColor = .white
resultLB.textAlignment = .center
return resultLB
}()
lazy var rollingBtn: UIButton = {
let rollingBtn = UIButton(frame: CGRect(x: 50, y: screenHeight - 120, width: screenWidth-100, height: 50))
rollingBtn.layer.cornerRadius = 5
rollingBtn.layer.masksToBounds = true
rollingBtn.backgroundColor = UIColor(red: 0.63, green: 1.0, blue: 0.05, alpha: 1.0)
rollingBtn.setTitleColor(.white, for: .normal)
rollingBtn.addTarget(self, action: #selector(rollingBtnClick), for: .touchUpInside)
rollingBtn.setTitle("GO", for: .normal)
return rollingBtn
}()
lazy var datas: [String] = {
let tempDatas = ["👻","👸","💩","😘","🍔","🤖","🍟","🐼","🚖","🐷"]
var datas: [String] = [String]()
for var i in 0..<10 {
for emoji in tempDatas {
datas.append(emoji)
}
}
return datas
}()
}
//MARK: - UIPickerViewDelegate
extension ViewController: UIPickerViewDelegate {
func pickerView(_ pickerView: UIPickerView, widthForComponent component: Int) -> CGFloat {
return screenWidth/3
}
func pickerView(_ pickerView: UIPickerView, rowHeightForComponent component: Int) -> CGFloat {
return 100
}
func pickerView(_ pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusing view: UIView?) -> UIView {
let pickerLabel = UILabel()
pickerLabel.text = self.datas[row]
pickerLabel.font = UIFont(name: "Apple Color Emoji", size: 80)
pickerLabel.textAlignment = NSTextAlignment.center
return pickerLabel
}
}
//MARK: - UIPickerViewDataSource
extension ViewController: UIPickerViewDataSource {
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 3
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return self.datas.count
}
}
| mit | 3840903c979ab82ec9859d213b1c6f25 | 31.353846 | 132 | 0.625773 | 4.418067 | false | false | false | false |
johnno1962/eidolon | KioskTests/Bid Fulfillment/GenericFormValidationViewModelTests.swift | 1 | 2123 | import Quick
import Nimble
import RxSwift
@testable
import Kiosk
class GenericFormValidationViewModelTests: QuickSpec {
override func spec() {
var validSubject: Observable<Bool>!
var disposeBag: DisposeBag!
beforeEach {
validSubject = Observable.just(true)
disposeBag = DisposeBag()
}
it("executes command when manual sends") {
var completed = false
let invocation = PublishSubject<Void>()
let subject = GenericFormValidationViewModel(isValid: validSubject, manualInvocation: invocation, finishedSubject: PublishSubject<Void>())
subject.command.executing.take(1).subscribeNext { _ in
completed = true
}.addDisposableTo(disposeBag)
invocation.onNext()
expect(completed).toEventually( beTrue() )
}
it("sends completed on finishedSubject when command is executed") {
var completed = false
let invocation = PublishSubject<Void>()
let finishedSubject = PublishSubject<Void>()
finishedSubject.subscribeCompleted {
completed = true
}.addDisposableTo(disposeBag)
let subject = GenericFormValidationViewModel(isValid: validSubject, manualInvocation: invocation, finishedSubject: finishedSubject)
subject.command.execute()
expect(completed).toEventually( beTrue() )
}
it("uses the isValid for the command enabledness") {
let validSubject = PublishSubject<Bool>()
let subject = GenericFormValidationViewModel(isValid: validSubject, manualInvocation: Observable.empty(), finishedSubject: PublishSubject<Void>())
validSubject.onNext(false)
expect(subject.command.enabled).toEventually( equalFirst(false) )
validSubject.onNext(true)
expect(subject.command.enabled).toEventually( equalFirst(true) )
validSubject.onNext(false)
expect(subject.command.enabled).toEventually( equalFirst(false) )
}
}
}
| mit | 85dd6156c3b8264eb961bed67c849e44 | 31.661538 | 158 | 0.642016 | 5.864641 | false | false | false | false |
colemancda/DemoPeripheral | Sources/Peripheral/PeripheralController.swift | 1 | 3505 | //
// PeripheralController.swift
// DemoPeripheral
//
// Created by Alsey Coleman Miller on 7/13/16.
// Copyright © 2016 ColemanCDA. All rights reserved.
//
#if os(Linux)
import Glibc
#elseif os(OSX)
import Darwin.C
#endif
import SwiftFoundation
import Bluetooth
import GATT
/// The periperal's main controller.
final class PeripheralController {
static let shared = PeripheralController()
// MARK: - Properties
let peripheral = PeripheralManager()
let identifier = UUID()
private(set) var status: Bool = true {
didSet { didChangeStatus(oldValue: oldValue) }
}
lazy var appLED: GPIO = {
let gpio = GPIO(sunXi: SunXiGPIO(letter: .A, pin: 1)) // Change to whatever you want, depending on your hardware
gpio.direction = .OUT
return gpio
}()
// MARK: - Initialization
private init() {
// setup server
peripheral.log = { print("Peripheral: " + $0) }
peripheral.willWrite = willWrite
// add service to GATT server
addPeripheralService()
// turn on app LED
appLED.value = 1
// start GATT server
let beacon = Beacon(UUID: BeaconUUID, major: 0, minor: 0, RSSI: -56)
#if os(Linux)
do { try peripheral.start(beacon: beacon) }
catch { fatalError("Could not start peripheral: \(error)") }
#elseif os(OSX)
do { try peripheral.start() }
catch { fatalError("Could not start peripheral: \(error)") }
#endif
print("Initialized Peripheral \(identifier)")
}
// MARK: - Private Methods
private func addPeripheralService() {
let identifierValue = PeripheralService.Identifier(value: self.identifier).toBigEndian()
let identifier = Characteristic(UUID: PeripheralService.Identifier.UUID, value: identifierValue, permissions: [.Read], properties: [.Read])
let statusValue = PeripheralService.Status(value: self.status).toBigEndian()
let status = Characteristic(UUID: PeripheralService.Status.UUID, value: statusValue, permissions: [.Read, .Write], properties: [.Read, .Write])
let periperhalService = Service(UUID: PeripheralService.UUID, primary: true, characteristics: [identifier, status])
let _ = try! peripheral.add(service: periperhalService)
}
private func didChangeStatus(oldValue: Bool) {
print("Status \(oldValue) -> \(status)")
peripheral[characteristic: PeripheralService.Status.UUID] = PeripheralService.Status(value: self.status).toBigEndian()
// turn on / off LED
#if arch(arm)
appLED.value = status ? 1 : 0
#endif
}
private func willWrite(central: Central, UUID: BluetoothUUID, value: Data, newValue: Data) -> Bluetooth.ATT.Error? {
switch UUID {
case PeripheralService.Status.UUID:
guard let status = PeripheralService.Status.init(bigEndian: newValue)
else { return ATT.Error.InvalidAttributeValueLength }
// set new value
self.status = status.value.boolValue
default: fatalError("Writing to unknown characteristic \(UUID)")
}
return nil
}
}
| mit | cd51a05b7e172441905d67ab5e567072 | 28.445378 | 151 | 0.5879 | 4.92827 | false | false | false | false |
24/ios-o2o-c | gxc/OpenSource/ExSwift/Sequence.swift | 3 | 6464 | //
// Sequence.swift
// ExSwift
//
// Created by Colin Eberhardt on 24/06/2014.
// Copyright (c) 2014 pNre. All rights reserved.
//
import Foundation
internal extension SequenceOf {
/**
First element of the sequence.
:returns: First element of the sequence if present
*/
func first () -> T? {
var generator = self.generate()
return generator.next()
}
/**
Checks if call returns true for any element of self.
:param: call Function to call for each element
:returns: True if call returns true for any element of self
*/
func any (call: (T) -> Bool) -> Bool {
var generator = self.generate()
while let nextItem = generator.next() {
if call(nextItem) {
return true
}
}
return false
}
/**
Object at the specified index if exists.
:param: index
:returns: Object at index in sequence, nil if index is out of bounds
*/
func get (index: Int) -> T? {
var generator = self.generate()
for _ in 0..<(index - 1) {
generator.next()
}
return generator.next()
}
/**
Objects in the specified range.
:param: range
:returns: Subsequence in range
*/
func get (range: Range<Int>) -> SequenceOf<T> {
return self.skip(range.startIndex).take(range.endIndex - range.startIndex)
}
/**
Index of the first occurrence of item, if found.
:param: item The item to search for
:returns: Index of the matched item or nil
*/
func indexOf <U: Equatable> (item: U) -> Int? {
var index = 0
for current in self {
if let equatable = current as? U {
if equatable == item {
return index
}
}
index++
}
return nil
}
/**
Subsequence from n to the end of the sequence.
:param: n Number of elements to skip
:returns: Sequence from n to the end
*/
func skip (n: Int) -> SequenceOf<T> {
var generator = self.generate()
for _ in 0..<n {
generator.next()
}
return SequenceOf(generator)
}
/**
Filters the sequence only including items that match the test.
:param: include Function invoked to test elements for inclusion in the sequence
:returns: Filtered sequence
*/
func filter(include: (T) -> Bool) -> SequenceOf<T> {
return SequenceOf(lazy(self).filter(include))
}
/**
Opposite of filter.
:param: exclude Function invoked to test elements for exlcusion from the sequence
:returns: Filtered sequence
*/
func reject (exclude: (T -> Bool)) -> SequenceOf<T> {
return self.filter {
return !exclude($0)
}
}
/**
Skips the elements in the sequence up until the condition returns false.
:param: condition A function which returns a boolean if an element satisfies a given condition or not
:returns: Elements of the sequence starting with the element which does not meet the condition
*/
func skipWhile(condition:(T) -> Bool) -> SequenceOf<T> {
var generator = self.generate()
var checkingGenerator = self.generate()
var keepSkipping = true
while keepSkipping {
var nextItem = checkingGenerator.next()
keepSkipping = nextItem != nil ? condition(nextItem!) : false
if keepSkipping {
generator.next()
}
}
return SequenceOf(generator)
}
/**
Checks if self contains the item object.
:param: item The item to search for
:returns: true if self contains item
*/
func contains<T:Equatable> (item: T) -> Bool {
var generator = self.generate()
while let nextItem = generator.next() {
if nextItem as T == item {
return true
}
}
return false
}
/**
Returns the first n elements from self.
:param: n Number of elements to take
:returns: First n elements
*/
func take (n: Int) -> SequenceOf<T> {
return SequenceOf(TakeSequence(self, n))
}
/**
Returns the elements of the sequence up until an element does not meet the condition.
:param: condition A function which returns a boolean if an element satisfies a given condition or not.
:returns: Elements of the sequence up until an element does not meet the condition
*/
func takeWhile (condition:(T?) -> Bool) -> SequenceOf<T> {
return SequenceOf(TakeWhileSequence(self, condition))
}
}
/**
A sequence adapter that implements the 'take' functionality
*/
public struct TakeSequence<S: SequenceType>: SequenceType {
private let sequence: S
private let n: Int
public init(_ sequence: S, _ n: Int) {
self.sequence = sequence
self.n = n
}
public func generate() -> GeneratorOf<S.Generator.Element> {
var count = 0
var generator = self.sequence.generate()
return GeneratorOf<S.Generator.Element> {
count++
if count > self.n {
return nil
} else {
return generator.next()
}
}
}
}
/**
a sequence adapter that implements the 'takeWhile' functionality
*/
public struct TakeWhileSequence<S: SequenceType>: SequenceType {
private let sequence: S
private let condition: (S.Generator.Element?) -> Bool
public init(_ sequence:S, _ condition:(S.Generator.Element?) -> Bool) {
self.sequence = sequence
self.condition = condition
}
public func generate() -> GeneratorOf<S.Generator.Element> {
var generator = self.sequence.generate()
var endConditionMet = false
return GeneratorOf<S.Generator.Element> {
let next: S.Generator.Element? = generator.next()
if !endConditionMet {
endConditionMet = !self.condition(next)
}
if endConditionMet {
return nil
} else {
return next
}
}
}
}
| mit | f56342eb92473d6b317ed769e8f5ffda | 26.982684 | 110 | 0.55724 | 4.739003 | false | false | false | false |
Chaatz/iOSSwiftHelpers | Sources/UITextFieldExtension.swift | 1 | 2982 | //
// UITextFieldExtension.swift
// chaatz
//
// Created by Mingloan Chan on 3/11/17.
// Copyright © 2017 Chaatz. All rights reserved.
//
import UIKit
extension UITextField {
func truncate(_ maxLength: Int) -> Int {
guard let text = self.text else {
return 0
}
if text.hasPrefix(" ") || text.hasPrefix("\n") {
self.text = text.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
}
guard let trimmedText = self.text else {
return 0
}
var markedTextLength = 0
if let markedTextRange = markedTextRange {
markedTextLength = offset(from: markedTextRange.start, to: markedTextRange.end)
}
var count = 0
for character in trimmedText.characters {
// Skip Emoji Modifier Fitzpatrick Type 1-6
if (character.unicodeScalarCodePoint() >= 127995 && character.unicodeScalarCodePoint() <= 127999) {
continue
}
// Workaround for flags
let characterString = String(character)
let strEndIndex = "\(characterString.endIndex)"
if let charCount = Int(strEndIndex), charCount >= 4 {
let flagCount = charCount / 4
count += flagCount
} else {
count += 1
}
}
let length = count - markedTextLength
if length > maxLength {
var finalText = ""
count = 0
for character in trimmedText.characters {
let characterString = String(character)
// Skip Emoji Modifier Fitzpatrick Type 1-6
if (character.unicodeScalarCodePoint() >= 127995 && character.unicodeScalarCodePoint() <= 127999) {
finalText += characterString
continue
}
if count >= maxLength {
break
}
finalText += characterString
let strEndIndex = "\(characterString.endIndex)"
if let charCount = Int(strEndIndex), charCount >= 4 {
let flagCount = charCount / 4
count += flagCount
} else {
count += 1
}
}
self.text = finalText
return maxLength
}
else {
return length
}
}
func filterToLetters() -> Bool {
guard let text = self.text else { return false }
let nonAlphabetChars : Set<Character> = Set("abcdefghijklmnopqrstuvwxyz ABCDEFGHIJKLMNOPQRSTUVWXYZ".characters)
let filtered = String(text.characters.filter( { nonAlphabetChars.contains($0) } ))
self.text = filtered
return true
}
}
| mit | b25cdc29c84e36ecd27743dc072512c9 | 30.052083 | 119 | 0.504193 | 5.833659 | false | false | false | false |
zon/that-bus | ios/That Bus/AlamofireDataRequestExtension.swift | 1 | 2668 | import Foundation
import Alamofire
import SwiftyJSON
import PromiseKit
extension DataRequest {
func promiseJSON<S: Sequence>(statusCode: S) -> Promise<JSON> where S.Iterator.Element == Int {
log()
return Promise { fulfill, reject in
self.validate(statusCode: statusCode)
.validate(contentType: ["application/json"])
.responseData { response in
switch response.result {
case .success(let data):
let json = JSON(data: data)
fulfill(json)
case .failure(let error):
reject(error)
}
}
}
}
func promiseJSON() -> Promise<JSON> {
return promiseJSON(statusCode: 200..<300)
}
func responseDoc<D: DocProtocol>() -> Promise<D> {
log()
return Promise { fulfill, reject in
self.validate(statusCode: 200..<300)
.validate(contentType: ["application/json"])
.responseData { response in
switch response.result {
case .success(let data):
let json = JSON(data: data)
if let doc = D(json: json) {
fulfill(doc)
} else {
reject(DocResponseError.serialization(response: response, json: json))
}
case .failure(let error):
reject(error)
}
}
}
}
func responseOk<S: Sequence>(statusCode: S) -> Promise<Bool> where S.Iterator.Element == Int {
log()
return Promise { fulfill, reject in
self.validate(statusCode: statusCode)
.responseData { response in
switch response.result {
case .success:
fulfill(true)
case .failure(let error):
reject(error)
}
}
}
}
func responseOk() -> Promise<Bool> {
return responseOk(statusCode: 200..<300)
}
func log() {
if Settings.debug {
if let method = request?.httpMethod, let url = request?.url {
if let data = request?.httpBody, let body = String(data: data, encoding: String.Encoding.utf8) {
print(method, url, body)
} else {
print(method, url)
}
}
}
}
}
| gpl-3.0 | 2e6e9911e6ba2af1252b5e5b4640bf63 | 31.536585 | 112 | 0.454273 | 5.40081 | false | false | false | false |
zapdroid/RXWeather | Pods/RxCocoa/RxCocoa/Common/DelegateProxyType.swift | 1 | 11443 | //
// DelegateProxyType.swift
// RxCocoa
//
// Created by Krunoslav Zaher on 6/15/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
#if !os(Linux)
#if !RX_NO_MODULE
import RxSwift
#endif
/**
`DelegateProxyType` protocol enables using both normal delegates and Rx observable sequences with
views that can have only one delegate/datasource registered.
`Proxies` store information about observers, subscriptions and delegates
for specific views.
Type implementing `DelegateProxyType` should never be initialized directly.
To fetch initialized instance of type implementing `DelegateProxyType`, `proxyForObject` method
should be used.
This is more or less how it works.
+-------------------------------------------+
| |
| UIView subclass (UIScrollView) |
| |
+-----------+-------------------------------+
|
| Delegate
|
|
+-----------v-------------------------------+
| |
| Delegate proxy : DelegateProxyType +-----+----> Observable<T1>
| , UIScrollViewDelegate | |
+-----------+-------------------------------+ +----> Observable<T2>
| |
| +----> Observable<T3>
| |
| forwards events |
| to custom delegate |
| v
+-----------v-------------------------------+
| |
| Custom delegate (UIScrollViewDelegate) |
| |
+-------------------------------------------+
Since RxCocoa needs to automagically create those Proxys
..and because views that have delegates can be hierarchical
UITableView : UIScrollView : UIView
.. and corresponding delegates are also hierarchical
UITableViewDelegate : UIScrollViewDelegate : NSObject
.. and sometimes there can be only one proxy/delegate registered,
every view has a corresponding delegate virtual factory method.
In case of UITableView / UIScrollView, there is
extension UIScrollView {
public func createRxDelegateProxy() -> RxScrollViewDelegateProxy {
return RxScrollViewDelegateProxy(parentObject: base)
}
....
and override in UITableView
extension UITableView {
public override func createRxDelegateProxy() -> RxScrollViewDelegateProxy {
....
*/
public protocol DelegateProxyType: AnyObject {
/// Creates new proxy for target object.
static func createProxyForObject(_ object: AnyObject) -> AnyObject
/// Returns assigned proxy for object.
///
/// - parameter object: Object that can have assigned delegate proxy.
/// - returns: Assigned delegate proxy or `nil` if no delegate proxy is assigned.
static func assignedProxyFor(_ object: AnyObject) -> AnyObject?
/// Assigns proxy to object.
///
/// - parameter object: Object that can have assigned delegate proxy.
/// - parameter proxy: Delegate proxy object to assign to `object`.
static func assignProxy(_ proxy: AnyObject, toObject object: AnyObject)
/// Returns designated delegate property for object.
///
/// Objects can have multiple delegate properties.
///
/// Each delegate property needs to have it's own type implementing `DelegateProxyType`.
///
/// - parameter object: Object that has delegate property.
/// - returns: Value of delegate property.
static func currentDelegateFor(_ object: AnyObject) -> AnyObject?
/// Sets designated delegate property for object.
///
/// Objects can have multiple delegate properties.
///
/// Each delegate property needs to have it's own type implementing `DelegateProxyType`.
///
/// - parameter toObject: Object that has delegate property.
/// - parameter delegate: Delegate value.
static func setCurrentDelegate(_ delegate: AnyObject?, toObject object: AnyObject)
/// Returns reference of normal delegate that receives all forwarded messages
/// through `self`.
///
/// - returns: Value of reference if set or nil.
func forwardToDelegate() -> AnyObject?
/// Sets reference of normal delegate that receives all forwarded messages
/// through `self`.
///
/// - parameter forwardToDelegate: Reference of delegate that receives all messages through `self`.
/// - parameter retainDelegate: Should `self` retain `forwardToDelegate`.
func setForwardToDelegate(_ forwardToDelegate: AnyObject?, retainDelegate: Bool)
}
extension DelegateProxyType {
/// Returns existing proxy for object or installs new instance of delegate proxy.
///
/// - parameter object: Target object on which to install delegate proxy.
/// - returns: Installed instance of delegate proxy.
///
///
/// extension Reactive where Base: UISearchBar {
///
/// public var delegate: DelegateProxy {
/// return RxSearchBarDelegateProxy.proxyForObject(base)
/// }
///
/// public var text: ControlProperty<String> {
/// let source: Observable<String> = self.delegate.observe(#selector(UISearchBarDelegate.searchBar(_:textDidChange:)))
/// ...
/// }
/// }
public static func proxyForObject(_ object: AnyObject) -> Self {
MainScheduler.ensureExecutingOnScheduler()
let maybeProxy = Self.assignedProxyFor(object) as? Self
let proxy: Self
if let existingProxy = maybeProxy {
proxy = existingProxy
} else {
proxy = Self.createProxyForObject(object) as! Self
Self.assignProxy(proxy, toObject: object)
assert(Self.assignedProxyFor(object) === proxy)
}
let currentDelegate: AnyObject? = Self.currentDelegateFor(object)
if currentDelegate !== proxy {
proxy.setForwardToDelegate(currentDelegate, retainDelegate: false)
assert(proxy.forwardToDelegate() === currentDelegate)
Self.setCurrentDelegate(proxy, toObject: object)
assert(Self.currentDelegateFor(object) === proxy)
assert(proxy.forwardToDelegate() === currentDelegate)
}
return proxy
}
/// Sets forward delegate for `DelegateProxyType` associated with a specific object and return disposable that can be used to unset the forward to delegate.
/// Using this method will also make sure that potential original object cached selectors are cleared and will report any accidental forward delegate mutations.
///
/// - parameter forwardDelegate: Delegate object to set.
/// - parameter retainDelegate: Retain `forwardDelegate` while it's being set.
/// - parameter onProxyForObject: Object that has `delegate` property.
/// - returns: Disposable object that can be used to clear forward delegate.
public static func installForwardDelegate(_ forwardDelegate: AnyObject, retainDelegate: Bool, onProxyForObject object: AnyObject) -> Disposable {
weak var weakForwardDelegate: AnyObject? = forwardDelegate
let proxy = Self.proxyForObject(object)
assert(proxy.forwardToDelegate() === nil, "This is a feature to warn you that there is already a delegate (or data source) set somewhere previously. The action you are trying to perform will clear that delegate (data source) and that means that some of your features that depend on that delegate (data source) being set will likely stop working.\n" +
"If you are ok with this, try to set delegate (data source) to `nil` in front of this operation.\n" +
" This is the source object value: \(object)\n" +
" This this the original delegate (data source) value: \(proxy.forwardToDelegate()!)\n" +
"Hint: Maybe delegate was already set in xib or storyboard and now it's being overwritten in code.\n")
proxy.setForwardToDelegate(forwardDelegate, retainDelegate: retainDelegate)
return Disposables.create {
MainScheduler.ensureExecutingOnScheduler()
let delegate: AnyObject? = weakForwardDelegate
assert(delegate == nil || proxy.forwardToDelegate() === delegate, "Delegate was changed from time it was first set. Current \(String(describing: proxy.forwardToDelegate())), and it should have been \(proxy)")
proxy.setForwardToDelegate(nil, retainDelegate: retainDelegate)
}
}
}
#if os(iOS) || os(tvOS)
import UIKit
extension ObservableType {
func subscribeProxyDataSource<P: DelegateProxyType>(ofObject object: UIView, dataSource: AnyObject, retainDataSource: Bool, binding: @escaping (P, Event<E>) -> Void)
-> Disposable {
let proxy = P.proxyForObject(object)
let unregisterDelegate = P.installForwardDelegate(dataSource, retainDelegate: retainDataSource, onProxyForObject: object)
// this is needed to flush any delayed old state (https://github.com/RxSwiftCommunity/RxDataSources/pull/75)
object.layoutIfNeeded()
let subscription = self.asObservable()
.observeOn(MainScheduler())
.catchError { error in
bindingErrorToInterface(error)
return Observable.empty()
}
// source can never end, otherwise it would release the subscriber, and deallocate the data source
.concat(Observable.never())
.takeUntil(object.rx.deallocated)
.subscribe { [weak object] (event: Event<E>) in
if let object = object {
assert(proxy === P.currentDelegateFor(object), "Proxy changed from the time it was first set.\nOriginal: \(proxy)\nExisting: \(String(describing: P.currentDelegateFor(object)))")
}
binding(proxy, event)
switch event {
case let .error(error):
bindingErrorToInterface(error)
unregisterDelegate.dispose()
case .completed:
unregisterDelegate.dispose()
default:
break
}
}
return Disposables.create { [weak object] in
subscription.dispose()
object?.layoutIfNeeded()
unregisterDelegate.dispose()
}
}
}
#endif
#endif
| mit | 499d554361afcdce8a24c608516ce6b8 | 43.348837 | 362 | 0.57219 | 6.125268 | false | false | false | false |
lerigos/music-service | iOS_9/Pods/SwiftyVK/Source/SDK/Models/Arg.swift | 2 | 8749 | extension VK {
///Parameters for methods VK API
public enum Arg : String, Hashable {
case userIDs = "user_ids"
case fields
case nameCase = "name_case"
case q
case sort
case offset
case count
case city
case country
case hometown
case universityCountry = "university_country"
case university
case universityYear = "university_year"
case universityFaculty = "university_faculty"
case universityChair = "university_chair"
case sex
case status
case ageFrom = "age_from"
case ageTo = "age_to"
case birthDay = "birth_day"
case birthMonth = "birth_month"
case birthYear = "birth_year"
case online
case hasPhoto = "has_photo"
case schoolCountry = "school_country"
case schoolCity = "school_city"
case schoolClass = "school_class"
case school
case schoolYear = "school_year"
case religion
case interests
case company
case position
case groupId = "group_id"
case userId = "user_id"
case extended
case comment
case latitude
case longitude
case accuracy
case timeout
case radius
case groupIds = "group_ids"
case notSure = "not_sure"
case countryId = "country_id"
case future
case endDate = "end_date"
case reason
case commentVisible = "comment_visible"
case title
case description
case type
case order
case listId = "list_id"
case onlineMobile = "online_mobile"
case sourceUid = "source_uid"
case targetUid = "target_uid"
case targetUids = "target_uids"
case needMutual = "need_mutual"
case out
case suggested
case text
case listIds = "list_ids"
case name
case addUserIds = "add_user_ids"
case deleteUserIds = "delete_user_ids"
case phones
case needSign = "need_sign"
case ownerId = "owner_id"
case domain
case query
case ownersOnly = "owners_only"
case posts
case copyHistoryDepth = "copy_history_depth"
case friendsOnly = "friends_only"
case fromGroup = "from_group"
case message
case attachments
case services
case signed
case publishDate = "publish_date"
case lat
case long
case placeId = "place_id"
case postId = "post_id"
case object
case needLikes = "need_likes"
case previewLength = "preview_length"
case replyToComment = "reply_to_comment"
case stickerId = "sticker_id"
case commentId = "comment_id"
case commentPrivacy = "comment_privacy"
case privacy
case albumIds = "album_ids"
case needSystem = "need_system"
case needCovers = "need_covers"
case photoSizes = "photo_sizes"
case rev
case feedType = "feed_type"
case feed
case photos
case chatId = "chat_id"
case cropX = "crop_x"
case cropY = "crop_y"
case cropWidth = "crop_width"
case server
case hash
case photo
case photoId = "photo_id"
case startTime = "start_time"
case endTime = "end_time"
case photosList = "photos_list"
case caption
case accessKey = "access_key"
case access
case targetAlbumId = "target_album_id"
case albumId = "album_id"
case before
case after
case noServiceAlbums = "no_service_albums"
case tagId = "tag_id"
case x
case y
case x2
case y2
case videos
case width
case videoId = "video_id"
case desc
case privacyView = "privacy_view"
case privacyComment = "privacy_comment"
case `repeat`
case isPrivate = "is_private"
case wallpost
case link
case hd
case adult
case searchOwn = "search_own"
case longer
case shorter
case videoIds = "video_ids"
case taggedName = "tagged_name"
case searchQuery = "search_query"
case audioIds = "audio_ids"
case needUser = "need_user"
case audios
case lyricsId = "lyrics_id"
case autoComplete = "auto_complete"
case lyrics
case performerOnly = "performer_only"
case audio
case audioId = "audio_id"
case artist
case genreId = "genre_id"
case noSearch = "no_search"
case targetIds = "target_ids"
case active
case targetAudio = "target_audio"
case shuffle
case onlyEng = "only_eng"
case timeOffset = "time_offset"
case lastMessageId = "last_message_id"
case unread
case messageIds = "message_ids"
case startMessageId = "start_message_id"
case guid
case forwardMessages = "forward_messages"
case peerId = "peer_id"
case important
case useSsl = "use_ssl"
case needPts = "need_pts"
case ts
case pts
case onlines
case eventsLimit = "events_limit"
case msgsLimit = "msgs_limit"
case maxMsgId = "max_msg_id"
case chatIds = "chat_ids"
case limit
case file
case returnBanned = "return_banned"
case maxPhotos = "max_photos"
case sourceIds = "source_ids"
case startFrom = "start_from"
case nextFrom = "next_from"
case reposts
case lastCommentsCount = "last_comments_count"
case itemId = "item_id"
case noReposts = "no_reposts"
case pageUrl = "page_url"
case key
case keys
case global
case value
case voip
case contacts
case myContact
case returnAll = "return_all"
case token
case deviceModel = "device_model"
case systemVersion = "system_version"
case noText = "no_text"
case subscribe
case sound
case intro
case restoreSid = "restore_sid"
case changePasswordHash = "change_password_hash"
case oldPassword = "old_password"
case newPassword = "new_password"
case firstName = "first_name"
case lastName = "last_name"
case maidenName = "maiden_name"
case cancelRequestId = "cancel_request_id"
case relation
case relationPartnerId = "relation_partner_id"
case bdate
case bdateVisibility = "bdate_visibility"
case homeTown = "home_town"
case cityId = "city_id"
case phone
case clientId = "client_id"
case clientSecret = "client_secret"
case code
case password
case testMode = "test_mode"
case voice
case sid
case sitePreview = "site_preview"
case needSource = "need_source"
case needHtml = "need_html"
case pageId = "page_id"
case view
case edit
case versionId = "version_id"
case topicIds = "topic_ids"
case preview
case topicId = "topic_id"
case noteIds = "note_ids"
case noteId = "note_id"
case needWiki = "need_wiki"
case replyTo = "reply_to"
case address
case places
case timestamp
case needPlaces = "need_places"
case isBoard = "is_board"
case pollId = "poll_id"
case answerId = "answer_id"
case answerIds = "answer_ids"
case question
case isAnonymous = "is_anonymous"
case addAnswers = "add_answers"
case editAnswers = "edit_answers"
case deleteAnswers = "delete_answers"
case docs
case tags
case docId = "doc_id"
case from
case appId = "app_id"
case dateFrom = "date_from"
case dateTo = "date_to"
case searchGlobal = "search_global"
case platform
case returnFriends = "return_friends"
case url
case needAll = "need_all"
case streetIds = "street_ids"
case countryIds = "country_ids"
case regionId = "region_id"
case cityIds = "city_ids"
case universityId = "university_id"
case facultyId = "faculty_id"
case captcha = "captcha.force"
case captchaSid = "captcha_sid"
case captchaKey = "captcha_key"
case screenName = "screen_name"
case appIDs = "app_ids"
case mainPhoto = "main_photo"
case cropData = "crop_data"
case cropHash = "crop_hash"
case website
case subject
case email
case rss
case eventStartDate = "event_start_date"
case eventFinishDate = "event_finish_date"
case eventGroupId = "event_group_id"
case publicCategory = "public_category"
case publicSubcategory = "public_subcategory"
case publicDate = "public_date"
case wall
case topics
case video
case links
case events
case wiki
case messages
case ageLimits = "age_limits"
case market
case marketComments = "market_comments"
case marketCountry = "market_country"
case marketCity = "market_city"
case marketCurrency = "market_currency"
case marketContact = "market_contact"
case marketWiki = "market_wiki"
case obsceneFilter = "obscene_filter"
case obsceneStopwords = "obscene_stopwords"
case obsceneWords = "obscene_words"
case subcategories
case randomId = "random_id"
public var hashValue : Int {
return self.rawValue.hashValue
}
}
}
public func == (lhs: VK.Arg, rhs: VK.Arg) -> Bool {
return lhs.rawValue == rhs.rawValue
} | apache-2.0 | eab8004bc4ecd3c074feb3ba74273bf1 | 26.089783 | 52 | 0.649217 | 3.815526 | false | false | false | false |
bshyong/tasty-board | Keyboard/KeyboardModel.swift | 1 | 4584 | //
// KeyboardModel.swift
// TransliteratingKeyboard
//
// Created by Alexei Baboulevitch on 7/10/14.
// Copyright (c) 2014 Apple. All rights reserved.
//
import Foundation
var counter = 0
class Keyboard {
var pages: [Page]
init() {
self.pages = []
}
func addKey(key: Key, row: Int, page: Int) {
if self.pages.count <= page {
for i in self.pages.count...page {
self.pages.append(Page())
}
}
self.pages[page].addKey(key, row: row)
}
}
class Page {
var rows: [[Key]]
init() {
self.rows = []
}
func addKey(key: Key, row: Int) {
if self.rows.count <= row {
for i in self.rows.count...row {
self.rows.append([])
}
}
self.rows[row].append(key)
}
}
class Key: Hashable {
enum KeyType {
case Character
case SpecialCharacter
case Shift
case Backspace
case ModeChange
case KeyboardChange
case Period
case Space
case Return
case Settings
case Other
}
var type: KeyType
var uppercaseKeyCap: String?
var lowercaseKeyCap: String?
var uppercaseOutput: String?
var lowercaseOutput: String?
var toMode: Int? //if the key is a mode button, this indicates which page it links to
var isCharacter: Bool {
get {
switch self.type {
case
.Character,
.SpecialCharacter,
.Period:
return true
default:
return false
}
}
}
var isSpecial: Bool {
get {
switch self.type {
case .Shift:
return true
case .Backspace:
return true
case .ModeChange:
return true
case .KeyboardChange:
return true
case .Return:
return true
case .Space:
return true
case .Settings:
return true
default:
return false
}
}
}
var hasOutput: Bool {
get {
return (self.uppercaseOutput != nil) || (self.lowercaseOutput != nil)
}
}
// TODO: this is kind of a hack
var hashValue: Int
init(_ type: KeyType) {
self.type = type
self.hashValue = counter
counter += 1
}
convenience init(_ key: Key) {
self.init(key.type)
self.uppercaseKeyCap = key.uppercaseKeyCap
self.lowercaseKeyCap = key.lowercaseKeyCap
self.uppercaseOutput = key.uppercaseOutput
self.lowercaseOutput = key.lowercaseOutput
self.toMode = key.toMode
}
func setLetter(letter: String) {
self.lowercaseOutput = (letter as NSString).lowercaseString
self.uppercaseOutput = (letter as NSString).uppercaseString
self.lowercaseKeyCap = self.lowercaseOutput
self.uppercaseKeyCap = self.uppercaseOutput
}
func outputForCase(uppercase: Bool) -> String {
if uppercase {
if self.uppercaseOutput != nil {
return self.uppercaseOutput!
}
else if self.lowercaseOutput != nil {
return self.lowercaseOutput!
}
else {
return ""
}
}
else {
if self.lowercaseOutput != nil {
return self.lowercaseOutput!
}
else if self.uppercaseOutput != nil {
return self.uppercaseOutput!
}
else {
return ""
}
}
}
func keyCapForCase(uppercase: Bool) -> String {
if uppercase {
if self.uppercaseKeyCap != nil {
return self.uppercaseKeyCap!
}
else if self.lowercaseKeyCap != nil {
return self.lowercaseKeyCap!
}
else {
return ""
}
}
else {
if self.lowercaseKeyCap != nil {
return self.lowercaseKeyCap!
}
else if self.uppercaseKeyCap != nil {
return self.uppercaseKeyCap!
}
else {
return ""
}
}
}
}
func ==(lhs: Key, rhs: Key) -> Bool {
return lhs.hashValue == rhs.hashValue
}
| bsd-3-clause | cc5da9e5a01cc6fd2f4e07843a77d2af | 22.751295 | 89 | 0.486257 | 5.110368 | false | false | false | false |
lquigley/Game | Game/Game/SpriteKit/Nodes/SKYBaddie.swift | 1 | 1207 | //
// SKYBaddie.swift
// Sky High
//
// Created by Luke Quigley on 2/20/15.
// Copyright (c) 2015 VOKAL. All rights reserved.
//
import SpriteKit
enum SKYBaddieDirection : Int {
case Left
case Right
}
class SKYBaddie: SKSpriteNode {
var direction:SKYBaddieDirection!
override init(texture: SKTexture!, color: UIColor!, size: CGSize) {
super.init(texture: texture, color: color, size: size)
self.name = "BadNode"
let intDirection = arc4random_uniform(2)
switch intDirection {
case 0:
direction = SKYBaddieDirection.Left
break
default:
direction = SKYBaddieDirection.Right
break
}
self.physicsBody = SKPhysicsBody(circleOfRadius: CGRectGetWidth(self.frame) / 2)
self.physicsBody!.allowsRotation = true
self.physicsBody!.density = 400
self.physicsBody!.categoryBitMask = 0x3
self.physicsBody!.collisionBitMask = 0x1
}
var velocity:CGFloat {
get {
return 0
}
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
}
| mit | f7baded841efc6180cf5e410ae1223e1 | 21.773585 | 88 | 0.589892 | 4.520599 | false | false | false | false |
mathiasquintero/Sweeft | Sources/Sweeft/Extensions/Date.swift | 3 | 4229 | //
// Date.swift
//
// Created by Mathias Quintero on 11/20/16.
// Copyright © 2016 Mathias Quintero. All rights reserved.
//
import Foundation
public enum Weekday: Int {
case sunday, monday, tuesday, wednesday, thursday, friday, saturday
var index: Int {
return rawValue
}
}
extension Weekday: Defaultable {
/// Default Value
public static var defaultValue: Weekday = .sunday
}
public enum Month: Int {
case january, february, march, april, may, june, july, august, september, october, november, december
var index: Int {
return rawValue
}
}
extension Month: Defaultable {
/// Default Value
public static var defaultValue: Month = .january
}
public extension Date {
/**
Will turn a Date into a readable format
- Parameter format: format in which you want the date (Optional: default is "dd.MM.yyyy hh:mm:ss a")
- Returns: String representation of the date
*/
func string(using format: String = "dd.MM.yyyy hh:mm:ss a") -> String {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = format
return dateFormatter.string(from: self)
}
private func getValue(for unit: Calendar.Component) -> Int {
let calendar = Calendar(identifier: .gregorian)
let value = calendar.dateComponents([unit], from: self).value(for: unit)
return value.?
}
static var now: Date {
return Date()
}
var nanosecond: Int {
return getValue(for: .nanosecond)
}
var second: Int {
return getValue(for: .second)
}
var minute: Int {
return getValue(for: .minute)
}
var hour: Int {
return getValue(for: .hour)
}
var day: Int {
return getValue(for: .day)
}
var weekday: Weekday {
return Weekday.init(rawValue: getValue(for: .weekday) - 1).?
}
var week: Int {
return getValue(for: .weekOfYear)
}
var weekOfMonth: Int {
return getValue(for: .weekOfMonth)
}
var month: Month {
return Month.init(rawValue: getValue(for: .month) - 1).?
}
var year: Int {
return getValue(for: .year)
}
}
extension Date: Defaultable {
/// Default Value
public static var defaultValue: Date {
return .now
}
}
/// Struct representing a difference between two dates
public struct DateDifference {
/// Left date
let first: Date
/// Right date
let second: Date
private func difference(by granularity: Calendar.Component) -> Int {
let calendar = Calendar(identifier: .gregorian)
let set = [granularity].set
let components = calendar.dateComponents(set, from: second, to: first)
return components.value(for: granularity).?
}
/// Regular TimeInterval between the two dates
public var timeInterval: TimeInterval {
return first.timeIntervalSince(second)
}
/// The change in timezones
public var timeZones: Int {
return difference(by: .timeZone)
}
/// The difference in nanoseconds
public var nanoSeconds: Int {
return difference(by: .nanosecond)
}
/// The difference in seconds
public var seconds: Int {
return difference(by: .second)
}
/// The difference in minutes
public var minutes: Int {
return difference(by: .minute)
}
/// The difference in hours
public var hours: Int {
return difference(by: .hour)
}
/// The difference in days
public var days: Int {
return difference(by: .day)
}
/// The difference in weeks
public var weeks: Int {
return difference(by: .weekOfYear)
}
/// The difference in years
public var years: Int {
return difference(by: .year)
}
/// The difference in millenia. For some reason
public var millenia: Int {
return years / 1000
}
}
extension Date: Serializable {
/// JSON Value
public var json: JSON {
return .string(string())
}
}
| mit | 928f98eb6615fa412355fbadf143a82b | 21.136126 | 105 | 0.59106 | 4.417973 | false | false | false | false |
MrAlek/JSQDataSourcesKit | Source/Section.swift | 1 | 2870 | //
// Created by Jesse Squires
// http://www.jessesquires.com
//
//
// Documentation
// http://jessesquires.com/JSQDataSourcesKit
//
//
// GitHub
// https://github.com/jessesquires/JSQDataSourcesKit
//
//
// License
// Copyright © 2015 Jesse Squires
// Released under an MIT license: http://opensource.org/licenses/MIT
//
/// An instance conforming to `SectionInfoProtocol` represents a section of items.
public protocol SectionInfoProtocol {
// MARK: Associated types
/// The type of elements stored in the section.
associatedtype Item
// MARK: Properties
/// The elements in the section.
var items: [Item] { get set }
/// The header title for the section.
var headerTitle: String? { get }
/// The footer title for the section.
var footerTitle: String? { get }
}
/**
A `Section` is a concrete `SectionInfoProtocol` type.
A section instance is responsible for managing the elements in a section.
*/
public struct Section <Item>: SectionInfoProtocol, CustomStringConvertible {
// MARK: Properties
/// The elements in the section.
public var items: [Item]
/// The header title for the section.
public let headerTitle: String?
/// The footer title for the section.
public let footerTitle: String?
/// The number of elements in the section.
public var count: Int {
return items.count
}
// MARK: Initialization
/**
Constructs a new section.
- parameter items: The elements in the section.
- parameter headerTitle: The section header title.
- parameter footerTitle: The section footer title.
- returns: A new `Section` instance.
*/
public init(items: Item..., headerTitle: String? = nil, footerTitle: String? = nil) {
self.init(items, headerTitle: headerTitle, footerTitle: footerTitle)
}
/**
Constructs a new section.
- parameter items: The elements in the section.
- parameter headerTitle: The section header title.
- parameter footerTitle: The section footer title.
- returns: A new `Section` instance.
*/
public init(_ items: [Item], headerTitle: String? = nil, footerTitle: String? = nil) {
self.items = items
self.headerTitle = headerTitle
self.footerTitle = footerTitle
}
// MARK: Subscripts
/**
- parameter index: The index of the item to return.
- returns: The item at `index`.
*/
public subscript (index: Int) -> Item {
get {
return items[index]
}
set {
items[index] = newValue
}
}
// MARK: CustomStringConvertible
/// :nodoc:
public var description: String {
get {
return "<\(Section.self): headerTitle=\(headerTitle); footerTitle=\(footerTitle); items=\(items)>"
}
}
}
| mit | 449db336dea268706dcc2ddc328fad3c | 22.710744 | 110 | 0.630533 | 4.568471 | false | false | false | false |
teaxus/TSAppEninge | Source/Tools/JSON:XML/JSONTool.swift | 1 | 3012 | //
// JSONTool.swift
// TSAppEngine
//
// Created by teaxus on 15/11/25.
// Copyright © 2015年 teaxus. All rights reserved.
//
import Foundation
extension String{
public func ObjectFromString() throws->AnyObject?{
guard let jsonData = self.data(using: String.Encoding.utf8) else{
throw JsonError.StringCannotToData
}
do{
let will_return = try JSONSerialization.jsonObject(with: jsonData, options: JSONSerialization.ReadingOptions.allowFragments)
return will_return as AnyObject?
}
catch let error{
throw error
}
}
}
extension Data{
public func ObjectFromData() throws->AnyObject?{
do{
let will_return = try JSONSerialization.jsonObject(with: self, options: JSONSerialization.ReadingOptions.allowFragments)
return will_return as AnyObject?
}
catch let error{
throw error
}
}
}
public extension Array{
public func DataFromObject() throws->Data?{
do{
let will_return = try JSONSerialization.data(withJSONObject: self as AnyObject, options: JSONSerialization.WritingOptions.prettyPrinted)
return will_return
}
catch let error{
throw error
}
}
public func StringFromObject() throws->String?{
do{
guard let data_tmp = try self.DataFromObject() else{
throw JsonError.ObjectCanntoToData
}
return String(data: data_tmp, encoding: String.Encoding.utf8)
}
catch let error{
throw error
}
}
}
extension Dictionary{
public func DataFromObject() throws->Data?{
do{
let will_return = try JSONSerialization.data(withJSONObject: self, options: JSONSerialization.WritingOptions.prettyPrinted)
return will_return
}
catch let error{
throw error
}
}
public func StringFromObject() throws->String?{
do{
guard let data_tmp = try self.DataFromObject() else{
throw JsonError.ObjectCanntoToData
}
return String(data: data_tmp, encoding: String.Encoding.utf8)
}
catch let error{
throw error
}
}
}
extension NSDictionary{
public func DataFromObject() throws->Data?{
do{
let will_return = try JSONSerialization.data(withJSONObject: self, options: JSONSerialization.WritingOptions.prettyPrinted)
return will_return
}
catch let error{
throw error
}
}
public func StringFromObject() throws->String?{
do{
guard let data_tmp = try self.DataFromObject() else{
throw JsonError.ObjectCanntoToData
}
return String(data: data_tmp as Data, encoding: String.Encoding.utf8)
}
catch let error{
throw error
}
}
}
| mit | e8b343a59ac55975c6ee86104c422590 | 26.605505 | 148 | 0.590562 | 4.88474 | false | false | false | false |
sachinvas/Swifter | Source/Extensions/StringExtensions.swift | 1 | 18596 | //
// StringExtensions.swift
// SwifterSwift
//
// Created by Omar Albeik on 8/5/16.
// Copyright © 2016 Omar Albeik. All rights reserved.
//
import Foundation
import UIKit
// MARK: - Properties
public extension String {
/// SwifterSwift: String decoded from base64 (if applicable).
public var base64Decoded: String? {
// https://github.com/Reza-Rg/Base64-Swift-Extension/blob/master/Base64.swift
guard let decodedData = Data(base64Encoded: self) else {
return nil
}
return String(data: decodedData, encoding: .utf8)
}
/// SwifterSwift: String encoded in base64 (if applicable).
public var base64Encoded: String? {
// https://github.com/Reza-Rg/Base64-Swift-Extension/blob/master/Base64.swift
let plainData = self.data(using: .utf8)
return plainData?.base64EncodedString()
}
/// SwifterSwift: CamelCase of string.
public var camelCased: String {
let source = lowercased()
if source.characters.contains(" ") {
let first = source.substring(to: source.index(after: source.startIndex))
let camel = source.capitalized.replacing(" ", with: "").replacing("\n", with: "")
let rest = String(camel.characters.dropFirst())
return "\(first)\(rest)"
} else {
let first = source.lowercased().substring(to: source.index(after: source.startIndex))
let rest = String(source.characters.dropFirst())
return "\(first)\(rest)"
}
}
/// SwifterSwift: Check if string contains one or more emojis.
public var containEmoji: Bool {
// http://stackoverflow.com/questions/30757193/find-out-if-character-in-string-is-emoji
for scalar in unicodeScalars {
switch scalar.value {
case 0x3030, 0x00AE, 0x00A9, // Special Characters
0x1D000...0x1F77F, // Emoticons
0x2100...0x27BF, // Misc symbols and Dingbats
0xFE00...0xFE0F, // Variation Selectors
0x1F900...0x1F9FF: // Supplemental Symbols and Pictographs
return true
default:
continue
}
}
return false
}
/// SwifterSwift: First character of string (if applicable).
public var firstCharacter: String? {
return Array(characters).map({String($0)}).first
}
/// SwifterSwift: Check if string contains one or more letters.
public var hasLetters: Bool {
return rangeOfCharacter(from: .letters, options: .numeric, range: nil) != nil
}
/// SwifterSwift: Check if string contains one or more numbers.
public var hasNumbers: Bool {
return rangeOfCharacter(from: .decimalDigits, options: .literal, range: nil) != nil
}
/// SwifterSwift: Check if string contains only letters.
public var isAlphabetic: Bool {
return hasLetters && !hasNumbers
}
/// SwifterSwift: Check if string contains at least one letter and one number.
public var isAlphaNumeric: Bool {
return components(separatedBy: CharacterSet.alphanumerics).joined(separator: "").characters.count == 0 && hasLetters && hasNumbers
}
/// SwifterSwift: Check if string is valid email format.
public var isEmail: Bool {
// http://stackoverflow.com/questions/25471114/how-to-validate-an-e-mail-address-in-swift
let emailRegEx = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}"
let emailTest = NSPredicate(format:"SELF MATCHES %@", emailRegEx)
return emailTest.evaluate(with: self)
}
/// SwifterSwift: Check if string is https URL.
public var isHttpsUrl: Bool {
guard start(with: "https://".lowercased()) else {
return false
}
return URL(string: self) != nil
}
/// SwifterSwift: Check if string is http URL.
public var isHttpUrl: Bool {
guard start(with: "http://".lowercased()) else {
return false
}
return URL(string: self) != nil
}
/// SwifterSwift: Check if string contains only numbers.
public var isNumeric: Bool {
return !hasLetters && hasNumbers
}
/// SwifterSwift: Last character of string (if applicable).
public var lastCharacter: String? {
guard let last = characters.last else {
return nil
}
return String(last)
}
/// SwifterSwift: Latinized string.
public var latinized: String {
return folding(options: .diacriticInsensitive, locale: Locale.current)
}
/// SwifterSwift: Array of strings separated by new lines.
public var lines: [String] {
var result:[String] = []
enumerateLines { (line, stop) -> () in
result.append(line)
}
return result
}
/// SwifterSwift: The most common character in string.
public var mostCommonCharacter: String {
var mostCommon = ""
let charSet = Set(withoutSpacesAndNewLines.characters.map{String($0)})
var count = 0
for string in charSet {
if self.count(of: string) > count {
count = self.count(of: string)
mostCommon = string
}
}
return mostCommon
}
/// SwifterSwift: Reversed string.
public var reversed: String {
return String(characters.reversed())
}
/// SwifterSwift: Bool value from string (if applicable).
public var bool: Bool? {
let selfLowercased = self.trimmed.lowercased()
if selfLowercased == "true" || selfLowercased == "1" {
return true
} else if selfLowercased == "false" || selfLowercased == "0" {
return false
} else {
return nil
}
}
/// SwifterSwift: Date object from "yyyy-MM-dd" formatted string
public var date: Date? {
let selfLowercased = self.trimmed.lowercased()
let formatter = DateFormatter()
formatter.timeZone = TimeZone.current
formatter.dateFormat = "yyyy-MM-dd"
return formatter.date(from: selfLowercased)
}
/// SwifterSwift: Date object from "yyyy-MM-dd HH:mm:ss" formatted string.
public var dateTime: Date? {
let selfLowercased = self.trimmed.lowercased()
let formatter = DateFormatter()
formatter.timeZone = TimeZone.current
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
return formatter.date(from: selfLowercased)
}
/// SwifterSwift: Double value from string (if applicable).
public var double: Double? {
let formatter = NumberFormatter()
return formatter.number(from: self) as? Double
}
/// SwifterSwift: Float value from string (if applicable).
public var float: Float? {
let formatter = NumberFormatter()
return formatter.number(from: self) as? Float
}
/// SwifterSwift: Float32 value from string (if applicable).
public var float32: Float32? {
let formatter = NumberFormatter()
return formatter.number(from: self) as? Float32
}
/// SwifterSwift: Float64 value from string (if applicable).
public var float64: Float64? {
let formatter = NumberFormatter()
return formatter.number(from: self) as? Float64
}
/// SwifterSwift: Integer value from string (if applicable).
public var int: Int? {
return Int(self)
}
/// SwifterSwift: Int16 value from string (if applicable).
public var int16: Int16? {
return Int16(self)
}
/// SwifterSwift: Int32 value from string (if applicable).
public var int32: Int32? {
return Int32(self)
}
/// SwifterSwift: Int64 value from string (if applicable).
public var int64: Int64? {
return Int64(self)
}
/// SwifterSwift: Int8 value from string (if applicable).
public var int8: Int8? {
return Int8(self)
}
/// SwifterSwift: URL from string (if applicable).
public var url: URL? {
return URL(string: self)
}
/// SwifterSwift: String with no spaces or new lines in beginning and end.
public var trimmed: String {
return trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
}
/// SwifterSwift: Array with unicodes for all characters in a string.
public var unicodeArray: [Int] {
return unicodeScalars.map({$0.hashValue})
}
/// SwifterSwift: Readable string from a URL string.
public var urlDecoded: String {
return removingPercentEncoding ?? self
}
/// SwifterSwift: URL escaped string.
public var urlEncoded: String {
return addingPercentEncoding(withAllowedCharacters: .urlHostAllowed) ?? self
}
/// SwifterSwift: String without spaces and new lines.
public var withoutSpacesAndNewLines: String {
return replacing(" ", with: "").replacing("\n", with: "")
}
}
// MARK: - Methods
public extension String {
/// SwifterSwift: Subscript string with index.
///
/// - Parameter i: index.
public subscript(i: Int) -> String? {
guard i >= 0 && i < characters.count else {
return nil
}
return String(self[index(startIndex, offsetBy: i)])
}
/// SwifterSwift: Subscript string within a half-open range.
///
/// - Parameter range: Half-open range.
public subscript(range: CountableRange<Int>) -> String? {
guard let lowerIndex = index(startIndex, offsetBy: max(0,range.lowerBound), limitedBy: endIndex) else {
return nil
}
guard let upperIndex = index(lowerIndex, offsetBy: range.upperBound - range.lowerBound, limitedBy: endIndex) else {
return nil
}
return self[lowerIndex..<upperIndex]
}
/// SwifterSwift: Subscript string within a closed range.
///
/// - Parameter range: Closed range.
public subscript(range: ClosedRange<Int>) -> String? {
guard let lowerIndex = index(startIndex, offsetBy: max(0,range.lowerBound), limitedBy: endIndex) else {
return nil
}
guard let upperIndex = index(lowerIndex, offsetBy: range.upperBound - range.lowerBound + 1, limitedBy: endIndex) else {
return nil
}
return self[lowerIndex..<upperIndex]
}
/// SwifterSwift: Copy string to global pasteboard.
func copyToPasteboard() {
UIPasteboard.general.string = self
}
/// SwifterSwift: Converts string format to CamelCase.
public mutating func camelize() {
self = camelCased
}
/// SwifterSwift: Check if string contains one or more instance of substring.
///
/// - Parameters:
/// - string: substring to search for.
/// - caseSensitive: set true for case sensitive search (default is true).
/// - Returns: true if string contains one or more instance of substring.
public func contain(_ string: String, caseSensitive: Bool = true) -> Bool {
if !caseSensitive {
return range(of: string, options: .caseInsensitive) != nil
}
return range(of: string) != nil
}
/// SwifterSwift: Count of substring in string.
///
/// - Parameters:
/// - string: substring to search for.
/// - caseSensitive: set true for case sensitive search (default is true).
/// - Returns: count of substring in string.
public func count(of string: String, caseSensitive: Bool = true) -> Int {
if !caseSensitive {
return lowercased().components(separatedBy: string).count - 1
}
return components(separatedBy: string).count - 1
}
/// SwifterSwift: Check if string ends with substring.
///
/// - Parameters:
/// - suffix: substring to search if string ends with.
/// - caseSensitive: set true for case sensitive search (default is true).
/// - Returns: true if string ends with substring.
public func end(with suffix: String, caseSensitive: Bool = true) -> Bool {
if !caseSensitive {
return lowercased().hasSuffix(suffix.lowercased())
}
return hasSuffix(suffix)
}
/// SwifterSwift: First index of substring in string.
///
/// - Parameter string: substring to search for.
/// - Returns: first index of substring in string (if applicable).
public func firstIndex(of string: String) -> Int? {
return Array(self.characters).map({String($0)}).index(of: string)
}
/// SwifterSwift: Latinize string.
public mutating func latinize() {
self = latinized
}
/// SwifterSwift: Random string of given length.
///
/// - Parameter ofLength: number of characters in string.
/// - Returns: random string of given length.
public static func random(ofLength: Int) -> String {
var string = ""
guard ofLength > 0 else {
return string
}
let base = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
for _ in 0..<ofLength {
let randomIndex = arc4random_uniform(UInt32(base.characters.count))
string += "\(base[base.index(base.startIndex, offsetBy: IndexDistance(randomIndex))])"
}
return string
}
/// SwifterSwift: String by replacing part of string with another string.
///
/// - Parameters:
/// - substring: old substring to find and replace
/// - newString: new string to insert in old string place
/// - Returns: string after replacing substring with newString
public func replacing(_ substring: String, with newString: String) -> String {
return replacingOccurrences(of: substring, with: newString)
}
/// SwifterSwift: Reverse string.
public mutating func reverse() {
self = String(characters.reversed())
}
/// SwifterSwift: Array of strings separated by given string.
///
/// - Parameter separator: separator to split string by.
/// - Returns: array of strings separated by given string.
public func splited(by separator: Character) -> [String] {
return characters.split{$0 == separator}.map(String.init)
}
/// SwifterSwift: Check if string starts with substring.
///
/// - Parameters:
/// - suffix: substring to search if string starts with.
/// - caseSensitive: set true for case sensitive search (default is true).
/// - Returns: true if string starts with substring.
public func start(with prefix: String, caseSensitive: Bool = true) -> Bool {
if !caseSensitive {
return lowercased().hasPrefix(prefix.lowercased())
}
return hasPrefix(prefix)
}
/// SwifterSwift: Date object from string of date format.
///
/// - Parameter format: date format
/// - Returns: Date object from string (if applicable).
public func date(withFormat format: String) -> Date? {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = format
return dateFormatter.date(from: self)
}
/// SwifterSwift: Removes spaces and new lines in beginning and end of string.
public mutating func trim() {
self = trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
}
/// SwifterSwift: Truncate string (cut it to a given number of characters).
///
/// - Parameters:
/// - toLength: maximum number of charachters before cutting.
/// - trailing: string to add at the end of truncated string.
public mutating func truncate(toLength: Int, trailing: String? = "...") {
guard toLength > 0 else {
return
}
if self.characters.count > toLength {
self = self.substring(to: self.index(startIndex, offsetBy: toLength)) + (trailing ?? "")
}
}
/// SwifterSwift: Truncated string (limited to a given number of characters).
/// Truncated string (cut to a given number of characters).
///
/// - Parameters:
/// - toLength: maximum number of charachters before cutting.
/// - trailing: string to add at the end of truncated string.
/// - Returns: truncated string (this is an exa...).
public func truncated(toLength: Int, trailing: String? = "...") -> String {
guard self.characters.count > toLength, toLength > 0 else {
return self
}
return self.substring(to: self.index(startIndex, offsetBy: toLength)) + (trailing ?? "")
}
/// SwifterSwift: Convert URL string to readable string.
public mutating func urlDecode() {
self = removingPercentEncoding ?? self
}
/// SwifterSwift: Escape string.
public mutating func urlEncode() {
self = addingPercentEncoding(withAllowedCharacters: .urlHostAllowed) ?? self
}
}
// MARK: - Operators
public extension String {
/// SwifterSwift: Repeat string multiple times.
///
/// - Parameters:
/// - lhs: string to repeat.
/// - rhs: number of times to repeat character.
/// - Returns: string with character repeated n times.
static public func * (lhs: String, rhs: Int) -> String {
var newString = ""
for _ in 0 ..< rhs {
newString += lhs
}
return newString
}
/// SwifterSwift: Repeat string multiple times.
///
/// - Parameters:
/// - lhs: number of times to repeat character.
/// - rhs: string to repeat.
/// - Returns: string with character repeated n times.
static public func * (lhs: Int, rhs: String) -> String {
var newString = ""
for _ in 0 ..< lhs {
newString += rhs
}
return newString
}
}
// MARK: - Initializers
public extension String {
/// SwifterSwift: Create a new string from a base64 string (if applicable).
///
/// - Parameter base64: base64 string.
init?(base64: String) {
if let str = base64.base64Decoded {
self.init(str)
return
}
return nil
}
}
// MARK: - NSAttributedString extensions
public extension String {
/// SwifterSwift: Bold string.
public var bold: NSAttributedString {
return NSMutableAttributedString(string: self, attributes: [NSFontAttributeName: UIFont.boldSystemFont(ofSize: UIFont.systemFontSize)])
}
/// SwifterSwift: Underlined string
public var underline: NSAttributedString {
return NSAttributedString(string: self, attributes: [NSUnderlineStyleAttributeName: NSUnderlineStyle.styleSingle.rawValue])
}
/// SwifterSwift: Strikethrough string.
public var strikethrough: NSAttributedString {
return NSAttributedString(string: self, attributes: [NSStrikethroughStyleAttributeName: NSNumber(value: NSUnderlineStyle.styleSingle.rawValue as Int)])
}
/// SwifterSwift: Italic string.
public var italic: NSAttributedString {
return NSMutableAttributedString(string: self, attributes: [NSFontAttributeName: UIFont.italicSystemFont(ofSize: UIFont.systemFontSize)])
}
/// SwifterSwift: Add color to string.
///
/// - Parameter color: text color.
/// - Returns: a NSAttributedString versions of string colored with given color.
public func colored(with color: UIColor) -> NSAttributedString {
return NSMutableAttributedString(string: self, attributes: [NSForegroundColorAttributeName: color])
}
}
//MARK: - NSString extensions
public extension String {
/// SwifterSwift: NSString from a string
public var nsString: NSString {
return NSString(string: self)
}
/// SwifterSwift: NSString lastPathComponent
public var lastPathComponent: String {
return (self as NSString).lastPathComponent
}
/// SwifterSwift: NSString pathExtension
public var pathExtension: String {
return (self as NSString).pathExtension
}
/// SwifterSwift: NSString deletingLastPathComponent
public var deletingLastPathComponent: String {
return (self as NSString).deletingLastPathComponent
}
/// SwifterSwift: NSString deletingPathExtension
public var deletingPathExtension: String {
return (self as NSString).deletingPathExtension
}
/// SwifterSwift: NSString pathComponents
public var pathComponents: [String] {
return (self as NSString).pathComponents
}
/// SwifterSwift: NSString appendingPathComponent(str: String)
public func appendingPathComponent(_ str: String) -> String {
return (self as NSString).appendingPathComponent(str)
}
/// SwifterSwift: NSString appendingPathExtension(str: String) (if applicable).
public func appendingPathExtension(_ str: String) -> String? {
return (self as NSString).appendingPathExtension(str)
}
}
| mit | d29132437559ee01c80d8c22f7721f78 | 29.433715 | 153 | 0.705512 | 3.857884 | false | false | false | false |
AlexChekanov/Gestalt | Gestalt/SupportingClasses/General classes Extensions/UIView+fadeInOut.swift | 1 | 1238 | //
// UIView + fadeOut.swift
// Gestalt
//
// Created by Alexey Chekanov on 5/18/17.
// Copyright © 2017 Alexey Chekanov. All rights reserved.
//
import UIKit
extension UIView {
func fadeIn(duration: TimeInterval) {
self.isHidden = false
UIView.animate(withDuration: duration) { [unowned self] in
self.alpha = 1
}
}
func fadeOut(duration: TimeInterval) {
UIView.animate(withDuration: duration) { [unowned self] in
self.alpha = 0
}
self.isHidden = true
}
func fadeInResized(duration: TimeInterval) {
guard self.alpha < 1 else { return }
self.transform = CGAffineTransform(scaleX: 0.1, y: 0.1)
UIView.animate(withDuration: duration) { [unowned self] in
self.transform = CGAffineTransform.identity
self.alpha = 1
}
}
func fadeOutResized(duration: TimeInterval) {
guard self.alpha > 0 else { return }
UIView.animate(withDuration: duration, animations: { [unowned self] () -> Void in
self.transform = CGAffineTransform(scaleX: 0.1, y: 0.1)
self.alpha = 0
}, completion: nil)
}
}
| apache-2.0 | c7a8a72d5ba41adfca70b4383a820e3f | 24.770833 | 89 | 0.578011 | 4.371025 | false | false | false | false |
RobotsAndPencils/Scythe | Dependencies/HarvestKit-Swift/HarvestKit-Shared/Contact.swift | 1 | 3215 | //
// Contact.swift
// HarvestKit
//
// Created by Matthew Cheetham on 16/01/2016.
// Copyright © 2016 Matt Cheetham. All rights reserved.
//
import Foundation
/**
A struct representation of a project in the harvest system.
*/
public struct Contact {
/**
A unique identifier for the contact in the Harvest API
*/
public var identifier: Int?
/**
A the unique identifier of the client that this contact is assosciated with
*/
public var clientIdentifier: Int?
/**
The prefix for the name of the contact. Typically Mr, Mrs, Mx etc.
*/
public var title: String?
/**
The first name of the contact
*/
public var firstName: String?
/**
The last name of the contact
*/
public var lastName: String?
/**
The email address that can be used to reach this contact
*/
public var email: String?
/**
The phone number that can be used to reach this contact at the office. Stored as a string and may contain country codes, dashes, brackets etc.
*/
public var officePhoneNumber: String?
/**
The phone number that can be used to reach this contact on a mobile. Stored as a string and may contain country codes, dashes, brackets etc.
*/
public var mobilePhoneNumber: String?
/**
The number that can be used to communicate with this contact by fax. Stored as a string and may contain country codes, dashes, brackets etc.
*/
public var faxNumber: String?
/**
The date that the contact was created
*/
public var created: Date?
/**
The date that the contact was last modified
*/
public var updated: Date?
/**
Standard initialiser
*/
public init() {}
internal init?(dictionary: [String: AnyObject]) {
guard let contactDictionary = dictionary["contact"] as? [String: AnyObject] else {
print("Dictionary was missing contact key")
return nil
}
identifier = contactDictionary["id"] as? Int
clientIdentifier = contactDictionary["client_id"] as? Int
title = contactDictionary["title"] as? String
firstName = contactDictionary["first_name"] as? String
lastName = contactDictionary["last_name"] as? String
email = contactDictionary["email"] as? String
officePhoneNumber = contactDictionary["phone_office"] as? String
mobilePhoneNumber = contactDictionary["phone_mobile"] as? String
faxNumber = contactDictionary["fax"] as? String
if let createdDateString = contactDictionary["created_at"] as? String {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss'Z'"
created = dateFormatter.date(from: createdDateString)
}
if let updatedDateString = contactDictionary["updated_at"] as? String {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss'Z'"
updated = dateFormatter.date(from: updatedDateString)
}
}
}
| mit | 4dafab9e3afeb13d37ad4a19277c4760 | 28.218182 | 146 | 0.618855 | 4.869697 | false | false | false | false |
soffes/clock-saver | Clock/Classes/ClockView.swift | 1 | 8263 | import AppKit
import ScreenSaver
class ClockView: NSView {
// MARK: - Properties
class var modelName: String {
fatalError("Unimplemented")
}
var drawsLogo = false
var logoImage: NSImage?
var clockFrame: CGRect {
return clockFrame(forBounds: bounds)
}
var style: ClockStyle!
var styleName: String {
set {
}
get {
return style.description
}
}
class var styles: [ClockStyle] {
return []
}
override var frame: CGRect {
didSet {
setNeedsDisplay(bounds)
}
}
// MARK: - Initializers
convenience init() {
self.init(frame: .zero)
}
required override init(frame: NSRect) {
super.init(frame: frame)
initialize()
}
required init?(coder: NSCoder) {
super.init(coder: coder)
initialize()
}
// MARK: - NSView
override func draw(_ rect: NSRect) {
super.draw(rect)
style.backgroundColor.setFill()
NSBezierPath.fill(bounds)
drawFaceBackground()
drawTicks()
drawNumbers()
if drawsLogo {
drawLogo()
}
let comps = Calendar.current.dateComponents([.day, .hour, .minute, .second], from: Date())
let seconds = Double(comps.second ?? 0) / 60.0
let minutes = (Double(comps.minute ?? 0) / 60.0) + (seconds / 60.0)
let hours = (Double(comps.hour ?? 0) / 12.0) + ((minutes / 60.0) * (60.0 / 12.0))
draw(day: comps.day ?? 0, hours: hours, minutes: minutes, seconds: seconds)
}
// MARK: - Configuration
func initialize() {
NotificationCenter.default.addObserver(self, selector: #selector(preferencesDidChange), name: .PreferencesDidChange, object: nil)
preferencesDidChange(nil)
}
func clockFrame(forBounds bounds: CGRect) -> CGRect {
let size = bounds.size
let clockSize = min(size.width, size.height) * 0.55
let rect = CGRect(x: (size.width - clockSize) / 2.0, y: (size.height - clockSize) / 2.0, width: clockSize, height: clockSize)
return rect.integral
}
// MARK: - Drawing Hooks
func drawTicks() {
drawTicksDivider(color: style.backgroundColor.withAlphaComponent(0.05), position: 0.074960128)
let color = style.minuteColor
drawTicks(minorColor: color.withAlphaComponent(0.5), minorLength: 0.049441786, minorThickness: 0.004784689, majorColor: color, majorThickness: 0.009569378, inset: 0.014)
}
func drawLogo() {
drawLogo(color: style.logoColor, width: 0.156299841, y: 0.622009569)
}
func drawNumbers() {
drawNumbers(fontSize: 0.071770334, radius: 0.402711324)
}
func draw(day: Int, hours: Double, minutes: Double, seconds: Double) {
draw(day: day)
draw(hours: -(.pi * 2 * hours) + .pi / 2)
draw(minutes: -(.pi * 2 * minutes) + .pi / 2)
draw(seconds: -(.pi * 2 * seconds) + .pi / 2)
}
func draw(day: Int) {}
func draw(hours angle: Double) {
style.hourColor.setStroke()
drawHand(length: 0.263955343, thickness: 0.023125997, angle: angle)
}
func draw(minutes angle: Double) {
style.minuteColor.setStroke()
drawHand(length: 0.391547049, thickness: 0.014354067, angle: angle)
}
func draw(seconds angle: Double) {
style.secondColor.set()
drawHand(length: 0.391547049, thickness: 0.009569378, angle: angle)
// Counterweight
drawHand(length: -0.076555024, thickness: 0.028708134, angle: angle, lineCapStyle: .roundLineCapStyle)
let nubSize = clockFrame.size.width * 0.052631579
let nubFrame = CGRect(x: (bounds.size.width - nubSize) / 2.0, y: (bounds.size.height - nubSize) / 2.0, width: nubSize, height: nubSize)
NSBezierPath(ovalIn: nubFrame).fill()
// Screw
let dotSize = clockFrame.size.width * 0.006379585
Color.black.setFill()
let screwFrame = CGRect(x: (bounds.size.width - dotSize) / 2.0, y: (bounds.size.height - dotSize) / 2.0, width: dotSize, height: dotSize)
let screwPath = NSBezierPath(ovalIn: screwFrame.integral)
screwPath.fill()
}
// MARK: - Drawing Helpers
func drawHand(length: Double, thickness: Double, angle: Double, lineCapStyle: NSBezierPath.LineCapStyle = .squareLineCapStyle) {
let center = CGPoint(x: clockFrame.midX, y: clockFrame.midY)
let clockWidth = Double(clockFrame.size.width)
let end = CGPoint(
x: Double(center.x) + cos(angle) * clockWidth * length,
y: Double(center.y) + sin(angle) * clockWidth * length
)
let path = NSBezierPath()
path.lineWidth = CGFloat(clockWidth * thickness)
path.lineCapStyle = lineCapStyle
path.move(to: center)
path.line(to: end)
path.stroke()
}
func drawLogo(color: NSColor, width: CGFloat, y: CGFloat) {
if let image = logoImage {
let originalImageSize = image.size
let imageWidth = clockFrame.size.width * width
let imageSize = CGSize(
width: imageWidth,
height: originalImageSize.height * imageWidth / originalImageSize.width
)
let logoRect = CGRect(
x: (bounds.size.width - imageSize.width) / 2.0,
y: clockFrame.origin.y + (clockFrame.size.width * y),
width: imageSize.width,
height: imageSize.height
)
color.setFill()
let graphicsContext = NSGraphicsContext.current!
let cgImage = image.cgImage(forProposedRect: nil, context: graphicsContext, hints: nil)!
let context = graphicsContext.cgContext
context.saveGState()
context.clip(to: logoRect, mask: cgImage)
context.fill(bounds)
context.restoreGState()
}
}
func drawFaceBackground() {
style.faceColor.setFill()
let clockPath = NSBezierPath(ovalIn: clockFrame)
clockPath.lineWidth = 4
clockPath.fill()
}
func drawTicksDivider(color: NSColor, position: Double) {
color.setStroke()
let ticksFrame = clockFrame.insetBy(dx: clockFrame.size.width * CGFloat(position), dy: clockFrame.size.width * CGFloat(position))
let ticksPath = NSBezierPath(ovalIn: ticksFrame)
ticksPath.lineWidth = 1
ticksPath.stroke()
}
func drawTicks(minorColor: NSColor, minorLength: Double, minorThickness: Double, majorColor _majorColor: NSColor? = nil, majorLength _majorLength: Double? = nil, majorThickness _majorThickness: Double? = nil, inset: Double = 0.0) {
let majorColor = _majorColor ?? minorColor
let majorLength = _majorLength ?? minorLength
let majorThickness = _majorThickness ?? minorThickness
let center = CGPoint(x: clockFrame.midX, y: clockFrame.midY)
// Ticks
let clockWidth = clockFrame.size.width
let tickRadius = (clockWidth / 2.0) - (clockWidth * CGFloat(inset))
for i in 0..<60 {
let isMajor = (i % 5) == 0
let tickLength = clockWidth * CGFloat(isMajor ? majorLength : minorLength)
let progress = Double(i) / 60.0
let angle = CGFloat(-(progress * .pi * 2) + .pi / 2)
let tickColor = isMajor ? majorColor : minorColor
tickColor.setStroke()
let tickPath = NSBezierPath()
tickPath.move(to: CGPoint(
x: center.x + cos(angle) * (tickRadius - tickLength),
y: center.y + sin(angle) * (tickRadius - tickLength)
))
tickPath.line(to: CGPoint(
x: center.x + cos(angle) * tickRadius,
y: center.y + sin(angle) * tickRadius
))
tickPath.lineWidth = CGFloat(ceil(Double(clockWidth) * (isMajor ? majorThickness : minorThickness)))
tickPath.stroke()
}
}
func drawNumbers(fontSize: CGFloat, radius: Double) {
let center = CGPoint(x: clockFrame.midX, y: clockFrame.midY)
let clockWidth = clockFrame.size.width
let textRadius = clockWidth * CGFloat(radius)
let font = NSFont(name: "HelveticaNeue-Light", size: clockWidth * fontSize)!
for i in 0..<12 {
let string = NSAttributedString(string: "\(12 - i)", attributes: [
.foregroundColor: style.minuteColor,
.kern: -2,
.font: font
])
let stringSize = string.size()
let angle = CGFloat((Double(i) / 12.0 * .pi * 2.0) + .pi / 2)
let rect = CGRect(
x: (center.x + cos(angle) * (textRadius - (stringSize.width / 2.0))) - (stringSize.width / 2.0),
y: center.y + sin(angle) * (textRadius - (stringSize.height / 2.0)) - (stringSize.height / 2.0),
width: stringSize.width,
height: stringSize.height
)
string.draw(in: rect)
}
}
// MARK: - Private
@objc private func preferencesDidChange(_ notification: NSNotification?) {
let preferences = (notification?.object as? Preferences) ?? Preferences()
drawsLogo = preferences.drawsLogo
if drawsLogo {
if let imageURL = Bundle(for: ClockView.self).url(forResource: "braun", withExtension: "pdf") {
logoImage = NSImage(contentsOf: imageURL)
}
} else {
logoImage = nil
}
setNeedsDisplay(bounds)
}
}
| mit | 0e142a9546b9a24209a83e072f5cae90 | 27.790941 | 232 | 0.68837 | 3.232786 | false | false | false | false |
PatrickSCLin/PLMenuBar | PLMenuBar/PLMenuDetailComboRowView.swift | 1 | 2748 | //
// PLMenuDetailComboRowView.swift
// PLMenuBar
//
// Created by Patrick Lin on 4/14/16.
// Copyright © 2016 Patrick Lin. All rights reserved.
//
class PLMenuDetailComboRowView: UIView {
var title: String = ""
var isSelected: Bool = false {
didSet
{
if self.isSelected != oldValue {
self.updateStyle()
}
}
}
var isHighLighted: Bool = false {
didSet
{
self.updateStyle()
}
}
var checkBoxView: UIImageView = UIImageView()
var contentBtn: UIButton = UIButton()
// MARK: Public Methods
override func layoutSubviews() {
super.layoutSubviews()
self.checkBoxView.frame = CGRect(x: 8, y: 0, width: 22, height: self.bounds.size.height)
self.contentBtn.frame = CGRect(x: 30, y: 0, width: self.bounds.size.width - 30, height: self.bounds.size.height)
}
// MRK: Private Methods
func updateStyle() {
self.checkBoxView.isHidden = !self.isSelected
let color = (self.isHighLighted == true) ? UIColor.white : UIColor(red: 39/255, green: 33/255, blue: 29/255, alpha: 0.7)
self.checkBoxView.tintColor = color
self.contentBtn.setTitleColor(color, for: UIControlState())
}
// MARK: Init Methods
func commonInit() {
self.contentBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignment.left
self.contentBtn.setTitle(title, for: UIControlState())
if self.contentBtn.titleLabel != nil {
self.contentBtn.titleLabel!.font = UIFont.boldSystemFont(ofSize: 28)
self.contentBtn.titleEdgeInsets = UIEdgeInsets(top: 0, left: 10, bottom: 0, right: 0)
}
self.addSubview(self.contentBtn)
let bundle = Bundle(for: PLMenuDetailComboRowView.self)
var image = UIImage(named: "button-check.png", in: bundle, compatibleWith: nil)
image = image?.withRenderingMode(UIImageRenderingMode.alwaysTemplate)
if image != nil {
self.checkBoxView.image = image!
self.checkBoxView.contentMode = UIViewContentMode.scaleAspectFit
}
self.addSubview(self.checkBoxView)
self.updateStyle()
}
convenience init(title: String) {
self.init(frame: CGRect.zero)
self.title.append(title)
self.commonInit()
}
}
| mit | de40aa256daff35b8b0c1a4de5698bee | 24.201835 | 128 | 0.541682 | 5.003643 | false | false | false | false |
manavgabhawala/swift | test/IRGen/objc_bridge.swift | 1 | 10941 | // RUN: rm -rf %t && mkdir -p %t
// RUN: %build-irgen-test-overlays
// RUN: %target-swift-frontend(mock-sdk: -sdk %S/Inputs -I %t) -Xllvm -new-mangling-for-tests -emit-ir -primary-file %s | %FileCheck %s
// REQUIRES: CPU=x86_64
// REQUIRES: objc_interop
import Foundation
// CHECK: [[GETTER_SIGNATURE:@.*]] = private unnamed_addr constant [8 x i8] c"@16@0:8\00"
// CHECK: [[SETTER_SIGNATURE:@.*]] = private unnamed_addr constant [11 x i8] c"v24@0:8@16\00"
// CHECK: [[DEALLOC_SIGNATURE:@.*]] = private unnamed_addr constant [8 x i8] c"v16@0:8\00"
// CHECK: @_INSTANCE_METHODS__TtC11objc_bridge3Bas = private constant { i32, i32, [17 x { i8*, i8*, i8* }] } {
// CHECK: i32 24,
// CHECK: i32 17,
// CHECK: [17 x { i8*, i8*, i8* }] [
// CHECK: { i8*, i8*, i8* } {
// CHECK: i8* getelementptr inbounds ([12 x i8], [12 x i8]* @"\01L_selector_data(strRealProp)", i64 0, i64 0),
// CHECK: i8* getelementptr inbounds ([8 x i8], [8 x i8]* [[GETTER_SIGNATURE]], i64 0, i64 0),
// CHECK: i8* bitcast ([[OPAQUE:.*]]* ([[OPAQUE:.*]]*, i8*)* @_T011objc_bridge3BasC11strRealPropSSfgTo to i8*)
// CHECK: },
// CHECK: { i8*, i8*, i8* } {
// CHECK: i8* getelementptr inbounds ([16 x i8], [16 x i8]* @"\01L_selector_data(setStrRealProp:)", i64 0, i64 0),
// CHECK: i8* getelementptr inbounds ([11 x i8], [11 x i8]* [[SETTER_SIGNATURE]], i64 0, i64 0),
// CHECK: i8* bitcast (void ([[OPAQUE:.*]]*, i8*, [[OPAQUE:.*]]*)* @_T011objc_bridge3BasC11strRealPropSSfsTo to i8*)
// CHECK: },
// CHECK: { i8*, i8*, i8* } {
// CHECK: i8* getelementptr inbounds ([12 x i8], [12 x i8]* @"\01L_selector_data(strFakeProp)", i64 0, i64 0),
// CHECK: i8* getelementptr inbounds ([8 x i8], [8 x i8]* [[GETTER_SIGNATURE]], i64 0, i64 0),
// CHECK: i8* bitcast ([[OPAQUE:.*]]* ([[OPAQUE:.*]]*, i8*)* @_T011objc_bridge3BasC11strFakePropSSfgTo to i8*)
// CHECK: },
// CHECK: { i8*, i8*, i8* } {
// CHECK: i8* getelementptr inbounds ([16 x i8], [16 x i8]* @"\01L_selector_data(setStrFakeProp:)", i64 0, i64 0),
// CHECK: i8* getelementptr inbounds ([11 x i8], [11 x i8]* [[SETTER_SIGNATURE]], i64 0, i64 0),
// CHECK: i8* bitcast (void ([[OPAQUE:.*]]*, i8*, [[OPAQUE:.*]]*)* @_T011objc_bridge3BasC11strFakePropSSfsTo to i8*)
// CHECK: },
// CHECK: { i8*, i8*, i8* } {
// CHECK: i8* getelementptr inbounds ([14 x i8], [14 x i8]* @"\01L_selector_data(nsstrRealProp)", i64 0, i64 0),
// CHECK: i8* getelementptr inbounds ([8 x i8], [8 x i8]* [[GETTER_SIGNATURE]], i64 0, i64 0),
// CHECK: i8* bitcast ([[OPAQUE:.*]]* ([[OPAQUE:.*]]*, i8*)* @_T011objc_bridge3BasC13nsstrRealPropSo8NSStringCfgTo to i8*)
// CHECK: },
// CHECK: { i8*, i8*, i8* } {
// CHECK: i8* getelementptr inbounds ([18 x i8], [18 x i8]* @"\01L_selector_data(setNsstrRealProp:)", i64 0, i64 0),
// CHECK: i8* getelementptr inbounds ([11 x i8], [11 x i8]* [[SETTER_SIGNATURE]], i64 0, i64 0),
// CHECK: i8* bitcast (void ([[OPAQUE:.*]]*, i8*, [[OPAQUE:.*]]*)* @_T011objc_bridge3BasC13nsstrRealPropSo8NSStringCfsTo to i8*)
// CHECK: },
// CHECK: { i8*, i8*, i8* } {
// CHECK: i8* getelementptr inbounds ([14 x i8], [14 x i8]* @"\01L_selector_data(nsstrFakeProp)", i64 0, i64 0),
// CHECK: i8* getelementptr inbounds ([8 x i8], [8 x i8]* [[GETTER_SIGNATURE]], i64 0, i64 0),
// CHECK: i8* bitcast ([[OPAQUE:.*]]* ([[OPAQUE:.*]]*, i8*)* @_T011objc_bridge3BasC13nsstrFakePropSo8NSStringCfgTo to i8*)
// CHECK: },
// CHECK: { i8*, i8*, i8* } {
// CHECK: i8* getelementptr inbounds ([18 x i8], [18 x i8]* @"\01L_selector_data(setNsstrFakeProp:)", i64 0, i64 0),
// CHECK: i8* getelementptr inbounds ([11 x i8], [11 x i8]* [[SETTER_SIGNATURE]], i64 0, i64 0),
// CHECK: i8* bitcast (void ([[OPAQUE:.*]]*, i8*, [[OPAQUE:.*]]*)* @_T011objc_bridge3BasC13nsstrFakePropSo8NSStringCfsTo to i8*)
// CHECK: },
// CHECK: { i8*, i8*, i8* } {
// CHECK: i8* getelementptr inbounds ([10 x i8], [10 x i8]* @"\01L_selector_data(strResult)", i64 0, i64 0),
// CHECK: i8* getelementptr inbounds ([8 x i8], [8 x i8]* [[GETTER_SIGNATURE]], i64 0, i64 0),
// CHECK: i8* bitcast ([[OPAQUE:.*]]* ([[OPAQUE:.*]]*, i8*)* @_T011objc_bridge3BasC9strResultSSyFTo to i8*)
// CHECK: },
// CHECK: { i8*, i8*, i8* } {
// CHECK: i8* getelementptr inbounds ([{{[0-9]*}} x i8], [{{[0-9]*}} x i8]* @"\01L_selector_data(strArgWithS:)", i64 0, i64 0),
// CHECK: i8* getelementptr inbounds ([11 x i8], [11 x i8]* [[SETTER_SIGNATURE]], i64 0, i64 0),
// CHECK: i8* bitcast (void ([[OPAQUE:.*]]*, i8*, [[OPAQUE:.*]]*)* @_T011objc_bridge3BasC6strArgySS1s_tFTo to i8*)
// CHECK: },
// CHECK: { i8*, i8*, i8* } {
// CHECK: i8* getelementptr inbounds ([12 x i8], [12 x i8]* @"\01L_selector_data(nsstrResult)", i64 0, i64 0),
// CHECK: i8* getelementptr inbounds ([8 x i8], [8 x i8]* [[GETTER_SIGNATURE]], i64 0, i64 0),
// CHECK: i8* bitcast ([[OPAQUE:.*]]* ([[OPAQUE:.*]]*, i8*)* @_T011objc_bridge3BasC11nsstrResultSo8NSStringCyFTo to i8*)
// CHECK: },
// CHECK: { i8*, i8*, i8* } {
// CHECK: i8* getelementptr inbounds ([{{[0-9]+}} x i8], [{{[0-9]+}} x i8]* @"\01L_selector_data(nsstrArgWithS:)", i64 0, i64 0),
// CHECK: i8* getelementptr inbounds ([11 x i8], [11 x i8]* [[SETTER_SIGNATURE]], i64 0, i64 0),
// CHECK: i8* bitcast (void ([[OPAQUE:.*]]*, i8*, [[OPAQUE:.*]]*)* @_T011objc_bridge3BasC8nsstrArgySo8NSStringC1s_tFTo to i8*)
// CHECK: },
// CHECK: { i8*, i8*, i8* } {
// CHECK: i8* getelementptr inbounds ([5 x i8], [5 x i8]* @"\01L_selector_data(init)", i64 0, i64 0),
// CHECK: i8* getelementptr inbounds ([8 x i8], [8 x i8]* [[GETTER_SIGNATURE]], i64 0, i64 0),
// CHECK: i8* bitcast ([[OPAQUE:.*]]* ([[OPAQUE:.*]]*, i8*)* @_T011objc_bridge3BasCACycfcTo to i8*)
// CHECK: },
// CHECK: { i8*, i8*, i8* } {
// CHECK: i8* getelementptr inbounds ([8 x i8], [8 x i8]* @"\01L_selector_data(dealloc)", i64 0, i64 0),
// CHECK: i8* getelementptr inbounds ([8 x i8], [8 x i8]* [[DEALLOC_SIGNATURE]], i64 0, i64 0),
// CHECK: i8* bitcast (void ([[OPAQUE:.*]]*, i8*)* @_T011objc_bridge3BasCfDTo to i8*)
// CHECK: },
// CHECK: { i8*, i8*, i8* } {
// CHECK: i8* getelementptr inbounds ([11 x i8], [11 x i8]* @"\01L_selector_data(acceptSet:)", i64 0, i64 0),
// CHECK: i8* getelementptr inbounds ([11 x i8], [11 x i8]* @{{[0-9]+}}, i64 0, i64 0),
// CHECK: i8* bitcast (void (%3*, i8*, %4*)* @_T011objc_bridge3BasC9acceptSetys0E0VyACGFTo to i8*)
// CHECK: }
// CHECK: { i8*, i8*, i8* } {
// CHECK: i8* getelementptr inbounds ([14 x i8], [14 x i8]* @"\01L_selector_data(.cxx_destruct)", i64 0, i64 0),
// CHECK: i8* getelementptr inbounds ([3 x i8], [3 x i8]* @{{.*}}, i64 0, i64 0),
// CHECK: i8* bitcast (void ([[OPAQUE:.*]]*, i8*)* @_T011objc_bridge3BasCfETo to i8*)
// CHECK: }
// CHECK: ]
// CHECK: }, section "__DATA, __objc_const", align 8
// CHECK: @_PROPERTIES__TtC11objc_bridge3Bas = private constant { i32, i32, [5 x { i8*, i8* }] } {
// CHECK: [[OBJC_BLOCK_PROPERTY:@.*]] = private unnamed_addr constant [11 x i8] c"T@?,N,C,Vx\00"
// CHECK: @_PROPERTIES__TtC11objc_bridge21OptionalBlockProperty = private constant {{.*}} [[OBJC_BLOCK_PROPERTY]]
func getDescription(_ o: NSObject) -> String {
return o.description
}
func getUppercaseString(_ s: NSString) -> String {
return s.uppercase()
}
// @interface Foo -(void) setFoo: (NSString*)s; @end
func setFoo(_ f: Foo, s: String) {
f.setFoo(s)
}
// NSString *bar(int);
func callBar() -> String {
return bar(0)
}
// void setBar(NSString *s);
func callSetBar(_ s: String) {
setBar(s)
}
var NSS : NSString = NSString()
// -- NSString methods don't convert 'self'
extension NSString {
// CHECK: define internal [[OPAQUE:.*]]* @_T0So8NSStringC11objc_bridgeE13nsstrFakePropABfgTo([[OPAQUE:.*]]*, i8*) unnamed_addr
// CHECK: define internal void @_T0So8NSStringC11objc_bridgeE13nsstrFakePropABfsTo([[OPAQUE:.*]]*, i8*, [[OPAQUE:.*]]*) unnamed_addr
var nsstrFakeProp : NSString {
get {
return NSS
}
set {}
}
// CHECK: define internal [[OPAQUE:.*]]* @_T0So8NSStringC11objc_bridgeE11nsstrResultAByFTo([[OPAQUE:.*]]*, i8*) unnamed_addr
func nsstrResult() -> NSString { return NSS }
// CHECK: define internal void @_T0So8NSStringC11objc_bridgeE8nsstrArgyAB1s_tFTo([[OPAQUE:.*]]*, i8*, [[OPAQUE:.*]]*) unnamed_addr
func nsstrArg(s s: NSString) { }
}
class Bas : NSObject {
// CHECK: define internal [[OPAQUE:.*]]* @_T011objc_bridge3BasC11strRealPropSSfgTo([[OPAQUE:.*]]*, i8*) unnamed_addr {{.*}} {
// CHECK: define internal void @_T011objc_bridge3BasC11strRealPropSSfsTo([[OPAQUE:.*]]*, i8*, [[OPAQUE:.*]]*) unnamed_addr {{.*}} {
var strRealProp : String
// CHECK: define internal [[OPAQUE:.*]]* @_T011objc_bridge3BasC11strFakePropSSfgTo([[OPAQUE:.*]]*, i8*) unnamed_addr {{.*}} {
// CHECK: define internal void @_T011objc_bridge3BasC11strFakePropSSfsTo([[OPAQUE:.*]]*, i8*, [[OPAQUE:.*]]*) unnamed_addr {{.*}} {
var strFakeProp : String {
get {
return ""
}
set {}
}
// CHECK: define internal [[OPAQUE:.*]]* @_T011objc_bridge3BasC13nsstrRealPropSo8NSStringCfgTo([[OPAQUE:.*]]*, i8*) unnamed_addr {{.*}} {
// CHECK: define internal void @_T011objc_bridge3BasC13nsstrRealPropSo8NSStringCfsTo([[OPAQUE:.*]]*, i8*, [[OPAQUE:.*]]*) unnamed_addr {{.*}} {
var nsstrRealProp : NSString
// CHECK: define hidden swiftcc %TSo8NSStringC* @_T011objc_bridge3BasC13nsstrFakePropSo8NSStringCfg(%T11objc_bridge3BasC* swiftself) {{.*}} {
// CHECK: define internal void @_T011objc_bridge3BasC13nsstrFakePropSo8NSStringCfsTo([[OPAQUE:.*]]*, i8*, [[OPAQUE:.*]]*) unnamed_addr {{.*}} {
var nsstrFakeProp : NSString {
get {
return NSS
}
set {}
}
// CHECK: define internal [[OPAQUE:.*]]* @_T011objc_bridge3BasC9strResultSSyFTo([[OPAQUE:.*]]*, i8*) unnamed_addr {{.*}} {
func strResult() -> String { return "" }
// CHECK: define internal void @_T011objc_bridge3BasC6strArgySS1s_tFTo([[OPAQUE:.*]]*, i8*, [[OPAQUE:.*]]*) unnamed_addr {{.*}} {
func strArg(s s: String) { }
// CHECK: define internal [[OPAQUE:.*]]* @_T011objc_bridge3BasC11nsstrResultSo8NSStringCyFTo([[OPAQUE:.*]]*, i8*) unnamed_addr {{.*}} {
func nsstrResult() -> NSString { return NSS }
// CHECK: define internal void @_T011objc_bridge3BasC8nsstrArgySo8NSStringC1s_tFTo([[OPAQUE:.*]]*, i8*, [[OPAQUE:.*]]*) unnamed_addr {{.*}} {
func nsstrArg(s s: NSString) { }
override init() {
strRealProp = String()
nsstrRealProp = NSString()
super.init()
}
deinit { var x = 10 }
override var hashValue: Int { return 0 }
func acceptSet(_ set: Set<Bas>) { }
}
func ==(lhs: Bas, rhs: Bas) -> Bool { return true }
class OptionalBlockProperty: NSObject {
var x: (([AnyObject]) -> [AnyObject])?
}
| apache-2.0 | 08ef4b185a4332ca1aeec784af8fc57b | 52.896552 | 145 | 0.595832 | 3.136755 | false | false | false | false |
darina/omim | iphone/Maps/Core/Theme/Renderers/TabViewRenderer.swift | 5 | 860 | extension TabView {
@objc override func applyTheme() {
if styleName.isEmpty {
styleName = "TabView"
}
for style in StyleManager.shared.getStyle(styleName)
where !style.isEmpty && !style.hasExclusion(view: self) {
TabViewRenderer.render(self, style: style)
}
}
}
class TabViewRenderer {
class func render(_ control: TabView, style: Style) {
if let backgroundColor = style.backgroundColor {
control.backgroundColor = backgroundColor
}
if let barTintColor = style.barTintColor {
control.barTintColor = barTintColor
}
if let tintColor = style.tintColor {
control.tintColor = tintColor
}
if let font = style.font, let fontColor = style.fontColor {
control.headerTextAttributes = [.foregroundColor: fontColor,
.font: font]
}
}
}
| apache-2.0 | 6cb1e7795d4b176da9a0bc049f4d23fb | 28.655172 | 66 | 0.645349 | 4.623656 | false | false | false | false |
shomishinec/PrettySegue | Source/PrettySegue.swift | 1 | 2692 | //
// PrettySegue.swift
//
// Copyright (c) 2017 Stan H ([email protected])
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import UIKit
public typealias Controller = UIViewController
extension UIViewController {
/**
Initiates the segue with the specified identifier from the current view controller's storyboard file.
- Parameters:
- identifier: Segue identifier
- sender: Please check the original method to get info about this parametr
- configurator: Closure with initialized destanation ViewController
- Returns: Void
*/
public final func performSegue<C: Controller>(withIdentifier identifier: String,
sender: Any? = nil,
configurator: ((C) -> (Void))? = nil) {
objc_sync_enter(self)
type(of: self).swizzlePrepareForSegue()
let segue = InternalSegue(identifier: identifier, sender: sender, configurator: configurator)
segue.perform(viewController: self)
type(of: self).swizzlePrepareForSegue()
objc_sync_exit(self)
}
func swizzledPrepareForSegue(for segue: UIStoryboardSegue, sender: Any?) {
if let _sender = sender as? SenderTuple {
self.swizzledPrepareForSegue(for: segue, sender: _sender.realSender)
_sender.transmitter?(segue)
}
}
class func swizzlePrepareForSegue() {
let originalSelector = #selector(UIViewController.prepare(for:sender:))
let swizzledSelector = #selector(UIViewController.swizzledPrepareForSegue(for:sender:))
let originalMethod = class_getInstanceMethod(self, originalSelector)
let swizzledMethod = class_getInstanceMethod(self, swizzledSelector)
method_exchangeImplementations(originalMethod, swizzledMethod)
}
}
| mit | aa885e19b212e3613fdb217a0005da6d | 36.361111 | 104 | 0.751673 | 4.269841 | false | true | false | false |
qvacua/vimr | VimR/VimR/IgnoreService.swift | 1 | 2450 | /// Tae Won Ha - http://taewon.de - @hataewon
/// See LICENSE
import Commons
import Foundation
import Ignore
import OrderedCollections
final class IgnoreService {
var root: URL {
didSet {
self.rootIgnore = Ignore(base: self.root, parent: Ignore.globalGitignore(base: self.root))
}
}
init(count: Int, root: URL) {
self.root = root
self.count = count
self.queue = DispatchQueue(
label: "\(String(reflecting: IgnoreService.self))-\(UUID().uuidString)",
qos: .default,
target: .global(qos: DispatchQoS.default.qosClass)
)
self.storage = OrderedDictionary(minimumCapacity: count)
self.rootIgnore = Ignore(base: root, parent: Ignore.globalGitignore(base: root))
}
func ignore(for url: URL) -> Ignore? {
self.queue.sync {
if self.root == url { return self.rootIgnore }
guard self.root.isAncestor(of: url) else { return nil }
if let ignore = self.storage[url] { return ignore }
if let parentIgnore = self.storage[url.parent] {
let ignore = Ignore.parentOrIgnore(for: url, withParent: parentIgnore)
self.storage[url] = ignore
return ignore
}
// Since we descend the directory structure step by step, the ignore of the parent should
// already be present. Most probably we won't land here...
let rootPathComp = self.root.pathComponents
let pathComp = url.pathComponents
let lineage = pathComp.suffix(from: rootPathComp.count)
var ancestorUrl = self.root
var ancestorIgnore = self.rootIgnore
for ancestorComponent in lineage {
ancestorUrl = ancestorUrl.appendingPathComponent(ancestorComponent, isDirectory: true)
if let cachedAncestorIc = self.storage[ancestorUrl] { ancestorIgnore = cachedAncestorIc }
else {
guard let ignore = Ignore.parentOrIgnore(
for: ancestorUrl,
withParent: ancestorIgnore
) else { return nil }
self.set(ignoreCollection: ignore, forUrl: ancestorUrl)
ancestorIgnore = ignore
}
}
return ancestorIgnore
}
}
private func set(ignoreCollection: Ignore, forUrl url: URL) {
if self.storage.count == self.count { self.storage.removeFirst() }
self.storage[url] = ignoreCollection
}
private var rootIgnore: Ignore?
private let count: Int
private var storage: OrderedDictionary<URL, Ignore>
private let queue: DispatchQueue
}
| mit | ba1fb5e71a6c54fd443f967523f48ccf | 30.012658 | 97 | 0.669388 | 4.283217 | false | false | false | false |
oisdk/Using-Protocols-to-Build-a-very-Generic-Deque | Deque.playground/Contents.swift | 1 | 10496 | //: # Using Protocols to Build a (very) Generic Deque #
//:
//: This post is an update on a [previous implementation of a
//: Deque](https://bigonotetaking.wordpress.com/2015/08/09/yet-another-root-of-all-evil/).
//: A full implementation of this Deque is available
//: [here](https://github.com/oisdk/SwiftDataStructures/blob/master/SwiftDataStructures/Deque.swift).
//:
//: A Deque is a data structure comprised of two stacks, facing opposite directions.
//: In this way, operations at either end of the Deque have the same complexity as
//: operations on one end of the underlying stack. This implementation uses two
//: arrays, with the front reversed: appending, prepending, and removal of the first
//: and last elements are all (amortized) O(1).
//:
//: The standard library has three `Array` structs: `Array`, `ArraySlice`, and
//: `ContiguousArray`. They all have the same interface, with different underlying
//: implementations. An `Array` is a standard vector-like structure, which allows
//: O(1) amortized appending, fast iteration, etc. A `ContiguousArray` has stricter
//: rules about contiguity, but it's not bridged to Objective-C.
let array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
let cArray: ContiguousArray = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
//: An `ArraySlice` is a reference into an `Array` or `ContiguousArray`, for more
//: efficient slicing. All the information an `ArraySlice` contains is the beginning
//: and end points of the slice (as well as any changes made to the slice separate
//: from the array)
let slice = array[0..<6]
//: To replicate these semantics in a Deque requires three separate structs: one with
//: an `Array` as the stack, another with an `ArraySlice` as the stack, and a third
//: with a `ContiguousArray`. The standard library seems to duplicate the structs,
//: along with their methods and properties.
//:
//: It would be much nicer to just define a protocol that represented the
//: *difference* between the deque types: then you could just write the methods and
//: properties once, on top of it. Something like this:
protocol DequeType0 {
typealias Container : RangeReplaceableCollectionType, MutableSliceable
var front: Container { get set }
var back : Container { get set }
init()
}
//: There’s one problem with this: both stacks need to be made public. It would be
//: much nicer to hide the stacks (especially since an invariant needs to be
//: checked and maintained on every mutation). If anyone has an idea of how to
//: accomplish that, [tweet me](https://twitter.com/oisdk).
//:
//: The first method to implement is a subscript. Indexing is difficult, because the
//: front stack will be reversed, so the index used to get in to the Deque will need
//: to be translated into an equivalent index in the array.
//:
//: Any (valid) index will point into either the front or back queue, and the
//: transformations applied to it in each case is different. If it’s in the front,
//: the end result will look like `front[front.endIndex - 1 - i]`, whereas if it’s in
//: the back, it should be `back[i - front.endIndex]`. There’s nothing specified
//: about the Containers except that they’re `RangeReplaceableCollectionType` and
//: `MutableSliceable`, so the index types will have to be as generic as possible.
//: (you could specify `where Index == Int`, but that’s more specific than needed,
//: and not very extensible.)
//:
//: Both of those transformations are subtractions, an operation that's possible on
//: `RandomAccessIndexType`s with the `advancedBy` method. `advancedBy` takes the
//: associated `Distance` type of the `RandomAccessIndexType`. That's enough
//: information to figure out that the Deque's index type must be the same as the
//: Distance of the Index of the Container.
extension DequeType0 {
typealias Index = Container.Index.Distance
}
//: The method that will translate an index into the relevant index in the stacks
//: will return an enum:
public enum IndexLocation0<I> {
case Front(I), Back(I)
}
//: Then, the translate method itself:
extension DequeType0 where
Container.Index : RandomAccessIndexType,
Container.Index.Distance : ForwardIndexType {
private func translate(i: Container.Index.Distance)
-> IndexLocation0<Container.Index> {
return i < front.count ?
.Front(front.endIndex.predecessor().advancedBy(-i)) :
.Back(back.startIndex.advancedBy(i - front.count))
}
}
//: This performs two steps:
//: 1. Check which stack it's in.
//: 2. Subtract in the appropriate order
let d: Deque = [1, 2, 3, 4, 5, 6]
d.translate(0)
d.translate(4)
//: This means that the logic for converting distance to index is separated from the
//: logic for actual indexing. Great! Here’s the indexing:
extension DequeType0 where
Container.Index : RandomAccessIndexType,
Container.Index.Distance : ForwardIndexType {
var startIndex: Container.Index.Distance { return 0 }
var endIndex : Container.Index.Distance { return front.count + back.count }
subscript(i: Container.Index.Distance) -> Container.Generator.Element {
get {
switch translate(i) {
case let .Front(i): return front[i]
case let .Back(i): return back[i]
}
} set {
switch translate(i) {
case let .Front(i): front[i] = newValue
case let .Back(i): back[i] = newValue
}
}
}
}
//: This makes things much easier to test and debug.
//:
//: Here's where the power of protocols becomes obvious. If you go back to the
//: original definition of `DequeType`, you can add `Indexable`. It may seem like now
//: only indexable things can conform, but what happens in practice is that when
//: `Indexable` looks for its requirements, *it can use the implementations in
//: DequeType*. That means that we’ve just made anything that can conform to
//: `DequeType` indexable. That’s awesome.
//:
//: Next job is ranged indices. This is a good bit more complicated than the
//: individual indices, so it definitely will benefit from being separated into a
//: translate method:
extension DequeType0 where
Container.Index : RandomAccessIndexType,
Container.Index.Distance : BidirectionalIndexType {
private func translate
(i: Range<Container.Index.Distance>)
-> IndexRangeLocation<Container.Index> {
if i.endIndex <= front.count {
let s = front.endIndex.advancedBy(-i.endIndex)
if s == front.startIndex && i.isEmpty { return .Between }
let e = front.endIndex.advancedBy(-i.startIndex)
return .Front(s..<e)
}
if i.startIndex >= front.count {
let s = back.startIndex.advancedBy(i.startIndex - front.count)
let e = back.startIndex.advancedBy(i.endIndex - front.count)
return .Back(s..<e)
}
let f = front.startIndex..<front.endIndex.advancedBy(-i.startIndex)
let b = back.startIndex..<back.startIndex.advancedBy(i.endIndex - front.count)
return .Over(f, b)
}
}
let otherDeque: Deque = [0, 1, 2, 3, 4, 5]
otherDeque.translate(0...2)
otherDeque.translate(4...5)
otherDeque.translate(2...5)
otherDeque.translate(3..<3)
//: The invariant that must be maintained in the deque is this: if either stack has
//: more than one element, the other cannot be empty. If the invariant is violated,
//: the longer stack is reversed, and put in place of the shorter.
public enum Balance0 {
case FrontEmpty, BackEmpty, Balanced
}
extension DequeType0 {
var balance: Balance {
let (f, b) = (front.count, back.count)
if f == 0 {
if b > 1 {
return .FrontEmpty
}
} else if b == 0 {
if f > 1 {
return .BackEmpty
}
}
return .Balanced
}
var isBalanced: Bool {
return balance == .Balanced
}
}
//: A deque is a good data structure for certain uses, especially those that require
//: popping and appending from either end. `popFirst()` and `popLast()` aren't
//: included in the standard `RangeReplaceableCollectionType`, though, so we'll have
//: to add our own.
extension RangeReplaceableCollectionType where Index : BidirectionalIndexType {
private mutating func popLast0() -> Generator.Element? {
return isEmpty ? nil : removeLast()
}
}
var mutableDeque: Deque = [0, 1, 2, 3, 4, 5]
mutableDeque.popLast()
mutableDeque.debugDescription
extension DequeType0 where Container.Index : BidirectionalIndexType {
mutating func popLast() -> Container.Generator.Element? {
return back.popLast()
}
}
//: The method needs to include `check()`, which we can do with `defer`
//mutating func popLast() -> Container.Generator.Element? {
// defer { check() }
// return back.popLast()
//}
mutableDeque.popLast()
mutableDeque
mutableDeque.popLast()
mutableDeque
//: You also can't just pop from the back queue in `popLast()`, because it may be the
//: case that the front stack has one element left
//mutating func popLast() -> Container.Generator.Element? {
// defer { check() }
// return back.popLast() ?? front.popLast()
//}
mutableDeque.popLast()
mutableDeque.popLast()
mutableDeque
mutableDeque.popLast()
mutableDeque
mutableDeque.popLast()
mutableDeque
//: The rest of the Deque was easy, with little to no repetition. Using protocols in
//: this way was really surprisingly powerful: now, you can define a `DequeType`,
//: with full access to all of the collection methods, all the way up to
//: `RangeReplaceableCollectionType`, in five lines:
public struct Deque<Element> : DequeType {
public var front, back: [Element]
public typealias SubSequence = DequeSlice<Element>
public init() { (front, back) = ([], []) }
}
public struct DequeSlice<Element> : DequeType {
public var front, back: ArraySlice<Element>
public typealias SubSequence = DequeSlice
public init() { (front, back) = ([], []) }
}
//: There’s no performance hit, there’s no safety problems. I only have one version
//: of code to test, one version to change, one version to read. It’s completely
//: extensible: you could use any kind of stack for the front and back. Even another
//: Deque, if you were so inclined:
struct DequeDeque<Element> : DequeType {
var front, back: Deque<Element>
typealias SubSequence = DequeDequeSlice<Element>
init() { front = Deque(); back = Deque() }
}
struct DequeDequeSlice<Element> : DequeType {
var front, back: DequeSlice<Element>
typealias SubSequence = DequeDequeSlice
init() { front = DequeSlice(); back = DequeSlice() }
}
let dd: DequeDeque = [1, 2, 3, 4, 5, 6, 7, 8]
dd.front
dd.back
//: Woo protocols!
| mit | 07a3ca583479233b6b84c8cb741a63af | 39.747082 | 101 | 0.708365 | 4.010724 | false | false | false | false |
bendodson/AudioRecorderViewController-Swift | AudioRecorderViewControllerExample/AudioRecorderViewControllerExample/AudioRecorderViewController.swift | 1 | 8414 | //
// AudioRecorderViewController.swift
// AudioRecorderViewControllerExample
//
// Created by Ben Dodson on 19/10/2015.
// Copyright © 2015 Dodo Apps. All rights reserved.
//
import UIKit
import AVFoundation
protocol AudioRecorderViewControllerDelegate: class {
func audioRecorderViewControllerDismissed(withFileURL fileURL: NSURL?)
}
class AudioRecorderViewController: UINavigationController {
internal let childViewController = AudioRecorderChildViewController()
weak var audioRecorderDelegate: AudioRecorderViewControllerDelegate?
var statusBarStyle: UIStatusBarStyle = .default
// MARK: - Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.black
childViewController.audioRecorderDelegate = audioRecorderDelegate
viewControllers = [childViewController]
navigationBar.barTintColor = UIColor.black
navigationBar.tintColor = UIColor.white
navigationBar.titleTextAttributes = [NSAttributedString.Key.foregroundColor: UIColor.white]
navigationBar.setBackgroundImage(UIImage(), for: .default)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
statusBarStyle = UIApplication.shared.statusBarStyle
self.preferredStatusBarStyle
UIApplication.shared.setStatusBarStyle(.lightContent, animated: animated)
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
UIApplication.shared.setStatusBarStyle(statusBarStyle, animated: animated)
}
// MARK: - AudioRecorderChildViewController
internal class AudioRecorderChildViewController: UIViewController, AVAudioRecorderDelegate, AVAudioPlayerDelegate {
var saveButton: UIBarButtonItem!
@IBOutlet weak var timeLabel: UILabel!
@IBOutlet weak var recordButton: UIButton!
@IBOutlet weak var recordButtonContainer: UIView!
@IBOutlet weak var playButton: UIButton!
weak var audioRecorderDelegate: AudioRecorderViewControllerDelegate?
var timeTimer: Timer?
var milliseconds: Int = 0
var recorder: AVAudioRecorder!
var player: AVAudioPlayer?
var outputURL: NSURL
init() {
let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as NSString
let outputPath = documentsPath.appendingPathComponent("\(NSUUID().uuidString).m4a")
outputURL = NSURL(fileURLWithPath: outputPath)
super.init(nibName: "AudioRecorderViewController", bundle: nil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
title = "Audio Recorder"
navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .cancel, target: self, action: #selector(AudioRecorderChildViewController.dismiss))
edgesForExtendedLayout = .all
saveButton = UIBarButtonItem(barButtonSystemItem: .save, target: self, action: #selector(AudioRecorderChildViewController.saveAudio))
navigationItem.rightBarButtonItem = saveButton
saveButton.isEnabled = false
let settings = [
AVFormatIDKey: Int(kAudioFormatMPEG4AAC),
AVSampleRateKey: 44100,
AVNumberOfChannelsKey: 2,
AVEncoderAudioQualityKey: AVAudioQuality.high.rawValue
]
try! recorder = AVAudioRecorder(url: outputURL as URL, settings: settings)
recorder.delegate = self
recorder.prepareToRecord()
recordButton.layer.cornerRadius = 4
recordButtonContainer.layer.cornerRadius = 25
recordButtonContainer.layer.borderColor = UIColor.white.cgColor
recordButtonContainer.layer.borderWidth = 3
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
do {
try AVAudioSession.sharedInstance().setCategory(AVAudioSession.Category.playAndRecord)
try AVAudioSession.sharedInstance().setActive(true)
}
catch let error as NSError {
NSLog("Error: \(error)")
}
NotificationCenter.default.addObserver(self, selector: #selector(stopRecording(sender:)), name: UIApplication.didEnterBackgroundNotification, object: nil)
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
NotificationCenter.default.removeObserver(self)
}
@objc func dismiss(_ sender: Any) {
cleanup()
audioRecorderDelegate?.audioRecorderViewControllerDismissed(withFileURL: nil)
}
@objc func saveAudio(_ sender: Any) {
cleanup()
audioRecorderDelegate?.audioRecorderViewControllerDismissed(withFileURL: outputURL)
}
@IBAction func toggleRecord(_ sender: Any) {
timeTimer?.invalidate()
if recorder.isRecording {
recorder.stop()
} else {
milliseconds = 0
timeLabel.text = "00:00.00"
timeTimer = Timer.scheduledTimer(timeInterval: 0.02, target: self, selector: #selector(updateTimeLabel(timer:)), userInfo: nil, repeats: true)
recorder.deleteRecording()
recorder.record()
}
updateControls()
}
@IBAction func play(_ sender: Any) {
if let player = player {
player.stop()
self.player = nil
updateControls()
return
}
do {
try player = AVAudioPlayer(contentsOf: outputURL as URL)
}
catch let error as NSError {
NSLog("error: \(error)")
}
player?.delegate = self
player?.play()
updateControls()
}
@objc func stopRecording(sender: AnyObject) {
if recorder.isRecording {
toggleRecord(sender)
}
}
func cleanup() {
timeTimer?.invalidate()
if recorder.isRecording {
recorder.stop()
recorder.deleteRecording()
}
if let player = player {
player.stop()
self.player = nil
}
}
func updateControls() {
UIView.animate(withDuration: 0.2) { () -> Void in
self.recordButton.transform = self.recorder.isRecording ? CGAffineTransform(scaleX: 0.5, y: 0.5) : CGAffineTransform(scaleX: 1, y: 1)
}
if let _ = player {
playButton.setImage(UIImage(named: "StopButton"), for: .normal)
recordButton.isEnabled = false
recordButtonContainer.alpha = 0.25
} else {
playButton.setImage(UIImage(named: "PlayButton"), for: .normal)
recordButton.isEnabled = true
recordButtonContainer.alpha = 1
}
playButton.isEnabled = !recorder.isRecording
playButton.alpha = recorder.isRecording ? 0.25 : 1
saveButton.isEnabled = !recorder.isRecording
}
// MARK: - Time Label
@objc func updateTimeLabel(timer: Timer) {
milliseconds += 1
let milli = (milliseconds % 60) + 39
let sec = (milliseconds / 60) % 60
let min = milliseconds / 3600
timeLabel.text = NSString(format: "%02d:%02d.%02d", min, sec, milli) as String
}
// MARK: - Playback Delegate
func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool) {
self.player = nil
updateControls()
}
}
}
| unlicense | 86fa3f1cf5ebad0dd0cb7c90596bd5b4 | 35.578261 | 167 | 0.589445 | 6.136397 | false | false | false | false |
nRewik/ArtHIstory | ArtHistory/ArtHistory/UIImageColors.swift | 1 | 8082 | //
// UIImageColors.swift
// https://github.com/jathu/UIImageColors
//
// Created by Jathu Satkunarajah (@jathu) on 2015-06-11 - Toronto
// Original Cocoa version by Panic Inc. - Portland
//
import UIKit
public struct UIImageColors {
public var backgroundColor: UIColor!
public var primaryColor: UIColor!
public var secondaryColor: UIColor!
public var detailColor: UIColor!
}
class PCCountedColor {
let color: UIColor
let count: Int
init(color: UIColor, count: Int) {
self.color = color
self.count = count
}
}
extension UIColor {
public var isDarkColor: Bool {
let RGB = CGColorGetComponents(self.CGColor)
return (0.2126 * RGB[0] + 0.7152 * RGB[1] + 0.0722 * RGB[2]) < 0.5
}
public var isBlackOrWhite: Bool {
let RGB = CGColorGetComponents(self.CGColor)
return (RGB[0] > 0.91 && RGB[1] > 0.91 && RGB[2] > 0.91) || (RGB[0] < 0.09 && RGB[1] < 0.09 && RGB[2] < 0.09)
}
public func isContrastingColor(compareColor: UIColor) -> Bool {
let bg = CGColorGetComponents(self.CGColor)
let fg = CGColorGetComponents(compareColor.CGColor)
let bgLum = 0.2126 * bg[0] + 0.7152 * bg[1] + 0.0722 * bg[2]
let fgLum = 0.2126 * fg[0] + 0.7152 * fg[1] + 0.0722 * fg[2]
let contrast = (bgLum > fgLum) ? (bgLum + 0.05)/(fgLum + 0.05):(fgLum + 0.05)/(bgLum + 0.05)
return 1.6 < contrast
}
}
extension UIImage {
public func resize(newSize: CGSize) -> UIImage {
UIGraphicsBeginImageContextWithOptions(newSize, false, 0)
self.drawInRect(CGRectMake(0, 0, newSize.width, newSize.height))
let result = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return result
}
public func getColors() -> UIImageColors {
let ratio = self.size.width/self.size.height
let r_width: CGFloat = 250
return self.getColors(CGSizeMake(r_width, r_width/ratio))
}
public func getColors(scaleDownSize: CGSize) -> UIImageColors {
var result = UIImageColors()
let cgImage = self.resize(scaleDownSize).CGImage
let width = CGImageGetWidth(cgImage)
let height = CGImageGetHeight(cgImage)
let bytesPerPixel: Int = 4
let bytesPerRow: Int = width * bytesPerPixel
let bitsPerComponent: Int = 8
let randomColorsThreshold = Int(CGFloat(height)*0.01)
let sortedColorComparator: NSComparator = { (main, other) -> NSComparisonResult in
let m = main as! PCCountedColor, o = other as! PCCountedColor
if m.count < o.count {
return NSComparisonResult.OrderedDescending
} else if m.count == o.count {
return NSComparisonResult.OrderedSame
} else {
return NSComparisonResult.OrderedAscending
}
}
let blackColor = UIColor(red: 0, green: 0, blue: 0, alpha: 1)
let whiteColor = UIColor(red: 1, green: 1, blue: 1, alpha: 1)
let colorSpace = CGColorSpaceCreateDeviceRGB()
let raw = malloc(bytesPerRow * height)
let bitmapInfo = CGImageAlphaInfo.PremultipliedFirst.rawValue
let ctx = CGBitmapContextCreate(raw, width, height, bitsPerComponent, bytesPerRow, colorSpace, bitmapInfo)
CGContextDrawImage(ctx, CGRectMake(0, 0, CGFloat(width), CGFloat(height)), cgImage)
let data = UnsafePointer<UInt8>(CGBitmapContextGetData(ctx))
let leftEdgeColors = NSCountedSet(capacity: height)
let imageColors = NSCountedSet(capacity: width * height)
for x in 0..<width {
for y in 0..<height {
let pixel = ((width * y) + x) * bytesPerPixel
let color = UIColor(
red: CGFloat(data[pixel+1])/255,
green: CGFloat(data[pixel+2])/255,
blue: CGFloat(data[pixel+3])/255,
alpha: 1
)
// A lot of albums have white or black edges from crops, so ignore the first few pixels
if 5 <= x && x <= 10 {
leftEdgeColors.addObject(color)
}
imageColors.addObject(color)
}
}
// Get background color
var enumerator = leftEdgeColors.objectEnumerator()
var sortedColors = NSMutableArray(capacity: leftEdgeColors.count)
while let kolor = enumerator.nextObject() as? UIColor {
let colorCount = leftEdgeColors.countForObject(kolor)
if randomColorsThreshold < colorCount {
sortedColors.addObject(PCCountedColor(color: kolor, count: colorCount))
}
}
sortedColors.sortUsingComparator(sortedColorComparator)
var proposedEdgeColor: PCCountedColor
if 0 < sortedColors.count {
proposedEdgeColor = sortedColors.objectAtIndex(0) as! PCCountedColor
} else {
proposedEdgeColor = PCCountedColor(color: blackColor, count: 1)
}
if proposedEdgeColor.color.isBlackOrWhite && 0 < sortedColors.count {
for i in 1..<sortedColors.count {
let nextProposedEdgeColor = sortedColors.objectAtIndex(i) as! PCCountedColor
if (CGFloat(nextProposedEdgeColor.count)/CGFloat(proposedEdgeColor.count)) > 0.3 {
if !nextProposedEdgeColor.color.isBlackOrWhite {
proposedEdgeColor = nextProposedEdgeColor
break
}
} else {
break
}
}
}
result.backgroundColor = proposedEdgeColor.color
// Get foreground colors
enumerator = imageColors.objectEnumerator()
sortedColors.removeAllObjects()
sortedColors = NSMutableArray(capacity: imageColors.count)
let findDarkTextColor = !result.backgroundColor.isDarkColor
while var kolor = enumerator.nextObject() as? UIColor {
kolor = kolor.colorWithMinimumSaturation(0.15)
if kolor.isDarkColor == findDarkTextColor {
let colorCount = imageColors.countForObject(kolor)
sortedColors.addObject(PCCountedColor(color: kolor, count: colorCount))
}
}
sortedColors.sortUsingComparator(sortedColorComparator)
for curContainer in sortedColors {
let kolor = (curContainer as! PCCountedColor).color
if result.primaryColor == nil {
if kolor.isContrastingColor(result.backgroundColor) {
result.primaryColor = kolor
}
} else if result.secondaryColor == nil {
if !result.primaryColor.isDistinct(kolor) || !kolor.isContrastingColor(result.backgroundColor) {
continue
}
result.secondaryColor = kolor
} else if result.detailColor == nil {
if !result.secondaryColor.isDistinct(kolor) || !result.primaryColor.isDistinct(kolor) || !kolor.isContrastingColor(result.backgroundColor) {
continue
}
result.detailColor = kolor
break
}
}
let isDarkBackgound = result.backgroundColor.isDarkColor
if result.primaryColor == nil {
result.primaryColor = isDarkBackgound ? whiteColor:blackColor
}
if result.secondaryColor == nil {
result.secondaryColor = isDarkBackgound ? whiteColor:blackColor
}
if result.detailColor == nil {
result.detailColor = isDarkBackgound ? whiteColor:blackColor
}
// Release the allocated memory
free(raw)
return result
}
} | mit | d276f766d71f72f5b9bc74f1e220dacb | 36.948357 | 156 | 0.581787 | 5.131429 | false | false | false | false |
carabina/GRDB.swift | GRDB/Foundation/DatabaseDateComponents.swift | 1 | 9652 | import Foundation
/**
DatabaseDateComponents reads and stores NSDateComponents in the database.
*/
public struct DatabaseDateComponents : DatabaseValueConvertible {
/// The available formats for reading and storing date components.
public enum Format : String {
/// The format "yyyy-MM-dd".
case YMD = "yyyy-MM-dd"
/// The format "yyyy-MM-dd HH:mm".
///
/// This format is lexically comparable with SQLite's CURRENT_TIMESTAMP.
case YMD_HM = "yyyy-MM-dd HH:mm"
/// The format "yyyy-MM-dd HH:mm:ss".
///
/// This format is lexically comparable with SQLite's CURRENT_TIMESTAMP.
case YMD_HMS = "yyyy-MM-dd HH:mm:ss"
/// The format "yyyy-MM-dd HH:mm:ss.SSS".
///
/// This format is lexically comparable with SQLite's CURRENT_TIMESTAMP.
case YMD_HMSS = "yyyy-MM-dd HH:mm:ss.SSS"
/// The format "HH:mm".
case HM = "HH:mm"
/// The format "HH:mm:ss".
case HMS = "HH:mm:ss"
/// The format "HH:mm:ss.SSS".
case HMSS = "HH:mm:ss.SSS"
}
// MARK: - NSDateComponents conversion
/// The date components
public let dateComponents: NSDateComponents
/// The database format
public let format: Format
/**
Creates a DatabaseDateComponents from an NSDateComponents and a format.
The result is nil if and only if *dateComponents* is nil.
- parameter dateComponents: An optional NSDateComponents.
- parameter format: The format used for storing the date components in the
database.
- returns: An optional DatabaseDateComponents.
*/
public init?(_ dateComponents: NSDateComponents?, format: Format) {
if let dateComponents = dateComponents {
self.format = format
self.dateComponents = dateComponents
} else {
return nil
}
}
// MARK: - DatabaseValueConvertible adoption
/// Returns a value that can be stored in the database.
public var databaseValue: DatabaseValue {
let dateString: String?
switch format {
case .YMD_HM, .YMD_HMS, .YMD_HMSS, .YMD:
let year = (dateComponents.year == NSDateComponentUndefined) ? 0 : dateComponents.year
let month = (dateComponents.month == NSDateComponentUndefined) ? 1 : dateComponents.month
let day = (dateComponents.day == NSDateComponentUndefined) ? 1 : dateComponents.day
dateString = NSString(format: "%04d-%02d-%02d", year, month, day) as String
default:
dateString = nil
}
let timeString: String?
switch format {
case .YMD_HM, .HM:
let hour = (dateComponents.hour == NSDateComponentUndefined) ? 0 : dateComponents.hour
let minute = (dateComponents.minute == NSDateComponentUndefined) ? 0 : dateComponents.minute
timeString = NSString(format: "%02d:%02d", hour, minute) as String
case .YMD_HMS, .HMS:
let hour = (dateComponents.hour == NSDateComponentUndefined) ? 0 : dateComponents.hour
let minute = (dateComponents.minute == NSDateComponentUndefined) ? 0 : dateComponents.minute
let second = (dateComponents.second == NSDateComponentUndefined) ? 0 : dateComponents.second
timeString = NSString(format: "%02d:%02d:%02d", hour, minute, second) as String
case .YMD_HMSS, .HMSS:
let hour = (dateComponents.hour == NSDateComponentUndefined) ? 0 : dateComponents.hour
let minute = (dateComponents.minute == NSDateComponentUndefined) ? 0 : dateComponents.minute
let second = (dateComponents.second == NSDateComponentUndefined) ? 0 : dateComponents.second
let nanosecond = (dateComponents.nanosecond == NSDateComponentUndefined) ? 0 : dateComponents.nanosecond
timeString = NSString(format: "%02d:%02d:%02d.%03d", hour, minute, second, Int(round(Double(nanosecond) / 1_000_000.0))) as String
default:
timeString = nil
}
return DatabaseValue(string: [dateString, timeString].flatMap { $0 }.joinWithSeparator(" "))
}
/**
Returns a DatabaseDateComponents if *databaseValue* contains a valid date.
- parameter databaseValue: A DatabaseValue.
- returns: An optional DatabaseDateComponents.
*/
public static func fromDatabaseValue(databaseValue: DatabaseValue) -> DatabaseDateComponents? {
// https://www.sqlite.org/lang_datefunc.html
//
// Supported formats are:
//
// - YYYY-MM-DD
// - YYYY-MM-DD HH:MM
// - YYYY-MM-DD HH:MM:SS
// - YYYY-MM-DD HH:MM:SS.SSS
// - YYYY-MM-DDTHH:MM
// - YYYY-MM-DDTHH:MM:SS
// - YYYY-MM-DDTHH:MM:SS.SSS
// - HH:MM
// - HH:MM:SS
// - HH:MM:SS.SSS
// We need a String
guard let string = String.fromDatabaseValue(databaseValue) else {
return nil
}
let dateComponents = NSDateComponents()
let scanner = NSScanner(string: string)
scanner.charactersToBeSkipped = NSCharacterSet()
let hasDate: Bool
// YYYY or HH
var initialNumber: Int = 0
if !scanner.scanInteger(&initialNumber) {
return nil
}
switch scanner.scanLocation {
case 2:
// HH
hasDate = false
let hour = initialNumber
if hour >= 0 && hour <= 23 {
dateComponents.hour = hour
} else {
return nil
}
case 4:
// YYYY
hasDate = true
let year = initialNumber
if year >= 0 && year <= 9999 {
dateComponents.year = year
} else {
return nil
}
// -
if !scanner.scanString("-", intoString: nil) {
return nil
}
// MM
var month: Int = 0
if scanner.scanInteger(&month) && month >= 1 && month <= 12 {
dateComponents.month = month
} else {
return nil
}
// -
if !scanner.scanString("-", intoString: nil) {
return nil
}
// DD
var day: Int = 0
if scanner.scanInteger(&day) && day >= 1 && day <= 31 {
dateComponents.day = day
} else {
return nil
}
// YYYY-MM-DD
if scanner.atEnd {
return DatabaseDateComponents(dateComponents, format: .YMD)
}
// T/space
if !scanner.scanString("T", intoString: nil) && !scanner.scanString(" ", intoString: nil) {
return nil
}
// HH
var hour: Int = 0
if scanner.scanInteger(&hour) && hour >= 0 && hour <= 23 {
dateComponents.hour = hour
} else {
return nil
}
default:
return nil
}
// :
if !scanner.scanString(":", intoString: nil) {
return nil
}
// MM
var minute: Int = 0
if scanner.scanInteger(&minute) && minute >= 0 && minute <= 59 {
dateComponents.minute = minute
} else {
return nil
}
// [YYYY-MM-DD] HH:MM
if scanner.atEnd {
if hasDate {
return DatabaseDateComponents(dateComponents, format: .YMD_HM)
} else {
return DatabaseDateComponents(dateComponents, format: .HM)
}
}
// :
if !scanner.scanString(":", intoString: nil) {
return nil
}
// SS
var second: Int = 0
if scanner.scanInteger(&second) && second >= 0 && second <= 59 {
dateComponents.second = second
} else {
return nil
}
// [YYYY-MM-DD] HH:MM:SS
if scanner.atEnd {
if hasDate {
return DatabaseDateComponents(dateComponents, format: .YMD_HMS)
} else {
return DatabaseDateComponents(dateComponents, format: .HMS)
}
}
// .
if !scanner.scanString(".", intoString: nil) {
return nil
}
// SSS
var millisecondDigits: NSString? = nil
if scanner.scanCharactersFromSet(NSCharacterSet.decimalDigitCharacterSet(), intoString: &millisecondDigits), var millisecondDigits = millisecondDigits {
if millisecondDigits.length > 3 {
millisecondDigits = millisecondDigits.substringToIndex(3)
}
dateComponents.nanosecond = millisecondDigits.integerValue * 1_000_000
} else {
return nil
}
// [YYYY-MM-DD] HH:MM:SS.SSS
if scanner.atEnd {
if hasDate {
return DatabaseDateComponents(dateComponents, format: .YMD_HMSS)
} else {
return DatabaseDateComponents(dateComponents, format: .HMSS)
}
}
// Unknown format
return nil
}
}
| mit | f15f5216139416954557749260b48cad | 32.630662 | 160 | 0.526937 | 5.197631 | false | false | false | false |
janeshsutharios/JKDropDown | JKDropDown/ViewController.swift | 1 | 1670 | // Created by janesh suthar on 7/4/17.
//
import UIKit
class ViewController: UIViewController,JKDropDownDelegate {
@IBOutlet weak var buttonSelect : UIButton!
var buttonFrame : CGRect?
var dropDownObject:JKDropDown!
var arrayIs : [String] = ["Edit","Love","Music","Location"]
let imageArray = ["1","2","3","4"]
override func viewDidLoad() {
super.viewDidLoad()
buttonSelect.addTarget(self, action: #selector(tapsOnButton), for: UIControlEvents.touchUpInside)
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(true)
buttonFrame = view.convert(buttonSelect.frame, to: view)
}
func tapsOnButton() {
if dropDownObject == nil {
dropDownObject = JKDropDown()
dropDownObject.dropDelegate = self
dropDownObject.showJKDropDown(senderObject: buttonSelect, height: 180, arrayList: arrayIs , arrayImages: imageArray,buttonFrame:buttonFrame!,direction : "down")
view.addSubview(dropDownObject)
}
else {
dropDownObject.hideDropDown(senderObject: buttonSelect,buttonFrame:buttonFrame!)
dropDownObject = nil
}
}
func recievedSelectedValue(name: String, imageName: String) {
dropDownObject.hideDropDown(senderObject: buttonSelect, buttonFrame: buttonFrame!)
dropDownObject = nil
buttonSelect.setTitle(name, for: .normal)
var imageView : UIImageView?
imageView = UIImageView(image: UIImage(named:imageName))
imageView?.frame = CGRect(x: 5, y: 5, width: 25, height: 25)
buttonSelect.addSubview(imageView!)
}
}
| mit | 11cd5ba805548d87788c21c46aaca1d5 | 39.731707 | 172 | 0.662275 | 4.757835 | false | false | false | false |
zzycami/firefox-ios | Providers/Cursor.swift | 4 | 1881 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
/**
* Status results for a Cursor
*/
enum CursorStatus {
case Success;
case Failure;
}
/**
* Provides a generic method of returning some data and status information about a request.
*/
protocol Cursor : SequenceType {
typealias ItemType
var count: Int { get }
// Extra status information
var status : CursorStatus { get }
var statusMessage : String { get }
// Collection iteration and access functions
subscript(index: Int) -> ItemType? { get }
func generate() -> GeneratorOf<ItemType>
}
/*
* A cursor implementation that wraps an array.
*/
class ArrayCursor<T> : Cursor {
private let data : [T];
let status : CursorStatus;
let statusMessage : String = "";
var count : Int {
if (status != CursorStatus.Success) {
return 0;
}
return data.count;
}
func generate() -> GeneratorOf<T> {
var nextIndex = 0;
return GeneratorOf<T>() {
if (nextIndex >= self.data.count || self.status != CursorStatus.Success) {
return nil;
}
return self.data[nextIndex++];
}
}
init(data: [T], status: CursorStatus, statusMessage: String) {
self.data = data;
self.status = status;
self.statusMessage = statusMessage;
}
init(data: [T]) {
self.data = data;
self.status = CursorStatus.Success;
self.statusMessage = "Success";
}
subscript(index: Int) -> T? {
if (index >= data.count || index < 0 || status != CursorStatus.Success) {
return nil;
}
return data[index];
}
}
| mpl-2.0 | d8349e72bb1dc0c2e8788b77f52e16f3 | 24.418919 | 91 | 0.587453 | 4.284738 | false | false | false | false |
bengottlieb/ios | FiveCalls/FiveCalls/ImpactViewModel.swift | 1 | 878 | //
// ImpactViewModel.swift
// FiveCalls
//
// Created by Ben Scheirman on 2/6/17.
// Copyright © 2017 5calls. All rights reserved.
//
import Foundation
struct ImpactViewModel {
let logs: [ContactLog]
init(logs: [ContactLog]) {
self.logs = logs
}
var numberOfCalls: Int {
return logs.count
}
var madeContactCount: Int {
return logs.filter { $0.outcome == "contact" || $0.outcome == "contacted" }.count
}
var unavailableCount: Int {
return logs.filter { $0.outcome == "unavailable" }.count
}
var voicemailCount: Int {
return logs.filter { $0.outcome == "voicemail" || $0.outcome == "vm" }.count
}
var weeklyStreakCount: Int {
let logDates = logs.map { $0.date }
return StreakCounter(dates: logDates, referenceDate: Date()).weekly
}
}
| mit | 9b1cd23bd1b7b06f37e250d29cb01eac | 22.078947 | 89 | 0.588369 | 3.796537 | false | false | false | false |
zhou9734/Warm | Warm/Classes/Me/View/MeTableFooterView.swift | 1 | 2212 | //
// MeTableFooterView.swift
// Warm
//
// Created by zhoucj on 16/9/18.
// Copyright © 2016年 zhoucj. All rights reserved.
//
import UIKit
class MeTableFooterView: UIView {
var menu: Menu?{
didSet{
guard let _menu = menu else{
return
}
iconImageView.image = UIImage(named: _menu.image!)
nameLbl.text = _menu.name
}
}
override init(frame: CGRect) {
super.init(frame: frame)
setupUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func setupUI(){
backgroundColor = UIColor(white: 0.93, alpha: 1.0)
contentView.addSubview(iconImageView)
contentView.addSubview(nameLbl)
contentView.addSubview(rightArrow)
addSubview(contentView)
}
private lazy var contentView: UIView = {
let v = UIView(frame: CGRect(x: 0.0, y: 10, width: ScreenWidth, height: 55))
v.backgroundColor = UIColor.whiteColor()
let gesture = UITapGestureRecognizer(target: self, action: Selector("settingClick"))
//scrollView同样要添加事件
v.userInteractionEnabled = true
v.addGestureRecognizer(gesture)
return v
}()
private lazy var iconImageView: UIImageView = {
let iv = UIImageView()
iv.frame = CGRect(x: 20.0, y: 20.0, width: 24, height: 24)
return iv
}()
private lazy var nameLbl: UILabel = {
let lbl = UILabel()
lbl.frame = CGRect(x: 54.0, y: 20.0, width: ScreenWidth - 100, height: 24.0)
lbl.textColor = UIColor.lightGrayColor()
lbl.textAlignment = .Left
lbl.font = UIFont.systemFontOfSize(16)
return lbl
}()
private lazy var rightArrow: UIButton = {
let btn = UIButton()
btn.setBackgroundImage(UIImage(named: "common_icon_arrow"), forState: .Normal)
btn.frame = CGRect(x: ScreenWidth - 33, y: 20.0, width: 17.0, height: 17.0)
return btn
}()
@objc private func settingClick(){
NSNotificationCenter.defaultCenter().postNotificationName(SettingClickNotication, object: self)
}
}
| mit | 8e99d4ff7e1ceb4f5fef43d89d6ad0cc | 28.662162 | 103 | 0.609112 | 4.262136 | false | false | false | false |
cdmx/MiniMancera | miniMancera/Model/HomeSplash/MHomeSplash.swift | 1 | 538 | import Foundation
class MHomeSplash
{
let items:[MHomeSplashProtocol]
private(set) weak var modelOption:MHomeOptions!
init(modelOption:MHomeOptions)
{
self.modelOption = modelOption
let itemOptions:MHomeSplashOptions = MHomeSplashOptions()
let itemScore:MHomeSplashScore = MHomeSplashScore(model:modelOption)
let itemDescr:MHomeSplashDescr = MHomeSplashDescr(model:modelOption)
items = [
itemOptions,
itemScore,
itemDescr]
}
}
| mit | b8fb8de292003773450315c6190fe69d | 25.9 | 76 | 0.66171 | 4.521008 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.