repo_name
stringlengths 7
91
| path
stringlengths 8
658
| copies
stringclasses 125
values | size
stringlengths 3
6
| content
stringlengths 118
674k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6.09
99.2
| line_max
int64 17
995
| alpha_frac
float64 0.3
0.9
| ratio
float64 2
9.18
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
giangbvnbgit128/AnViet | AnViet/Class/ViewControllers/HomeViewController/Cell/AVBaseNewFeedTableViewCell.swift | 1 | 1674 | //
// AVBaseNewFeedTableViewCell.swift
// AnViet
//
// Created by Bui Giang on 6/11/17.
// Copyright © 2017 Bui Giang. All rights reserved.
//
import UIKit
class AVBaseNewFeedTableViewCell: AVBaseTableViewCell {
// var host:String = ""
override func awakeFromNib() {
super.awakeFromNib()
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
}
func configCell(data:DataForItem, host:String,vc: UIViewController) {
}
func loadImage(url:String, complete: ((UIImage) -> Void)? ) {
let url = URL(string: url)
DispatchQueue.global().async {
let data = try? Data(contentsOf: url!)
DispatchQueue.main.async {
var imageData:UIImage = UIImage(named: "no_image.png")!
if data != nil && UIImage(data: data!) != nil {
imageData = UIImage(data: data!)!
}
if let rs = complete {
return rs(imageData)
}
}
}
}
func getArrayImageLoadFromUrl(arrayImageItem:[ImageItem],host: String, completed: (([UIImage])->Void)?) {
var arrayImage:[UIImage] = []
for i in 0..<arrayImageItem.count {
self.loadImage(url:host + arrayImageItem[i].urlImage, complete: { (image) in
arrayImage.append(image)
if arrayImage.count == arrayImageItem.count {
if let rs = completed {
return rs(arrayImage)
}
}
})
}
}
}
| apache-2.0 | 0a3f3c4d4ac210ddc8be2ee3acf66306 | 29.981481 | 109 | 0.531978 | 4.558583 | false | false | false | false |
onekiloparsec/SwiftAA | Tests/SwiftAATests/XCTestExtensions.swift | 2 | 1732 | //
// XCTestExtensions.swift
// SwiftAA
//
// Created by Alexander Vasenin on 27/12/2016.
// MIT Licence. See LICENCE file.
//
import XCTest
@testable import SwiftAA
/// This function is a type-safe way to test NumericType's equality
func AssertEqual<T : NumericType>(_ value1: T, _ value2: T, accuracy: T? = nil, _ message: String = "", file: StaticString = #file, line: UInt = #line) {
if let _accuracy = accuracy {
XCTAssertEqual(value1.value, value2.value, accuracy: _accuracy.value, message, file: file, line: line)
} else {
XCTAssertEqual(value1.value, value2.value, message, file: file, line: line)
}
}
// See https://stackoverflow.com/questions/32873212/unit-test-fatalerror-in-swift?answertab=active#tab-top
// to make possible to unit test fatalError.
extension XCTestCase {
func assertFatalError(expectedMessage: String, testcase: @escaping () -> Void) {
// arrange
let expectation = self.expectation(description: "expectingFatalError")
var assertionMessage: String? = nil
// override fatalError. This will pause forever when fatalError is called.
FatalErrorUtil.replaceFatalError { message, _, _ in
assertionMessage = message
expectation.fulfill()
unreachable()
}
// act, perform on separate thead because a call to fatalError pauses forever
DispatchQueue.global(qos: .userInitiated).async(execute: testcase)
waitForExpectations(timeout: 0.1) { _ in
// assert
XCTAssertEqual(assertionMessage, expectedMessage)
// clean up
FatalErrorUtil.restoreFatalError()
}
}
}
| mit | 0d91c2a1e9d9b9ab6f6e6921b6e52b94 | 34.346939 | 153 | 0.644919 | 4.395939 | false | true | false | false |
WhisperSystems/Signal-iOS | SignalServiceKit/src/Util/UserProfileFinder.swift | 1 | 4664 | //
// Copyright (c) 2019 Open Whisper Systems. All rights reserved.
//
import Foundation
@objc
class AnyUserProfileFinder: NSObject {
let grdbAdapter = GRDBUserProfileFinder()
let yapdbAdapter = YAPDBSignalServiceAddressIndex()
let yapdbUsernameAdapter = YAPDBUserProfileFinder()
}
extension AnyUserProfileFinder {
@objc(userProfileForAddress:transaction:)
func userProfile(for address: SignalServiceAddress, transaction: SDSAnyReadTransaction) -> OWSUserProfile? {
switch transaction.readTransaction {
case .grdbRead(let transaction):
return grdbAdapter.userProfile(for: address, transaction: transaction)
case .yapRead(let transaction):
return yapdbAdapter.fetchOne(for: address, transaction: transaction)
}
}
@objc
func userProfile(forUsername username: String, transaction: SDSAnyReadTransaction) -> OWSUserProfile? {
switch transaction.readTransaction {
case .grdbRead(let transaction):
return grdbAdapter.userProfile(forUsername: username.lowercased(), transaction: transaction)
case .yapRead(let transaction):
return yapdbUsernameAdapter.userProfile(forUsername: username.lowercased(), transaction: transaction)
}
}
}
@objc
class GRDBUserProfileFinder: NSObject {
func userProfile(for address: SignalServiceAddress, transaction: GRDBReadTransaction) -> OWSUserProfile? {
if let userProfile = userProfileForUUID(address.uuid, transaction: transaction) {
return userProfile
} else if let userProfile = userProfileForPhoneNumber(address.phoneNumber, transaction: transaction) {
return userProfile
} else {
return nil
}
}
private func userProfileForUUID(_ uuid: UUID?, transaction: GRDBReadTransaction) -> OWSUserProfile? {
guard let uuidString = uuid?.uuidString else { return nil }
let sql = "SELECT * FROM \(UserProfileRecord.databaseTableName) WHERE \(userProfileColumn: .recipientUUID) = ?"
return OWSUserProfile.grdbFetchOne(sql: sql, arguments: [uuidString], transaction: transaction)
}
private func userProfileForPhoneNumber(_ phoneNumber: String?, transaction: GRDBReadTransaction) -> OWSUserProfile? {
guard let phoneNumber = phoneNumber else { return nil }
let sql = "SELECT * FROM \(UserProfileRecord.databaseTableName) WHERE \(userProfileColumn: .recipientPhoneNumber) = ?"
return OWSUserProfile.grdbFetchOne(sql: sql, arguments: [phoneNumber], transaction: transaction)
}
func userProfile(forUsername username: String, transaction: GRDBReadTransaction) -> OWSUserProfile? {
let sql = "SELECT * FROM \(UserProfileRecord.databaseTableName) WHERE \(userProfileColumn: .username) = ? LIMIT 1"
return OWSUserProfile.grdbFetchOne(sql: sql, arguments: [username], transaction: transaction)
}
}
@objc
public class YAPDBUserProfileFinder: NSObject {
public static let extensionName = "index_on_username"
private static let usernameKey = "usernameKey"
@objc
public static func asyncRegisterDatabaseExtensions(_ storage: OWSStorage) {
storage.asyncRegister(extensionConfig(), withName: extensionName)
}
static func extensionConfig() -> YapDatabaseSecondaryIndex {
let setup = YapDatabaseSecondaryIndexSetup()
setup.addColumn(usernameKey, with: .text)
let handler = YapDatabaseSecondaryIndexHandler.withObjectBlock { _, dict, _, _, object in
guard let userProfile = object as? OWSUserProfile else { return }
dict[usernameKey] = userProfile.username
}
return YapDatabaseSecondaryIndex.init(setup: setup, handler: handler, versionTag: "1")
}
func userProfile(forUsername username: String, transaction: YapDatabaseReadTransaction) -> OWSUserProfile? {
guard let ext = transaction.safeSecondaryIndexTransaction(YAPDBUserProfileFinder.extensionName) else {
owsFailDebug("missing extension")
return nil
}
let queryFormat = String(format: "WHERE %@ = \"%@\"", YAPDBUserProfileFinder.usernameKey, username)
let query = YapDatabaseQuery(string: queryFormat, parameters: [])
var matchedProfile: OWSUserProfile?
ext.enumerateKeysAndObjects(matching: query) { _, _, object, stop in
guard let userProfile = object as? OWSUserProfile else {
owsFailDebug("Unexpected object type")
return
}
matchedProfile = userProfile
stop.pointee = true
}
return matchedProfile
}
}
| gpl-3.0 | b39d7957fe1a2801e102c107697ae4ae | 41.4 | 126 | 0.698971 | 5.053088 | false | false | false | false |
SomeSimpleSolutions/MemorizeItForever | MemorizeItForeverCore/MemorizeItForeverCore/Services/Depot/DepotPhraseService.swift | 1 | 1429 | //
// DepotPhraseService.swift
// MemorizeItForeverCore
//
// Created by Hadi Zamani on 11/14/19.
// Copyright © 2019 SomeSimpleSolutions. All rights reserved.
//
final public class DepotPhraseService: DepotPhraseServiceProtocol {
private var dataAccess: DepotPhraseDataAccessProtocol
init(dataAccess: DepotPhraseDataAccessProtocol){
self.dataAccess = dataAccess
}
public func save(_ phrase: String){
do{
var depot = DepotPhraseModel()
depot.phrase = phrase
try dataAccess.save(depotPhraseModel: depot)
}
catch{
}
}
public func save(_ phrases: [String]){
do{
var depots = [DepotPhraseModel]()
for phrase in phrases {
var depot = DepotPhraseModel()
depot.phrase = phrase
depots.append(depot)
}
try dataAccess.save(depotPhraseModels: depots)
}
catch{
}
}
public func delete(_ model: DepotPhraseModel) -> Bool{
do{
try dataAccess.delete(model)
return true
}
catch{
}
return false
}
public func get() -> [DepotPhraseModel]{
do{
return try dataAccess.fetchAll()
}
catch{
}
return []
}
}
| mit | 15deb8fe4addf8f6e3e51022c6e7b5e3 | 22.032258 | 67 | 0.521709 | 4.840678 | false | false | false | false |
gfiumara/TwentyOne | TwentyOne/support/Constants.swift | 1 | 828 | /*
* Constants.swift
* Part of https://github.com/gfiumara/TwentyOne by Gregory Fiumara.
* See LICENSE for details.
*/
import Foundation
struct Constants
{
static let BackgroundSessionID = "com.gregfiumara.twentyone.backgroundDownload"
static let AppGroupID = "group.com.gregfiumara.twentyone"
static let BlockListURL:URL = URL.init(string:"https://raw.githubusercontent.com/gfiumara/TwentyOne/master/SafariExtension/twentyone.safariextension/blockerList.json")!
static let SettingsAppURL = URL.init(string:"prefs://")!
static let ContentBlockerBundleID = "com.gregfiumara.twentyone.contentblocker"
static let BlockerListNameKey = "blockerList"
static let JSONExtension = "json"
static let BlockerListRetrievedDateKey = "BlockerListRetrievedDate"
static let BlockerListUpdatedDateKey = "BlockerListUpdatedDate"
}
| bsd-3-clause | ba50c360247b71df30e4e917fdf392fb | 40.4 | 169 | 0.80314 | 3.6 | false | false | false | false |
practicalswift/swift | validation-test/compiler_crashers_2_fixed/0134-rdar35947198.swift | 27 | 1420 | // RUN: %target-swift-frontend %s -O -emit-sil | %FileCheck %s
// CHECK-LABEL: sil shared [transparent] [thunk] @$sSf4main7NumProtA2aBP5valueSdyFTW : $@convention(witness_method: NumProt) (@in_guaranteed Float) -> Double
// CHECK-NOT: %1 = load %0 : $*Float
// CHECK-NOT: function_ref @$sSf4mainE5valueSdyF : $@convention(method) (Float) -> Double
// CHECK: %1 = struct_element_addr %0 : $*Float, #Float._value // user: %2
// CHECK: %2 = load %1 : $*Builtin.FPIEEE32 // user: %3
// CHECK: %3 = builtin "fpext_FPIEEE32_FPIEEE64"(%2 : $Builtin.FPIEEE32) : $Builtin.FPIEEE64 // user: %4
// CHECK: %4 = struct $Double (%3 : $Builtin.FPIEEE64) // user: %5
// CHECK: return %4 : $Double
public protocol NumProt: Prot {
func value() -> Double
}
extension Float: NumProt {
public func value() -> Double {
return Double(self)
}
}
public protocol Prot: CustomStringConvertible {
func getOp() -> Op
}
extension Prot {
public func getOp() -> Op {
return Op("\(self) ")
}
}
public protocol CompProt: Prot {}
open class Op: CompProt {
fileprivate var valueText = ""
open var description: String {
return "42"
}
open func getOp() -> Op {
return self
}
public init(_ value: Double) {
self.valueText = "\(value)"
}
public init(_ operationString: String) {
self.valueText = operationString
}
}
| apache-2.0 | 0d4510a67e1d535efbba88571bd81afb | 26.307692 | 157 | 0.607746 | 3.405276 | false | false | false | false |
nasust/LeafViewer | LeafViewer/classes/App.swift | 1 | 2360 | //
// Created by hideki on 2017/06/22.
// Copyright (c) 2017 hideki. All rights reserved.
//
import Foundation
class App {
static let keyViewMode = "viewMode"
static let keyCenterWindow = "centerWindow"
static let keyRecentFile = "recentFile"
static let keyToolBarHide = "toolBarHide"
static var configIsCenterWindow: Bool {
get {
if UserDefaults.standard.object(forKey: App.keyCenterWindow) != nil {
return UserDefaults.standard.bool(forKey: App.keyCenterWindow)
} else {
return true
}
}
set {
UserDefaults.standard.set(newValue, forKey: App.keyCenterWindow)
}
}
static var configViewMode: ViewMode {
get {
if UserDefaults.standard.object(forKey: App.keyViewMode) != nil {
return ViewMode(rawValue: UserDefaults.standard.integer(forKey: App.keyViewMode))!
} else {
return ViewMode.automaticZoom
}
}
set {
UserDefaults.standard.set(newValue.rawValue, forKey: App.keyViewMode)
}
}
static func addRecentOpenFile(fileName: String) {
var recentFiles = Array<String>()
if UserDefaults.standard.object(forKey: App.keyRecentFile) != nil {
recentFiles = UserDefaults.standard.stringArray(forKey: App.keyRecentFile)!
}
recentFiles.insert(fileName, at: 0)
if recentFiles.count > 10 {
recentFiles.removeLast()
}
UserDefaults.standard.set(recentFiles, forKey: App.keyRecentFile)
}
static var recentOpenFile: Array<String> {
get {
var recentFiles = Array<String>()
if UserDefaults.standard.object(forKey: App.keyRecentFile) != nil {
recentFiles = UserDefaults.standard.stringArray(forKey: App.keyRecentFile)!
}
return recentFiles
}
}
static var hideToolBar: Bool {
get {
if UserDefaults.standard.object(forKey: App.keyToolBarHide) != nil {
return UserDefaults.standard.bool(forKey: App.keyToolBarHide)
} else {
return false
}
}
set {
UserDefaults.standard.set(newValue, forKey: App.keyToolBarHide)
}
}
}
| gpl-3.0 | 3d34c64bdbe25f8c75961ed8d2026bf3 | 27.095238 | 98 | 0.588983 | 4.582524 | false | false | false | false |
faimin/ZDOpenSourceDemo | ZDOpenSourceSwiftDemo/Pods/lottie-ios/lottie-swift/src/Private/NodeRenderSystem/Nodes/OutputNodes/PathOutputNode.swift | 1 | 2372 | //
// PathNodeOutput.swift
// lottie-swift
//
// Created by Brandon Withrow on 1/30/19.
//
import Foundation
import CoreGraphics
/// A node that has an output of a BezierPath
class PathOutputNode: NodeOutput {
init(parent: NodeOutput?) {
self.parent = parent
}
let parent: NodeOutput?
fileprivate(set) var outputPath: CGPath? = nil
var lastUpdateFrame: CGFloat? = nil
var lastPathBuildFrame: CGFloat? = nil
var isEnabled: Bool = true
func hasOutputUpdates(_ forFrame: CGFloat) -> Bool {
guard isEnabled else {
let upstreamUpdates = parent?.hasOutputUpdates(forFrame) ?? false
outputPath = parent?.outputPath
return upstreamUpdates
}
/// Ask if parent was updated
let upstreamUpdates = parent?.hasOutputUpdates(forFrame) ?? false
/// If parent was updated and the path hasn't been built for this frame, clear the path.
if upstreamUpdates && lastPathBuildFrame != forFrame {
outputPath = nil
}
if outputPath == nil {
/// If the path is clear, build the new path.
lastPathBuildFrame = forFrame
let newPath = CGMutablePath()
if let parentNode = parent, let parentPath = parentNode.outputPath {
newPath.addPath(parentPath)
}
for path in pathObjects {
for subPath in path.paths {
newPath.addPath(subPath.cgPath())
}
}
outputPath = newPath
}
/// Return true if there were upstream updates or if this node was updated.
return upstreamUpdates || (lastUpdateFrame == forFrame)
}
// MARK: Internal
fileprivate(set) var totalLength: CGFloat = 0
fileprivate(set) var pathObjects: [CompoundBezierPath] = []
@discardableResult func removePaths(updateFrame: CGFloat?) -> [CompoundBezierPath] {
lastUpdateFrame = updateFrame
let returnPaths = pathObjects
outputPath = nil
totalLength = 0
pathObjects = []
return returnPaths
}
func setPath(_ path: BezierPath, updateFrame: CGFloat) {
lastUpdateFrame = updateFrame
outputPath = nil
totalLength = path.length
pathObjects = [CompoundBezierPath(path: path)]
}
func appendPath(_ path: CompoundBezierPath, updateFrame: CGFloat) {
lastUpdateFrame = updateFrame
outputPath = nil
totalLength = totalLength + path.length
pathObjects.append(path)
}
}
| mit | ef82eba17e26c540a8026f0cc2586c5c | 25.954545 | 92 | 0.670742 | 4.526718 | false | false | false | false |
kysonyangs/ysbilibili | Pods/SwiftDate/Sources/SwiftDate/DateInRegion.swift | 5 | 13312 | //
// SwiftDate, Full featured Swift date library for parsing, validating, manipulating, and formatting dates and timezones.
// Created by: Daniele Margutti
// Main contributors: Jeroen Houtzager
//
//
// 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
/// `DateInRegion` represent a Date in a specified world region: along with absolute date it essentially encapsulate
/// all informations about the time zone (`TimeZone`), calendar (`Calendar`) and locale (`Locale`).
/// These info are contained inside the `.region` property.
///
/// Using `DateInRegion` you can:
/// * Represent an absolute Date in a specific timezone/calendar/locale
/// * Easy access to all date components (day,month,hour,minute etc.) of the date in specified region
/// * Easily create a new date from string, date components or swift operators
/// * Compare date using Swift operators like `==, !=, <, >, <=, >=` and several
/// additional methods like `isInWeekend,isYesterday`...
/// * Change date by adding or subtracting elements with Swift operators
/// (e.g. `date + 2.days + 15.minutes`)
public class DateInRegion: CustomStringConvertible {
/// region in which the `DateInRegion` is expressed
public fileprivate(set) var region: Region
/// Absolute date represented outside the `region`
public internal(set) var absoluteDate: Date
/// This is a reference to use formatters
public fileprivate(set) var formatters: Formatters
public class Formatters {
private var timeZone: TimeZone
private var calendar: Calendar
private var locale: Locale
/// `DateFormatter` reserved instance (nil unless you set `.useSharedFormatters = false`)
private var customDateFormatter: DateFormatter? = nil
/// `ISO8601DateTimeFormatter` reserved instance (nil unless you set `.useSharedFormatters = false`)
private var customISO8601Formatter: ISO8601DateTimeFormatter? = nil
/// `DateIntervalFormatter` reserved instance (nil unless you set `.useSharedFormatters = false`)
private var customDateIntervalFormatter: DateIntervalFormatter? = nil
/// If true this instance of `DateInRegion` will use formatters shared along calling thread.
/// If false a new date formatter is created automatically and used only by a single `DateInRegion`
/// Usually you don't need to create a single formatter for each DateInRegion because this
/// operation is expensive.
/// Unless you need of a particular behaviour you will be happy enough to share a single formatter
/// for each thread.
public var useSharedFormatters: Bool = true
public init(region: Region) {
self.timeZone = region.timeZone
self.calendar = region.calendar
self.locale = region.locale
}
public func isoFormatter() -> ISO8601DateTimeFormatter {
var formatter: ISO8601DateTimeFormatter? = nil
if useSharedFormatters == true {
let name = "SwiftDate_\(NSStringFromClass(ISO8601DateTimeFormatter.self))"
formatter = localThreadSingleton(key: name, create: { (Void) -> ISO8601DateTimeFormatter in
return ISO8601DateTimeFormatter()
})
} else {
if customISO8601Formatter == nil {
customISO8601Formatter = ISO8601DateTimeFormatter()
formatter = customISO8601Formatter
}
}
formatter!.locale = self.locale
return formatter!
}
/// Return an `DateFormatter` instance. Returned instance is the one shared along calling thread
/// if `.useSharedFormatters = false`; otherwise a reserved instance is created for this `DateInRegion`
///
/// - parameter format: if not nil a new `.dateFormat` is also set
///
/// - returns: a new instance of the formatter
public func dateFormatter(format: String? = nil, heuristics: Bool = true) -> DateFormatter {
var formatter: DateFormatter? = nil
if useSharedFormatters == true {
let name = "SwiftDate_\(NSStringFromClass(DateFormatter.self))"
formatter = localThreadSingleton(key: name, create: { (Void) -> DateFormatter in
return DateFormatter()
})
} else {
if customDateFormatter == nil {
customDateFormatter = DateFormatter()
formatter = customDateFormatter
}
}
if format != nil {
formatter!.dateFormat = format!
}
formatter!.timeZone = self.timeZone
formatter!.calendar = self.calendar
formatter!.locale = self.locale
formatter!.isLenient = heuristics
return formatter!
}
/// Return an `DateIntervalFormatter` instance. Returned instance is the one shared along calling thread
/// if `.useSharedFormatters = false`; otherwise a reserved instance is created for this `DateInRegion`
///
/// - returns: a new instance of the formatter
public func intervalFormatter() -> DateIntervalFormatter {
var formatter: DateIntervalFormatter? = nil
if useSharedFormatters == true {
let name = "SwiftDate_\(NSStringFromClass(DateIntervalFormatter.self))"
formatter = localThreadSingleton(key: name, create: { (Void) -> DateIntervalFormatter in
return DateIntervalFormatter()
})
} else {
if customDateIntervalFormatter == nil {
customDateIntervalFormatter = DateIntervalFormatter()
formatter = customDateIntervalFormatter
}
}
formatter!.timeZone = self.timeZone
formatter!.calendar = self.calendar
formatter!.locale = self.locale
return formatter!
}
}
/// Initialize a new `DateInRegion` object from an absolute date and a destination region.
/// The new instance express given date into specified region.
///
/// - parameter absoluteDate: absolute `Date` object
/// - parameter region: `Region` in which you would express given date (absolute time will be converted into passed region)
///
/// - returns: a new instance of the `DateInRegion` object
public init(absoluteDate: Date, in region: Region? = nil) {
let srcRegion = region ?? Region.Local()
self.absoluteDate = absoluteDate
self.region = srcRegion
self.formatters = Formatters(region: srcRegion)
}
/// Initialize a new DateInRegion set to the current date in local's device region (`Region.Local()`).
///
/// - returns: a new DateInRegion object
public init() {
self.absoluteDate = Date()
self.region = Region.Local()
self.formatters = Formatters(region: self.region)
}
/// Initialize a new `DateInRegion` object from a `DateComponents` object.
/// Both `TimeZone`, `Locale` and `Calendar` must be specified in `DateComponents` instance in order to get a valid result; if omitted a `MissingCalTzOrLoc` exception will thrown.
/// If from given components a valid Date cannot be created a `FailedToParse`
/// exception will thrown.
///
/// - parameter components: `DateComponents` with valid components used to generate a new date
///
/// - returns: a new `DateInRegion` from given components
public init?(components: DateComponents) {
guard let srcRegion = Region(components: components) else {
return nil
}
guard let absDate = srcRegion.calendar.date(from: components) else {
return nil
}
self.absoluteDate = absDate
self.region = srcRegion
self.formatters = Formatters(region: srcRegion)
}
/// Initialize a new `DateInRegion` where components are specified in an dictionary
/// where the key is `Calendar.Component` and the value is an int; region informations
/// (timezone, locale and calendars) are specified separately by the region parameter.
///
/// - parameter components: calendar components keys and values to assign
/// - parameter region: region in which the date is expressed. If `nil` local region will used instead (`Region.Local()`)
///
/// - returns: a new `DateInRegion` instance expressed in passed region, `nil` if parse fails
public init?(components: [Calendar.Component : Int], fromRegion region: Region? = nil) {
let srcRegion = region ?? Region.Local()
self.formatters = Formatters(region: srcRegion)
let cmp = DateInRegion.componentsFrom(values: components, setRegion: srcRegion)
guard let absDate = srcRegion.calendar.date(from: cmp) else {
return nil
}
self.absoluteDate = absDate
self.region = srcRegion
}
/// Parse a string using given formats; the first format which produces a valid `DateInRegion`
/// instance returns parsed instance. If none of passed formats can produce a valid region `nil`
/// is returned.
///
/// - Parameters:
/// - string: string to parse
/// - formats: formats used for parsing. Formats are evaluated in order.
/// - parameter region: region in which the date is expressed. If `nil` local region will used instead (`Region.Local()`). When `.iso8601` or `.iso8601Auto` is used, `region` parameter is ignored (timezone is set automatically by reading the string.
/// - returns: a new `DateInRegion` instance expressed in passed region, `nil` if parse fails
public class func date(string: String, formats: [DateFormat], fromRegion region: Region? = nil) -> DateInRegion? {
for format in formats {
if let date = DateInRegion(string: string, format: format, fromRegion: region) {
return date
}
}
return nil
}
/// Initialize a new `DateInRegion` created from passed format rexpressed in specified region.
///
/// - parameter string: string with date to parse
/// - parameter format: format in which the date is expressed (see `DateFormat`)
/// - parameter region: region in which the date should be expressed (if nil `Region.Local()` will be used instead)
/// When `.iso8601` or `.iso8601Auto` is used, `region.timezone' is ignored (timezone is set automatically by reading the string; Region `calendar` and `locale` are used)
/// - returns: a new DateInRegion from given string
public init?(string: String, format: DateFormat, fromRegion region: Region? = nil) {
var srcRegion = region ?? Region.Local()
self.formatters = Formatters(region: srcRegion)
switch format {
case .custom(let format):
guard let date = self.formatters.dateFormatter(format: format).date(from: string) else {
return nil
}
self.absoluteDate = date
case .strict(let format):
guard let date = self.formatters.dateFormatter(format: format, heuristics: false).date(from: string) else {
return nil
}
self.absoluteDate = date
case .iso8601(_), .iso8601Auto:
let configuration = ISO8601Configuration(calendar: srcRegion.calendar)
guard let parser = ISO8601Parser(string, config: configuration), let date = parser.parsedDate, let tz = parser.parsedTimeZone else { return nil }
self.absoluteDate = date
srcRegion = Region(tz: tz, cal: srcRegion.calendar, loc: srcRegion.locale)
case .extended:
let format = "eee dd-MMM-yyyy GG HH:mm:ss.SSS zzz"
guard let date = self.formatters.dateFormatter(format: format).date(from: string) else {
return nil
}
self.absoluteDate = date
case .rss(let isAltRSS):
let format = (isAltRSS ? "d MMM yyyy HH:mm:ss ZZZ" : "EEE, d MMM yyyy HH:mm:ss ZZZ")
guard let date = self.formatters.dateFormatter(format: format).date(from: string) else {
return nil
}
self.absoluteDate = date
case .dotNET:
guard let parsed_date = DOTNETDateTimeFormatter.date(string, calendar: srcRegion.calendar) else {
return nil
}
self.absoluteDate = parsed_date.date
srcRegion = Region(tz: parsed_date.tz, cal: srcRegion.calendar, loc: srcRegion.locale)
}
self.region = srcRegion
}
/// Convert a `DateInRegion` instance to a new specified `Region`
///
/// - parameter newRegion: destination region in which returned `DateInRegion` instance will be expressed in
///
/// - returns: a new `DateInRegion` expressed in passed destination region
public func toRegion(_ newRegion: Region) -> DateInRegion {
return DateInRegion(absoluteDate: self.absoluteDate, in: newRegion)
}
/// Modify absolute date value of the `DateInRegion` instance by adding a fixed value of seconds
///
/// - parameter interval: seconds to add
public func add(interval: TimeInterval) {
self.absoluteDate.addTimeInterval(interval)
}
/// Return a description of the `DateInRegion`
public var description: String {
let formatter = DateFormatter()
formatter.dateStyle = .medium
formatter.timeStyle = .long
formatter.locale = self.region.locale
formatter.calendar = self.region.calendar
formatter.timeZone = self.region.timeZone
return formatter.string(from: self.absoluteDate)
}
}
| mit | b7d705e336f88a3d16dffbf7c9092c27 | 42.789474 | 254 | 0.726262 | 4.083436 | false | false | false | false |
tensorflow/examples | lite/examples/posenet/ios/PoseNet/Extensions/CVPixelBufferExtension.swift | 1 | 6175 | // Copyright 2019 The TensorFlow Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// =============================================================================
import Accelerate
import Foundation
extension CVPixelBuffer {
var size: CGSize {
return CGSize(width: CVPixelBufferGetWidth(self), height: CVPixelBufferGetHeight(self))
}
/// Returns a new `CVPixelBuffer` created by taking the self area and resizing it to the
/// specified target size. Aspect ratios of source image and destination image are expected to be
/// same.
///
/// - Parameters:
/// - from: Source area of image to be cropped and resized.
/// - to: Size to scale the image to(i.e. image size used while training the model).
/// - Returns: The cropped and resized image of itself.
func resize(from source: CGRect, to size: CGSize) -> CVPixelBuffer? {
let rect = CGRect(origin: .zero, size: self.size)
guard rect.contains(source) else {
os_log("Resizing Error: source area is out of index", type: .error)
return nil
}
guard abs(size.width / size.height - source.size.width / source.size.height) < 1e-5
else {
os_log(
"Resizing Error: source image ratio and destination image ratio is different",
type: .error)
return nil
}
let inputImageRowBytes = CVPixelBufferGetBytesPerRow(self)
let imageChannels = 4
CVPixelBufferLockBaseAddress(self, CVPixelBufferLockFlags(rawValue: 0))
defer { CVPixelBufferUnlockBaseAddress(self, CVPixelBufferLockFlags(rawValue: 0)) }
// Finds the address of the upper leftmost pixel of the source area.
guard
let inputBaseAddress = CVPixelBufferGetBaseAddress(self)?.advanced(
by: Int(source.minY) * inputImageRowBytes + Int(source.minX) * imageChannels)
else {
return nil
}
// Crops given area as vImage Buffer.
var croppedImage = vImage_Buffer(
data: inputBaseAddress, height: UInt(source.height), width: UInt(source.width),
rowBytes: inputImageRowBytes)
let resultRowBytes = Int(size.width) * imageChannels
guard let resultAddress = malloc(Int(size.height) * resultRowBytes) else {
return nil
}
// Allocates a vacant vImage buffer for resized image.
var resizedImage = vImage_Buffer(
data: resultAddress,
height: UInt(size.height), width: UInt(size.width),
rowBytes: resultRowBytes
)
// Performs the scale operation on cropped image and stores it in result image buffer.
guard vImageScale_ARGB8888(&croppedImage, &resizedImage, nil, vImage_Flags(0)) == kvImageNoError
else {
return nil
}
let releaseCallBack: CVPixelBufferReleaseBytesCallback = { mutablePointer, pointer in
if let pointer = pointer {
free(UnsafeMutableRawPointer(mutating: pointer))
}
}
var result: CVPixelBuffer?
// Converts the thumbnail vImage buffer to CVPixelBuffer
let conversionStatus = CVPixelBufferCreateWithBytes(
nil,
Int(size.width), Int(size.height),
CVPixelBufferGetPixelFormatType(self),
resultAddress,
resultRowBytes,
releaseCallBack,
nil,
nil,
&result
)
guard conversionStatus == kCVReturnSuccess else {
free(resultAddress)
return nil
}
return result
}
/// Returns the RGB `Data` representation of the given image buffer.
///
/// - Parameters:
/// - isModelQuantized: Whether the model is quantized (i.e. fixed point values rather than
/// floating point values).
/// - Returns: The RGB data representation of the image buffer or `nil` if the buffer could not be
/// converted.
func rgbData(
isModelQuantized: Bool
) -> Data? {
CVPixelBufferLockBaseAddress(self, .readOnly)
defer { CVPixelBufferUnlockBaseAddress(self, .readOnly) }
guard let sourceData = CVPixelBufferGetBaseAddress(self) else {
return nil
}
let width = CVPixelBufferGetWidth(self)
let height = CVPixelBufferGetHeight(self)
let sourceBytesPerRow = CVPixelBufferGetBytesPerRow(self)
let destinationBytesPerRow = Constants.rgbPixelChannels * width
// Assign input image to `sourceBuffer` to convert it.
var sourceBuffer = vImage_Buffer(
data: sourceData,
height: vImagePixelCount(height),
width: vImagePixelCount(width),
rowBytes: sourceBytesPerRow)
// Make `destinationBuffer` and `destinationData` for its data to be assigned.
guard let destinationData = malloc(height * destinationBytesPerRow) else {
os_log("Error: out of memory", type: .error)
return nil
}
defer { free(destinationData) }
var destinationBuffer = vImage_Buffer(
data: destinationData,
height: vImagePixelCount(height),
width: vImagePixelCount(width),
rowBytes: destinationBytesPerRow)
// Convert image type.
switch CVPixelBufferGetPixelFormatType(self) {
case kCVPixelFormatType_32BGRA:
vImageConvert_BGRA8888toRGB888(&sourceBuffer, &destinationBuffer, UInt32(kvImageNoFlags))
case kCVPixelFormatType_32ARGB:
vImageConvert_BGRA8888toRGB888(&sourceBuffer, &destinationBuffer, UInt32(kvImageNoFlags))
default:
os_log("The type of this image is not supported.", type: .error)
return nil
}
// Make `Data` with converted image.
let imageByteData = Data(
bytes: destinationBuffer.data, count: destinationBuffer.rowBytes * height)
if isModelQuantized { return imageByteData }
let imageBytes = [UInt8](imageByteData)
return Data(copyingBufferOf: imageBytes.map { Float($0) / Constants.maxRGBValue })
}
}
| apache-2.0 | e60b5e6799f989fc06b5ff2a4f7e7964 | 34.901163 | 100 | 0.691336 | 4.481132 | false | false | false | false |
dylan/colors | Sources/Color+Gradient.swift | 1 | 4015 | //
// Color+Gradient.swift
// Colors
//
// Created by Dylan Wreggelsworth on 4/11/17.
// Copyright © 2017 Colors. All rights reserved.
//
import Foundation
extension Color {
/// Represents the type of interpolation used when sampling colors.
///
/// - note:
/// - `.rgb` represent lerping across the RGB values of a color.
/// - `.hue` represents only lerping on the hue component.
public enum Interpolation {
case rgb
case hue
}
/// Samples a color across an `interpolation` type at a given position.
///
/// - Parameters:
/// - a: The starting color of the interpolation.
/// - b: The ending color of the interpolation.
/// - position: At what point in the interpolation the `Color` is sampled.
/// - interpolation: What interpolation method to use.
/// - Returns: The sampled `Color`.
public static func sample(from a: Color, through b: Color, at position: Float, using interpolation: Interpolation = .hue) -> Color {
func lerp(from a: Float, to b: Float, percent: Float) -> Float {
return (b - a) * percent + a
}
func hueLerpValues(a: Color, b: Color, percent: Percent) -> HSLComponents {
var tempA = a
var tempB = b
var result = HSLComponents(hue: 0, saturation: 0, luminosity: 0)
var delta = tempB.hsl.hue - tempA.hsl.hue
var p = percent
if tempA.hsl.hue > tempB.hsl.hue {
let temp = tempB
tempB = tempA
tempA = temp
delta = -1 * delta
p = 1 - percent
}
if delta > 0.5 {
tempA.hsl.hue = tempA.hsl.hue + 1.0
result.hue = (tempA.hsl.hue + p * (tempB.hsl.hue - tempA.hsl.hue))
}
if delta <= 0.5 {
result.hue = tempA.hsl.hue + p * delta
}
// Hack to make sure we cross over correctly.
if result.hue > 1.0 {
result.hue -= 1.0
}
return (hue: result.hue,
saturation: lerp(from: tempA.hsl.saturation, to: tempB.hsl.saturation, percent: p),
luminosity: lerp(from: tempA.hsl.luminosity, to: tempB.hsl.luminosity, percent: p))
}
switch interpolation {
case .hue:
var result = Color(hueLerpValues(a: a, b: b, percent: position))
result.alpha = lerp(from: a.alpha, to: b.alpha, percent: position)
return result
case .rgb:
return Color(red: lerp(from: a.rgb.red, to: b.rgb.red, percent: position),
green: lerp(from: a.rgb.green, to: b.rgb.green, percent: position),
blue: lerp(from: a.rgb.blue, to: b.rgb.blue, percent: position),
alpha: lerp(from: a.alpha, to: b.alpha, percent: position))
}
}
/// Given an array of `Color`s, sample across an interpolation until we have a spread or gradient.
///
/// - Parameters:
/// - colors: The array of `Colors` to interpolate through.
/// - size: The desired size of the final spread or gradient.
/// - interpolation: What interpolation method to use.
/// - Returns: The sampled `Color`s.
public static func spread(colors: [Color], to size: Int, using interpolation: Interpolation = .hue) -> [Color] {
var result = [Color]()
let dividingFactor = Float(colors.count - 1) / Float(size - 1)
for i in 0..<size {
let tmp = Float(i) * dividingFactor
let priorIndex = Int(floor(tmp))
let nextIndex = Int(ceil(tmp))
let percent = tmp - Float(priorIndex)
let color = Color.sample(from: colors[priorIndex], through: colors[nextIndex], at: percent, using: interpolation)
result.append(color)
}
return result
}
}
| mit | 8458285475eaccc841f28a0b6fb098cc | 37.228571 | 136 | 0.546587 | 3.95858 | false | false | false | false |
hachinobu/CleanQiitaClient | PresentationLayer/Routing/ItemList/ItemListRouting.swift | 1 | 3146 | //
// ItemListRouting.swift
// CleanQiitaClient
//
// Created by Takahiro Nishinobu on 2016/09/25.
// Copyright © 2016年 hachinobu. All rights reserved.
//
import Foundation
public protocol ItemListRouting: Routing {
func segueItem(id: String)
func presentErrorAlert(message: String)
}
//public class AllItemListRoutingImpl: ItemListRouting {
//
// weak public var viewController: UIViewController? {
// didSet {
// viewController?.navigationItem.backBarButtonItem = UIBarButtonItem(title: "", style: .plain, target: nil, action: nil)
// }
// }
//
// public func segueItem(id: String) {
//
// let stockersRepository = StockersRepositoryImpl.shared
// let stockRepository = StockItemRepositoryImpl.shared
// let itemRepository = ItemRepositoryImpl.shared
// let useCase = AllItemUseCaseImpl(stockItemRepository: stockRepository, stockersRepository: stockersRepository, itemRepository: itemRepository, itemId: id)
//
// let presenter = ItemPresenterImplFromAllItem(useCase: useCase)
//
// let vc = UIStoryboard(name: "ItemScreen", bundle: Bundle(for: ItemViewController.self)).instantiateInitialViewController() as! ItemViewController
// let routing = ItemRoutingImpl()
// routing.viewController = vc
//
// vc.injection(presenter: presenter, routing: routing)
// viewController?.navigationController?.pushViewController(vc, animated: true)
//
// }
//
// public func presentErrorAlert(message: String) {
// let alertController = UIAlertController(title: "エラー", message: message, preferredStyle: .alert)
// let action = UIAlertAction(title: "OK", style: .default, handler: nil)
// alertController.addAction(action)
// viewController?.navigationController?.present(alertController, animated: true, completion: nil)
// }
//
//}
//public class UserItemListRoutingImpl: AllItemListRoutingImpl {
//
// override public func segueItem(id: String) {
//
// let stockersRepository = StockersRepositoryImpl.shared
// let stockRepository = StockItemRepositoryImpl.shared
// let itemRepository = ItemRepositoryImpl.shared
// let useCase = AllItemUseCaseImpl(stockItemRepository: stockRepository, stockersRepository: stockersRepository, itemRepository: itemRepository, itemId: id)
//
// //ItemPresenterImplFromUserItemを使うとタップした時にRoutingを呼ばないPresenter
//// let presenter = ItemPresenterImplFromUserItem(useCase: useCase)
//
// let presenter = ItemPresenterImplFromAllItem(useCase: useCase)
//
// let vc = UIStoryboard(name: "ItemScreen", bundle: Bundle(for: ItemViewController.self)).instantiateInitialViewController() as! ItemViewController
// let routing = UserItemRoutingImpl()
// routing.viewController = vc
//
// vc.injection(presenter: presenter, routing: routing)
// viewController?.navigationController?.pushViewController(vc, animated: true)
//
// }
//
//}
| mit | ad6eb06243cc1be0ad503bb949e391dd | 40.959459 | 164 | 0.685668 | 4.354839 | false | false | false | false |
silence0201/Swift-Study | GuidedTour/18ErrorHandling.playground/Contents.swift | 1 | 4280 | import Foundation
//
enum VendingMachineError: Error{
case invalidSelection
case insufficientFunds(coinsNeeded: Int)
case outOfStock
}
func canThrowErrors() throws -> String {
return ""
}
func cannotThrowErrors() -> String{
return ""
}
struct Item {
var price: Int
var count: Int
}
class VendingMachine{
var inventory = [
"Candy Bar": Item(price: 12, count: 7),
"Chips": Item(price: 10, count: 4),
"Pretzels": Item(price: 7, count: 11)
]
var coinsDeposited = 0
func vend(itemNamed name: String) throws{
guard let item = inventory[name] else{
throw VendingMachineError.invalidSelection
}
guard item.price <= coinsDeposited else{
throw VendingMachineError.insufficientFunds(coinsNeeded: item.price - coinsDeposited)
}
coinsDeposited -= item.price
var newItem = item
newItem.count -= 1
inventory[name] = newItem
print("Dispensing \(name)")
}
}
let favoriteSnacks = [
"Alice": "Chips",
"Bob": "Licorice",
"Eve": "Pretzels",
]
func buyFavoriteSnack(person: String, vendingMachine: VendingMachine) throws {
let snackName = favoriteSnacks[person] ?? "Candy Bar"
try vendingMachine.vend(itemNamed: snackName)
}
struct PurchasedSnack {
let name: String
init(name: String, vendingMachine: VendingMachine) throws {
try vendingMachine.vend(itemNamed: name)
self.name = name
}
}
var vendingMachine = VendingMachine()
vendingMachine.coinsDeposited = 8
do {
try buyFavoriteSnack(person: "Alice", vendingMachine: vendingMachine)
// Enjoy delicious snack
} catch VendingMachineError.invalidSelection {
print("Invalid Selection")
} catch VendingMachineError.outOfStock {
print("Out of Stock")
} catch VendingMachineError.insufficientFunds(let coinsNeeded) {
print("Insufficient funds. Please insert an additional $\(coinsNeeded).")
}
//=============
enum UnlickError: Error{case unlucky}
func someThrowingfunction() throws -> Int{
let success = arc4random_uniform(5)
if success == 0 { throw UnlickError.unlucky}
return Int(success)
}
let x = try?someThrowingfunction()
if let x = x{
print(x)
}else{
print("error")
}
let y:Int?
do{
y = try someThrowingfunction()
}catch{
y = nil
}
struct Data { }
func fetchDataFromDisk() throws -> Data {
let success = arc4random_uniform(5)
if success == 0 { throw UnlickError.unlucky }
return Data()
}
func fetchDataFromServer() throws -> Data {
let success = arc4random_uniform(5)
if success == 0 { throw UnlickError.unlucky }
return Data()
}
func fetchData() -> Data? {
if let data = try? fetchDataFromDisk() { return data }
if let data = try? fetchDataFromServer() { return data }
return nil
}
fetchData()
//--------
enum FileError: Error {
case endOfFile
case fileClosed
}
func exists(_ filename: String) -> Bool { return true }
class FakeFile {
var isOpen = false
var filename = ""
var lines = 100
func readline() throws -> String? {
if self.isOpen {
if lines > 0 {
lines -= 1
return "line number \(lines) of text\n"
} else {
throw FileError.endOfFile
//return nil
}
} else {
throw FileError.fileClosed
}
}
}
func open(fileNamed: String) -> FakeFile {
let file = FakeFile()
file.filename = fileNamed
file.isOpen = true
print("\(file.filename) has been opened")
return file
}
func close(file: FakeFile) {
file.isOpen = false
print("\(file.filename) has been closed")
}
func processFile(named: String) throws {
if exists(named) {
let file = open(fileNamed: named)
defer {
close(file: file)
}
while let line = try file.readline() {
// Work with the file
print(line)
}
// close(file) is called here, at the end of the scope.
}
}
do {
try processFile(named: "myFakeFile")
} catch FileError.endOfFile {
print("Reached the end of the file")
} catch FileError.fileClosed {
print("The file isn't open")
}
| mit | 74597f0b065599c406d37f5aa70a0206 | 21.887701 | 97 | 0.618458 | 4.05303 | false | false | false | false |
el-hoshino/NotAutoLayout | Sources/NotAutoLayout/LayoutMaker/IndividualProperties/3-Element/MiddleCenterLeft.Individual.swift | 1 | 2735 | //
// MiddleCenterLeft.Individual.swift
// NotAutoLayout
//
// Created by 史翔新 on 2017/06/20.
// Copyright © 2017年 史翔新. All rights reserved.
//
import Foundation
extension IndividualProperty {
public struct MiddleCenterLeft {
let middleCenter: LayoutElement.Point
let left: LayoutElement.Horizontal
}
}
// MARK: - Make Frame
extension IndividualProperty.MiddleCenterLeft {
private func makeFrame(middleCenter: Point, left: Float, top: Float) -> Rect {
let height = (middleCenter.y - top).double
return self.makeFrame(middleCenter: middleCenter, left: left, height: height)
}
private func makeFrame(middleCenter: Point, left: Float, bottom: Float) -> Rect {
let height = (bottom - middleCenter.y).double
return self.makeFrame(middleCenter: middleCenter, left: left, height: height)
}
private func makeFrame(middleCenter: Point, left: Float, height: Float) -> Rect {
let x = left
let y = middleCenter.y - height.half
let width = (middleCenter.x - left).double
let frame = Rect(x: x, y: y, width: width, height: height)
return frame
}
}
// MARK: - Set A Line -
// MARK: Top
extension IndividualProperty.MiddleCenterLeft: LayoutPropertyCanStoreTopToEvaluateFrameType {
public func evaluateFrame(top: LayoutElement.Vertical, parameters: IndividualFrameCalculationParameters) -> Rect {
let middleCenter = self.middleCenter.evaluated(from: parameters)
let left = self.left.evaluated(from: parameters)
let top = top.evaluated(from: parameters)
return self.makeFrame(middleCenter: middleCenter, left: left, top: top)
}
}
// MARK: Bottom
extension IndividualProperty.MiddleCenterLeft: LayoutPropertyCanStoreBottomToEvaluateFrameType {
public func evaluateFrame(bottom: LayoutElement.Vertical, parameters: IndividualFrameCalculationParameters) -> Rect {
let middleCenter = self.middleCenter.evaluated(from: parameters)
let left = self.left.evaluated(from: parameters)
let bottom = bottom.evaluated(from: parameters)
return self.makeFrame(middleCenter: middleCenter, left: left, bottom: bottom)
}
}
// MARK: - Set A Length -
// MARK: Height
extension IndividualProperty.MiddleCenterLeft: LayoutPropertyCanStoreHeightToEvaluateFrameType {
public func evaluateFrame(height: LayoutElement.Length, parameters: IndividualFrameCalculationParameters) -> Rect {
let middleCenter = self.middleCenter.evaluated(from: parameters)
let left = self.left.evaluated(from: parameters)
let width = (middleCenter.x - left).double
let height = height.evaluated(from: parameters, withTheOtherAxis: .width(width))
return self.makeFrame(middleCenter: middleCenter, left: left, height: height)
}
}
| apache-2.0 | 02fbbb3769983e14e5b379c27701a980 | 25.930693 | 118 | 0.740809 | 3.994126 | false | false | false | false |
jpttsn/RazzleDazzle | Source/PathPositionAnimation.swift | 1 | 2253 | //
// PathPositionAnimation.swift
// RazzleDazzle
//
// Created by Laura Skelton on 6/30/15.
// Copyright © 2015 IFTTT. All rights reserved.
//
import UIKit
/**
Animates the view's position along the given path.
*/
public class PathPositionAnimation : Animation<CGFloat>, Animatable {
private let view : UIView
public var path : CGPathRef? {
didSet {
createKeyframeAnimation()
}
}
private let animationKey = "PathPosition"
public var rotationMode : String? = kCAAnimationRotateAuto {
didSet {
createKeyframeAnimation()
}
}
public init(view: UIView, path: CGPathRef?) {
self.view = view
self.path = path
super.init()
createKeyframeAnimation()
// CAAnimations are lost when application enters the background, so re-add them
NSNotificationCenter.defaultCenter().addObserver(
self,
selector: #selector(PathPositionAnimation.createKeyframeAnimation),
name: UIApplicationDidBecomeActiveNotification,
object: nil)
}
deinit {
NSNotificationCenter.defaultCenter().removeObserver(self)
}
public func animate(time: CGFloat) {
if !hasKeyframes() {return}
view.layer.timeOffset = CFTimeInterval(self[time])
}
public override func validateValue(value: CGFloat) -> Bool {
return (value >= 0) && (value <= 1)
}
@objc private func createKeyframeAnimation() {
// Set up a CAKeyframeAnimation to move the view along the path
view.layer.addAnimation(pathAnimation(), forKey: animationKey)
view.layer.speed = 0
view.layer.timeOffset = 0
}
private func pathAnimation() -> CAKeyframeAnimation {
let animation = CAKeyframeAnimation()
animation.keyPath = "position"
animation.path = path
animation.duration = 1
animation.additive = true
animation.repeatCount = Float.infinity
animation.calculationMode = kCAAnimationPaced
animation.rotationMode = rotationMode
animation.fillMode = kCAFillModeBoth
animation.removedOnCompletion = false
return animation
}
}
| mit | 42b1f9428e2fbe259f80c33d764908b0 | 29.026667 | 87 | 0.637211 | 5.118182 | false | false | false | false |
argent-os/argent-ios | app-ios/IdentitySSNModalViewController.swift | 1 | 8560 | //
// IdentitySSNModalViewController.swift
// app-ios
//
// Created by Sinan Ulkuatam on 6/2/16.
// Copyright © 2016 Sinan Ulkuatam. All rights reserved.
//
import Foundation
import UIKit
import MZFormSheetPresentationController
import VMaskTextField
import CWStatusBarNotification
import Crashlytics
class IdentitySSNModalViewController: UIViewController, UITextFieldDelegate {
let titleLabel = UILabel()
let ssnTextField = VMaskTextField()
let submitSSNButton = UIButton()
override func preferredStatusBarStyle() -> UIStatusBarStyle {
return UIStatusBarStyle.LightContent
}
override func viewDidLoad() {
super.viewDidLoad()
configureView()
setupNav()
}
private func configureView() {
// This will set to only one instance
self.view.backgroundColor = UIColor.whiteColor()
// screen width and height:
let screen = UIScreen.mainScreen().bounds
let screenWidth = screen.size.width
_ = screen.size.height
self.navigationController?.navigationBar.translucent = true
self.navigationController?.navigationBar.barTintColor = UIColor.lightGrayColor()
let imageFingerprint = UIImageView()
imageFingerprint.frame = CGRect(x: 140-30, y: 60, width: 60, height: 60)
imageFingerprint.contentMode = .ScaleAspectFit
self.view.addSubview(imageFingerprint)
titleLabel.text = ""
titleLabel.textAlignment = .Center
titleLabel.font = UIFont(name: "SFUIText-Regular", size: 18)
titleLabel.textColor = UIColor.lightBlue()
self.view.addSubview(titleLabel)
ssnTextField.frame = CGRect(x: 0, y: 90, width: 280, height: 150)
ssnTextField.placeholder = "123-45-6789"
ssnTextField.alpha = 0.8
ssnTextField.textAlignment = .Center
ssnTextField.font = UIFont(name: "SFUIText-Regular", size: 18)
ssnTextField.textColor = UIColor.darkBlue()
ssnTextField.mask = "#########"
ssnTextField.delegate = self
ssnTextField.keyboardType = .NumberPad
ssnTextField.secureTextEntry = true
ssnTextField.becomeFirstResponder()
submitSSNButton.frame = CGRect(x: 0, y: 220, width: 280, height: 60)
submitSSNButton.layer.borderColor = UIColor.whiteColor().CGColor
submitSSNButton.layer.borderWidth = 0
submitSSNButton.layer.cornerRadius = 0
submitSSNButton.layer.masksToBounds = true
submitSSNButton.setBackgroundColor(UIColor.pastelBlue(), forState: .Normal)
submitSSNButton.setBackgroundColor(UIColor.pastelBlue().darkerColor(), forState: .Highlighted)
var attribs: [String: AnyObject] = [:]
attribs[NSFontAttributeName] = UIFont(name: "SFUIText-Regular", size: 15)
attribs[NSForegroundColorAttributeName] = UIColor.whiteColor()
let str = adjustAttributedString("SUBMIT", spacing: 2, fontName: "SFUIText-Regular", fontSize: 14, fontColor: UIColor.whiteColor(), lineSpacing: 0.0, alignment: .Center)
submitSSNButton.setAttributedTitle(str, forState: .Normal)
submitSSNButton.addTarget(self, action: #selector(self.submitSSN(_:)), forControlEvents: .TouchUpInside)
let rectShape = CAShapeLayer()
rectShape.bounds = submitSSNButton.frame
rectShape.position = submitSSNButton.center
rectShape.path = UIBezierPath(roundedRect: submitSSNButton.bounds, byRoundingCorners: [.BottomLeft, .BottomRight], cornerRadii: CGSize(width: 5, height: 5)).CGPath
submitSSNButton.layer.backgroundColor = UIColor.mediumBlue().CGColor
//Here I'm masking the textView's layer with rectShape layer
submitSSNButton.layer.mask = rectShape
Account.getStripeAccount { (acct, err) in
//
if (acct?.pin)! == true {
imageFingerprint.image = UIImage(named: "IconSuccess")
imageFingerprint.frame = CGRect(x: 140-30, y: 100, width: 60, height: 60)
self.titleLabel.text = "SSN is provided"
self.titleLabel.frame = CGRect(x: 0, y: 165, width: 280, height: 20)
} else {
imageFingerprint.image = UIImage(named: "IconFingerprint")
self.view.addSubview(self.ssnTextField)
self.view.addSubview(self.submitSSNButton)
}
}
}
private func setupNav() {
let navigationBar = self.navigationController?.navigationBar
navigationBar!.backgroundColor = UIColor.offWhite()
navigationBar!.tintColor = UIColor.darkBlue()
// Create a navigation item with a title
let navigationItem = UINavigationItem()
// Create left and right button for navigation item
let leftButton = UIBarButtonItem(title: "Close", style: .Plain, target: self, action: #selector(self.close(_:)))
let font = UIFont(name: "SFUIText-Regular", size: 17)!
leftButton.setTitleTextAttributes([NSFontAttributeName: font, NSForegroundColorAttributeName:UIColor.mediumBlue()], forState: UIControlState.Normal)
leftButton.setTitleTextAttributes([NSFontAttributeName: font, NSForegroundColorAttributeName:UIColor.darkBlue()], forState: UIControlState.Highlighted)
// Create two buttons for the navigation item
navigationItem.leftBarButtonItem = leftButton
// Assign the navigation item to the navigation bar
navigationBar!.titleTextAttributes = [NSFontAttributeName: font, NSForegroundColorAttributeName:UIColor.darkGrayColor()]
navigationBar!.items = [navigationItem]
}
func close(sender: AnyObject) -> Void {
self.dismissViewControllerAnimated(true, completion: nil)
}
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
return ssnTextField.shouldChangeCharactersInRange(range, replacementString: string)
}
func submitSSN(sender: AnyObject) {
addActivityIndicatorButton(UIActivityIndicatorView(), button: submitSSNButton, color: .White)
if ssnTextField.text == "" || ssnTextField.text?.characters.count < 9 {
showGlobalNotification("Invalid number provided", duration: 2.0, inStyle: CWNotificationAnimationStyle.Top, outStyle: CWNotificationAnimationStyle.Top, notificationStyle: CWNotificationStyle.NavigationBarNotification, color: UIColor.brandRed())
return
}
let legalContent: [String: AnyObject] = [
"personal_id_number": ssnTextField.text!,
]
let legalJSON: [String: AnyObject] = [
"legal_entity" : legalContent
]
showGlobalNotification("Securely submitting ssn...", duration: 2.0, inStyle: CWNotificationAnimationStyle.Top, outStyle: CWNotificationAnimationStyle.Top, notificationStyle: CWNotificationStyle.NavigationBarNotification, color: UIColor.pastelBlue())
Account.saveStripeAccount(legalJSON) { (acct, bool, err) in
if bool {
let _ = Timeout(2) {
showGlobalNotification("SSN Submitted!", duration: 4.0, inStyle: CWNotificationAnimationStyle.Top, outStyle: CWNotificationAnimationStyle.Top, notificationStyle: CWNotificationStyle.NavigationBarNotification, color: UIColor.pastelBlue())
}
self.dismissViewControllerAnimated(true, completion: nil)
Answers.logCustomEventWithName("Identity Verification SSN Upload Success",
customAttributes: [:])
} else {
showGlobalNotification("An error occurred", duration: 4.0, inStyle: CWNotificationAnimationStyle.Top, outStyle: CWNotificationAnimationStyle.Top, notificationStyle: CWNotificationStyle.NavigationBarNotification, color: UIColor.neonOrange())
Answers.logCustomEventWithName("Identity Verification SSN Upload Failure",
customAttributes: [:])
self.dismissViewControllerAnimated(true, completion: nil)
}
}
}
override func viewDidDisappear(animated: Bool) {
}
override func viewDidAppear(animated: Bool) {
}
func close() -> Void {
self.dismissViewControllerAnimated(true, completion: nil)
}
} | mit | e7841c07e6ffeff2915a3c5d318d25c1 | 45.521739 | 257 | 0.664914 | 5.094643 | false | false | false | false |
MoralAlberto/SlackWebAPIKit | SlackWebAPIKit/Classes/Domain/Models/Team.swift | 1 | 481 | import Foundation
public class Team {
public var id: String?
public var name: String?
public var domain: String?
public var emailDomain: String?
public var icon: String?
init(id: String?,
name: String?,
domain: String?,
emailDomain: String?,
icon: String?) {
self.id = id
self.name = name
self.domain = domain
self.emailDomain = emailDomain
self.icon = icon
}
}
| mit | 743485584804629e96905adfba3010ef | 20.863636 | 38 | 0.557173 | 4.372727 | false | false | false | false |
kreeger/pinwheel | Classes/Adapters/Pinboard/Models/PinboardPost.swift | 1 | 1320 | //
// Pinwheel // PinboardPost.swift
// Copyright (c) 2014 Ben Kreeger. All rights reserved.
//
import Foundation
class PinboardPost {
let title: String
var extendedDescription: String?
let hashIdentifier: String
let href: NSURL
let meta: String
let shared: Bool
var tags: [String]?
let time: NSDate?
let toRead: Bool
init(_ responseDict: NSDictionary) {
// This also feels like it sucks to write.
title = responseDict["description"] as String
extendedDescription = responseDict["extended"] as? String
hashIdentifier = responseDict["hash"] as String
href = NSURL(string: responseDict["href"] as String)
meta = responseDict["meta"] as String
shared = responseDict["shared"] as String == "true"
tags = (responseDict["tags"] as String).componentsSeparatedByString(" ")
let f = NSDateFormatter()
f.dateFormat = "yyyy-MM-dd'T'HH:mm:ss'Z'"
if let value = f.dateFromString(responseDict["time"] as String) { time = value }
toRead = responseDict["toread"] as String == "true"
}
}
extension PinboardPost: Printable {
var description: String {
get {
return "(PinboardPost) title: \(title) / href: \(href) / time: \(time)"
}
}
} | mit | 2ece4245c9db2af00cd02894c9552b94 | 29.72093 | 88 | 0.618182 | 4.230769 | false | false | false | false |
buscarini/vitemo | vitemo/Carthage/Checkouts/SwiftCLI/SwiftCLI/CLI/CommandSignature.swift | 2 | 1878 | //
// CommandSignature.swift
// Pods
//
// Created by Jake Heiser on 3/9/15.
//
//
import Foundation
class CommandSignature {
var requiredParameters: [String] = []
var optionalParameters: [String] = []
var collectRemainingArguments = false
init(_ string: String) {
var parameters = string.componentsSeparatedByString(" ").filter { !$0.isEmpty }
let requiredRegex = NSRegularExpression(pattern: "^<.*>$", options: nil, error: nil)
let optionalRegex = NSRegularExpression(pattern: "^\\[<.*>\\]$", options: nil, error: nil)
for parameter in parameters {
if parameter == "..." {
assert(parameter == parameters.last, "The collection operator (...) must come at the end of a command signature.")
collectRemainingArguments = true
continue
}
let parameterRange = NSRange(location: 0, length: count(parameter))
if requiredRegex?.numberOfMatchesInString(parameter, options: nil, range: parameterRange) > 0 {
assert(optionalParameters.count == 0, "All required parameters must come before any optional parameter.")
required(parameter.trimEndsByLength(1))
} else if optionalRegex?.numberOfMatchesInString(parameter, options: nil, range: parameterRange) > 0 {
optional(parameter.trimEndsByLength(2))
} else {
assert(false, "Unrecognized parameter format: \(parameter)")
}
}
}
func required(parameter: String) {
requiredParameters.append(parameter)
}
func optional(parameter: String) {
optionalParameters.append(parameter)
}
var isEmpty: Bool {
return requiredParameters.isEmpty && optionalParameters.isEmpty
}
}
| mit | c875a6248d0f5abe16bc324420d150ff | 33.145455 | 130 | 0.602769 | 5.008 | false | false | false | false |
qvacua/vimr | VimR/VimR/MainWindow+Types.swift | 1 | 1585 | /**
* Tae Won Ha - http://taewon.de - @hataewon
* See LICENSE
*/
import Cocoa
import NvimView
import Workspace
extension MainWindow {
enum Action {
case cd(to: URL)
case setBufferList([NvimView.Buffer])
case newCurrentBuffer(NvimView.Buffer)
case bufferWritten(NvimView.Buffer)
case setDirtyStatus(Bool)
case becomeKey(isFullScreen: Bool)
case frameChanged(to: CGRect)
case scroll(to: Marked<Position>)
case setCursor(to: Marked<Position>)
case focus(FocusableView)
case openQuickly
case toggleAllTools(Bool)
case toggleToolButtons(Bool)
case setState(for: Tools, with: WorkspaceTool)
case setToolsState([(Tools, WorkspaceTool)])
case makeSessionTemporary
case setTheme(Theme)
case close
// RPC actions
case setFont(NSFont)
case setLinespacing(CGFloat)
case setCharacterspacing(CGFloat)
}
enum FocusableView {
case neoVimView
case fileBrowser
case bufferList
case markdownPreview
case htmlPreview
}
enum Tools: String, Codable {
static let all = Set(
[
Tools.fileBrowser,
Tools.buffersList,
Tools.preview,
Tools.htmlPreview,
]
)
case fileBrowser = "com.qvacua.vimr.tools.file-browser"
case buffersList = "com.qvacua.vimr.tools.opened-files-list"
case preview = "com.qvacua.vimr.tools.preview"
case htmlPreview = "com.qvacua.vimr.tools.html-preview"
}
enum OpenMode {
case `default`
case currentTab
case newTab
case horizontalSplit
case verticalSplit
}
}
| mit | fee0411f5cf90ee8653b9830fd210352 | 19.584416 | 64 | 0.680126 | 3.972431 | false | false | false | false |
rob-nash/Zip | examples/Sample/Sample/FileBrowser.swift | 2 | 5140 | //
// FileBrowser.swift
// Sample
//
// Created by Roy Marmelstein on 17/01/2016.
// Copyright © 2016 Roy Marmelstein. All rights reserved.
//
import UIKit
import Zip
class FileBrowser: UIViewController, UITableViewDataSource, UITableViewDelegate {
// IBOutlets
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var selectionCounter: UIBarButtonItem!
@IBOutlet weak var zipButton: UIBarButtonItem!
@IBOutlet weak var unzipButton: UIBarButtonItem!
let fileManager = FileManager.default
var path: URL? {
didSet {
updateFiles()
}
}
var files = [String]()
var selectedFiles = [String]()
//MARK: Lifecycle
override func viewDidLoad() {
if self.path == nil {
let documentsUrl = fileManager.urls(for: .documentDirectory, in: .userDomainMask)[0] as URL
self.path = documentsUrl
}
updateSelection()
}
//MARK: File manager
func updateFiles() {
if let filePath = path {
var tempFiles = [String]()
do {
self.title = filePath.lastPathComponent
tempFiles = try self.fileManager.contentsOfDirectory(atPath: filePath.path)
} catch {
if filePath.path == "/System" {
tempFiles = ["Library"]
}
if filePath.path == "/Library" {
tempFiles = ["Preferences"]
}
if filePath.path == "/var" {
tempFiles = ["mobile"]
}
if filePath.path == "/usr" {
tempFiles = ["lib", "libexec", "bin"]
}
}
self.files = tempFiles.sorted(){$0 < $1}
tableView.reloadData()
}
}
//MARK: UITableView Data Source and Delegate
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return files.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cellIdentifier = "FileCell"
var cell = UITableViewCell(style: .subtitle, reuseIdentifier: cellIdentifier)
if let reuseCell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier) {
cell = reuseCell
}
guard let path = path else {
return cell
}
cell.selectionStyle = .none
let filePath = files[(indexPath as NSIndexPath).row]
let newPath = path.appendingPathComponent(filePath).path
var isDirectory: ObjCBool = false
fileManager.fileExists(atPath: newPath, isDirectory: &isDirectory)
cell.textLabel?.text = files[(indexPath as NSIndexPath).row]
if isDirectory.boolValue {
cell.imageView?.image = UIImage(named: "Folder")
}
else {
cell.imageView?.image = UIImage(named: "File")
}
cell.backgroundColor = (selectedFiles.contains(filePath)) ? UIColor(white: 0.9, alpha: 1.0):UIColor.white
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let filePath = files[(indexPath as NSIndexPath).row]
if let index = selectedFiles.index(of: filePath) , selectedFiles.contains(filePath) {
selectedFiles.remove(at: index)
}
else {
selectedFiles.append(filePath)
}
updateSelection()
}
func updateSelection() {
tableView.reloadData()
selectionCounter.title = "\(selectedFiles.count) Selected"
zipButton.isEnabled = (selectedFiles.count > 0)
if (selectedFiles.count == 1) {
let filePath = selectedFiles.first
let pathExtension = path!.appendingPathComponent(filePath!).pathExtension
if pathExtension == "zip" {
unzipButton.isEnabled = true
}
else {
unzipButton.isEnabled = false
}
}
else {
unzipButton.isEnabled = false
}
}
//MARK: Actions
@IBAction func unzipSelection(_ sender: AnyObject) {
let filePath = selectedFiles.first
let pathURL = path!.appendingPathComponent(filePath!)
do {
let _ = try Zip.quickUnzipFile(pathURL)
self.selectedFiles.removeAll()
updateSelection()
updateFiles()
} catch {
print("ERROR")
}
}
@IBAction func zipSelection(_ sender: AnyObject) {
var urlPaths = [URL]()
for filePath in selectedFiles {
urlPaths.append(path!.appendingPathComponent(filePath))
}
do {
let _ = try Zip.quickZipFiles(urlPaths, fileName: "Archive")
self.selectedFiles.removeAll()
updateSelection()
updateFiles()
} catch {
print("ERROR")
}
}
}
| mit | 4c0d84a2f56479dc7ba1ba84cca435fd | 29.957831 | 113 | 0.564118 | 5.154463 | false | false | false | false |
mavieth/aws-sdk-ios-samples | S3BackgroundTransfer-Sample/Swift/S3BackgroundTransferSampleSwift/Constants.swift | 4 | 1194 | /*
* Copyright 2010-2015 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
import Foundation
//WARNING: To run this sample correctly, you must set the following constants.
let CognitoRegionType = AWSRegionType.Unknown
let DefaultServiceRegionType = AWSRegionType.Unknown
let CognitoIdentityPoolId: String = "YourPoolID"
let S3BucketName: String = "YourS3BucketName"
let S3DownloadKeyName: String = "YourDownloadKeyName"
let S3UploadKeyName: String = "uploadfileswift.txt"
let BackgroundSessionUploadIdentifier: String = "com.amazon.example.s3BackgroundTransferSwift.uploadSession"
let BackgroundSessionDownloadIdentifier: String = "com.amazon.example.s3BackgroundTransferSwift.downloadSession"
| apache-2.0 | 8079f24ff6fa4edd58e1832f22645fe4 | 43.222222 | 112 | 0.798995 | 4.075085 | false | false | false | false |
jverkoey/FigmaKit | Sources/FigmaKit/Node/Node.swift | 1 | 3651 | public class Node: Codable, PolymorphicDecodable, CustomDebugStringConvertible {
/// A string uniquely identifying this node within the document.
public let id: String
/// The name given to the node by the user in the tool.
public let name: String
/// Whether or not the node is visible on the canvas.
public let visible: Bool
/// The type of the node, refer to table below for details.
public let type: FigmaType
/// The nodes that are attached to this node.
public let children: [Node]
enum CodingKeys: String, CodingKey {
case id
case name
case visible
case type
case children
}
public enum FigmaType: String, Codable {
case booleanOperation = "BOOLEAN_OPERATION"
case canvas = "CANVAS"
case component = "COMPONENT"
case componentSet = "COMPONENT_SET"
case document = "DOCUMENT"
case ellipse = "ELLIPSE"
case frame = "FRAME"
case group = "GROUP"
case instance = "INSTANCE"
case line = "LINE"
case rectangle = "RECTANGLE"
case regularPolygon = "REGULAR_POLYGON"
case slice = "SLICE"
case star = "STAR"
case text = "TEXT"
case vector = "VECTOR"
case section = "SECTION"
}
static let typeMap: [FigmaType: Node.Type] = [
.booleanOperation: Node.BooleanOperationNode.self,
.canvas: Node.CanvasNode.self,
.component: Node.ComponentNode.self,
.componentSet: Node.ComponentSetNode.self,
.document: Node.DocumentNode.self,
.ellipse: Node.EllipseNode.self,
.frame: Node.FrameNode.self,
.group: Node.GroupNode.self,
.instance: Node.InstanceNode.self,
.line: Node.LineNode.self,
.rectangle: Node.RectangleNode.self,
.regularPolygon: Node.RegularPolygonNode.self,
.section: Node.SectionNode.self,
.slice: Node.SliceNode.self,
.star: Node.StarNode.self,
.text: Node.TextNode.self,
.vector: Node.VectorNode.self,
]
/// Decodes an array of Paint types from an unkeyed container.
///
/// The returned array's values will be instances of the corresponding type of
/// paint.
private static func decodePolymorphicArray(from decoder: UnkeyedDecodingContainer) throws
-> [Node]
{
return try decodePolyType(
from: decoder, keyedBy: Node.CodingKeys.self, key: .type, typeMap: Node.typeMap)
}
public required init(from decoder: Decoder) throws {
let keyedDecoder = try decoder.container(keyedBy: Self.CodingKeys)
self.id = try keyedDecoder.decode(String.self, forKey: .id)
self.name = try keyedDecoder.decode(String.self, forKey: .name)
self.visible = try keyedDecoder.decodeIfPresent(Bool.self, forKey: .visible) ?? true
self.type = try keyedDecoder.decode(FigmaType.self, forKey: .type)
guard keyedDecoder.contains(.children) else {
self.children = []
return
}
let childrenDecoder = try keyedDecoder.nestedUnkeyedContainer(forKey: .children)
self.children = try Node.decodePolymorphicArray(from: childrenDecoder)
}
public func encode(to encoder: Encoder) throws {
fatalError("Not yet implemented")
}
public var debugDescription: String {
return """
<\(Swift.type(of: self))
- id: \(id)
- name: \(name)
- visible: \(visible)
- type: \(type)
\(contentDescription.isEmpty ? "" : "\n" + contentDescription)
children:
\(children.debugDescription.indented(by: 2))
>
"""
}
var contentDescription: String {
return ""
}
}
extension Node: Hashable {
public static func == (lhs: Node, rhs: Node) -> Bool {
return lhs.id == rhs.id
}
public func hash(into hasher: inout Hasher) {
hasher.combine(id)
}
}
| apache-2.0 | 9156647d100523ac69c9f3596d69a271 | 29.680672 | 91 | 0.676253 | 3.913183 | false | false | false | false |
karivalkama/Agricola-Scripture-Editor | TranslationEditor/ConflictResolver.swift | 1 | 2920 | //
// ConflictResolver.swift
// TranslationEditor
//
// Created by Mikko Hilpinen on 14.12.2016.
// Copyright © 2017 SIL. All rights reserved.
//
import Foundation
// This interface goes through the database and resolves conflicts it finds
class ConflictResolver
{
// PROPERTIES -----------
static let instance = ConflictResolver()
// Type -> Id String + Conflicting property versions --> Merged properties
private var mergers = [String : (String, [PropertySet]) throws -> PropertySet]()
// INIT -------------------
private init()
{
// Static interface
}
// OTHER METHODS -------
// Adds a new tool to handle merge conflicts
func addMerger<T: Storable>(_ merger: @escaping ([T]) throws -> (T))
{
mergers[T.type] =
{
idString, conflictProperties in
return try merger(conflictProperties.map { try T.create(from: $0, withId: T.createId(from: idString)) }).toPropertySet
}
}
// Performs the conflict search algorithm
// Returns the number of handled conflicts
func run() -> Int
{
var conflictsHandled = 0
// Creates a query for all conflicting documents
let query = DATABASE.createAllDocumentsQuery()
query.allDocsMode = .onlyConflicts
// Runs the query and applies merge where possible
do
{
let results = try query.run()
try DATABASE.tryTransaction
{
// Goes through each conflict row
while let row = results.nextRow()
{
guard let document = row.document else
{
continue
}
// Finds the conflicting revisions
let conflicts = try document.getConflictingRevisions()
guard conflicts.count > 1 else
{
continue
}
guard let type = document[PROPERTY_TYPE] as? String else
{
print("ERROR: Conflict in typeless document \(document.documentID)")
continue
}
// Finds the correct merge function
guard let merge = self.mergers[type] else
{
print("ERROR: No conflict merger for document of type \(type)")
continue
}
let mergedProperties = try merge(document.documentID, conflicts.map { PropertySet($0.properties!) })
conflictsHandled += 1
let current = document.currentRevision!
for revision in conflicts
{
let newRevision = revision.createRevision()
if revision == current
{
// Sets merge results to the version marked as current
let finalProperties = newRevision.properties.map { PropertySet($0.toDict) }.or(PropertySet.empty) + mergedProperties
newRevision.properties = NSMutableDictionary(dictionary: finalProperties.toDict)
}
else
{
// Deletes the other revisions
newRevision.isDeletion = true
}
try newRevision.saveAllowingConflict()
}
}
}
}
catch
{
print("ERROR: Conflict handling failed with error: \(error)")
}
return conflictsHandled
}
}
| mit | 766944db62e5960aea565eb22318089c | 23.529412 | 123 | 0.647482 | 3.960651 | false | false | false | false |
RxSwiftCommunity/Action | Tests/iOS-Tests/ButtonTests.swift | 1 | 3931 | import Quick
import Nimble
import RxSwift
import Action
class ButtonTests: QuickSpec {
override func spec() {
it("is nil by default") {
let subject = UIButton(type: .system)
expect(subject.rx.action).to( beNil() )
}
it("respects setter") {
var subject = UIButton(type: .system)
let action = emptyAction()
subject.rx.action = action
expect(subject.rx.action) === action
}
it("disables the button while executing") {
var subject = UIButton(type: .system)
var observer: AnyObserver<Void>!
let action = CocoaAction(workFactory: { _ in
return Observable.create { (obsv) -> Disposable in
observer = obsv
return Disposables.create()
}
})
subject.rx.action = action
action.execute()
expect(subject.isEnabled).toEventually( beFalse() )
observer.onCompleted()
expect(subject.isEnabled).toEventually( beTrue() )
}
it("disables the button if the Action is disabled") {
var subject = UIButton(type: .system)
subject.rx.action = emptyAction(.just(false))
expect(subject.allTargets.count) == 1
expect(subject.isEnabled) == false
}
it("doesn't execute a disabled action when tapped") {
var subject = UIButton(type: .system)
var executed = false
subject.rx.action = CocoaAction(enabledIf: .just(false), workFactory: { _ in
executed = true
return .empty()
})
subject.sendActions(for: .touchUpInside)
expect(executed) == false
}
it("executes the action when tapped") {
var subject = UIButton(type: .system)
var executed = false
let action = CocoaAction(workFactory: { _ in
executed = true
return .empty()
})
subject.rx.action = action
// Setting the action has an asynchronous effect of adding a target.
expect(subject.allTargets.count) == 1
subject.test_executeTap()
expect(executed).toEventually( beTrue() )
}
it("disposes of old action subscriptions when re-set") {
var subject = UIButton(type: .system)
var disposed = false
autoreleasepool {
let disposeBag = DisposeBag()
let action = emptyAction()
subject.rx.action = action
action
.elements
.subscribe(onNext: nil, onError: nil, onCompleted: nil, onDisposed: {
disposed = true
})
.disposed(by: disposeBag)
}
subject.rx.action = nil
expect(disposed) == true
}
it("cancels the observable if the button is deallocated") {
var disposed = false
waitUntil { done in
autoreleasepool {
var subject = UIButton(type: .system)
let action = CocoaAction {
return Observable.create {_ in
Disposables.create {
disposed = true
done()
}
}
}
subject.rx.action = action
subject.rx.action?.execute()
}
}
expect(disposed) == true
}
}
}
func emptyAction(_ enabledIf: Observable<Bool> = .just(true)) -> CocoaAction {
return CocoaAction(enabledIf: enabledIf, workFactory: { _ in
return .empty()
})
}
| mit | 1ec93950d1a4956fe74eeb6ecfcc0e7b | 27.693431 | 89 | 0.492496 | 5.437068 | false | false | false | false |
davejlin/treehouse | swift/swift2/vending-machine/VendingMachine/ViewController.swift | 1 | 6126 | //
// ViewController.swift
// VendingMachine
//
// Created by Pasan Premaratne on 1/19/16.
// Copyright © 2016 Treehouse. All rights reserved.
//
import UIKit
private let reuseIdentifier = "vendingItem"
private let screenWidth = UIScreen.mainScreen().bounds.width
class ViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate {
@IBOutlet weak var collectionView: UICollectionView!
@IBOutlet weak var totalLabel: UILabel!
@IBOutlet weak var balanceLabel: UILabel!
@IBOutlet weak var quantityLabel: UILabel!
@IBOutlet weak var stepper: UIStepper!
let vendingMachine: VendingMachineType
var currentSelection: VendingSelection?
var quantity: Double = 1.0
required init?(coder aDecoder: NSCoder) {
do {
let dictionary = try PlistConverter.dictionaryFromFile("VendingInventory", ofType: "plist")
let inventory = try InventoryUnarchiver.vendingInventoryFromDictionary(dictionary)
self.vendingMachine = VendingMachine(inventory: inventory)
} catch let error {
fatalError("\(error)")
}
super.init(coder: aDecoder)
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
setupCollectionViewCells()
print(vendingMachine.inventory)
setupViews()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func setupViews() {
updateQuantityLabel()
updateBalanceLabel()
}
// MARK: - UICollectionView
func setupCollectionViewCells() {
let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
layout.sectionInset = UIEdgeInsets(top: 20, left: 0, bottom: 10, right: 0)
let padding: CGFloat = 10
layout.itemSize = CGSize(width: (screenWidth / 3) - padding, height: (screenWidth / 3) - padding)
layout.minimumInteritemSpacing = 10
layout.minimumLineSpacing = 10
collectionView.collectionViewLayout = layout
}
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return vendingMachine.selection.count
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! VendingItemCell
let item = vendingMachine.selection[indexPath.row]
cell.iconView.image = item.icon()
return cell
}
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
updateCellBackgroundColor(indexPath, selected: true)
reset()
currentSelection = vendingMachine.selection[indexPath.row]
updateTotalPriceLabel()
}
func collectionView(collectionView: UICollectionView, didDeselectItemAtIndexPath indexPath: NSIndexPath) {
updateCellBackgroundColor(indexPath, selected: false)
}
func collectionView(collectionView: UICollectionView, didHighlightItemAtIndexPath indexPath: NSIndexPath) {
updateCellBackgroundColor(indexPath, selected: true)
}
func collectionView(collectionView: UICollectionView, didUnhighlightItemAtIndexPath indexPath: NSIndexPath) {
updateCellBackgroundColor(indexPath, selected: false)
}
func updateCellBackgroundColor(indexPath: NSIndexPath, selected: Bool) {
if let cell = collectionView.cellForItemAtIndexPath(indexPath) {
cell.contentView.backgroundColor = selected ? UIColor(red: 41/255.0, green: 211/255.0, blue: 241/255.0, alpha: 1.0) : UIColor.clearColor()
}
}
// MARK: - Helper Methods
@IBAction func purchase() {
if let currentSelection = currentSelection {
do {
try vendingMachine.vend(currentSelection, quantity: quantity)
updateBalanceLabel()
} catch VendingMachineError.OutOfStock {
showAlert("Out of Stock")
} catch VendingMachineError.InsufficientFunds(let amount) {
showAlert("Insufficient Funds", message: "Additional $\(amount) needed to complete the transaction.")
} catch VendingMachineError.InvalidSelection {
showAlert("Invalid Selection")
} catch let error {
fatalError("\(error)")
}
} else {
// FIXME: Alert user to no selection
}
}
@IBAction func updateQuantity(sender: UIStepper) {
quantity = sender.value
updateTotalPriceLabel()
updateQuantityLabel()
}
func updateTotalPriceLabel() {
if let currentSelection = currentSelection, let item = vendingMachine.itemForCurrentSelection(currentSelection) {
totalLabel.text = "$\(item.price * quantity)"
}
}
func updateQuantityLabel() {
quantityLabel.text = "\(quantity)"
}
func updateBalanceLabel() {
balanceLabel.text = "$\(vendingMachine.amountDeposited)"
}
func reset() {
quantity = 1
stepper.value = 1
updateTotalPriceLabel()
updateQuantityLabel()
}
func showAlert(title: String, message: String? = nil, alertType: UIAlertControllerStyle = .Alert) {
let alertController = UIAlertController(title: title, message: message, preferredStyle: alertType)
let okAction = UIAlertAction(title: "OK", style: .Default, handler: dismissAlert)
alertController.addAction(okAction)
presentViewController(alertController, animated: true, completion: nil)
}
func dismissAlert(sender: UIAlertAction) {
reset()
}
@IBAction func updateFunds() {
vendingMachine.deposit(5.00)
updateBalanceLabel()
}
}
| unlicense | e8a0e0ebd276c63903fa9e6bd424cc2a | 35.029412 | 150 | 0.665306 | 5.498205 | false | false | false | false |
willlarche/material-components-ios | components/PageControl/examples/PageControlTypicalUseExample.swift | 3 | 4587 | /*
Copyright 2016-present the Material Components for iOS authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import Foundation
import MaterialComponents.MaterialPageControl
class PageControlSwiftExampleViewController: UIViewController, UIScrollViewDelegate {
static let pageColors = [
MDCPalette.cyan.tint300,
MDCPalette.cyan.tint500,
MDCPalette.cyan.tint700,
MDCPalette.cyan.tint300,
MDCPalette.cyan.tint500,
MDCPalette.cyan.tint700
]
let pageControl = MDCPageControl()
let scrollView = UIScrollView()
let pageLabels: [UILabel] = PageControlSwiftExampleViewController.pageColors.enumerated().map {
enumeration in
let (i, pageColor) = enumeration
let pageLabel = UILabel()
pageLabel.text = "Page \(i + 1)"
pageLabel.font = pageLabel.font.withSize(50)
pageLabel.textColor = UIColor(white: 0, alpha: 0.8)
pageLabel.backgroundColor = pageColor
pageLabel.textAlignment = NSTextAlignment.center
pageLabel.autoresizingMask = [.flexibleTopMargin, .flexibleBottomMargin]
return pageLabel
}
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.white
scrollView.frame = self.view.bounds
scrollView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
scrollView.delegate = self
scrollView.isPagingEnabled = true
scrollView.contentSize = CGSize(width: view.bounds.width * CGFloat(pageLabels.count),
height: view.bounds.height)
scrollView.showsHorizontalScrollIndicator = false
view.addSubview(scrollView)
// Add pages to scrollView.
for (i, pageLabel) in pageLabels.enumerated() {
let pageFrame = view.bounds.offsetBy(dx: CGFloat(i) * view.bounds.width, dy: 0)
pageLabel.frame = pageFrame
scrollView.addSubview(pageLabel)
}
pageControl.numberOfPages = pageLabels.count
pageControl.addTarget(self, action: #selector(didChangePage), for: .valueChanged)
pageControl.autoresizingMask = [.flexibleTopMargin, .flexibleWidth]
view.addSubview(pageControl)
}
// MARK: - Frame changes
override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
let pageBeforeFrameChange = pageControl.currentPage
for (i, pageLabel) in pageLabels.enumerated() {
pageLabel.frame = view.bounds.offsetBy(dx: CGFloat(i) * view.bounds.width, dy: 0)
}
scrollView.contentSize = CGSize(width: view.bounds.width * CGFloat(pageLabels.count),
height: view.bounds.height)
var offset = scrollView.contentOffset
offset.x = CGFloat(pageBeforeFrameChange) * view.bounds.width
// This non-anmiated change of offset ensures we keep the same page
scrollView.contentOffset = offset
var edgeInsets = UIEdgeInsets.zero;
#if swift(>=3.2)
if #available(iOS 11, *) {
edgeInsets = self.view.safeAreaInsets
}
#endif
let pageControlSize = pageControl.sizeThatFits(view.bounds.size)
let yOffset = self.view.bounds.height - pageControlSize.height - 8 - edgeInsets.bottom;
pageControl.frame =
CGRect(x: 0, y: yOffset, width: view.bounds.width, height: pageControlSize.height)
}
// MARK: - UIScrollViewDelegate
func scrollViewDidScroll(_ scrollView: UIScrollView) {
pageControl.scrollViewDidScroll(scrollView)
}
func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
pageControl.scrollViewDidEndDecelerating(scrollView)
}
func scrollViewDidEndScrollingAnimation(_ scrollView: UIScrollView) {
pageControl.scrollViewDidEndScrollingAnimation(scrollView)
}
// MARK: - User events
@objc func didChangePage(_ sender: MDCPageControl) {
var offset = scrollView.contentOffset
offset.x = CGFloat(sender.currentPage) * scrollView.bounds.size.width
scrollView.setContentOffset(offset, animated: true)
}
// MARK: - CatalogByConvention
@objc class func catalogBreadcrumbs() -> [String] {
return [ "Page Control", "Swift example"]
}
@objc class func catalogIsPrimaryDemo() -> Bool {
return false
}
}
| apache-2.0 | b2716348f2d693a60eccd7f26e5e07e3 | 33.75 | 97 | 0.727273 | 4.685393 | false | false | false | false |
LesCoureurs/Courir | Courir/Courir/Obstacle.swift | 1 | 1060 | //
// Obstacle.swift
// Courir
//
// Created by Sebastian Quek on 19/3/16.
// Copyright © 2016 NUS CS3217. All rights reserved.
//
enum ObstacleType {
case NonFloating, Floating
}
class Obstacle: GameObject {
static var uniqueId = 0
static let spawnXCoordinate = 64 * unitsPerGameGridCell
static let spawnYCoordinate = -4 * unitsPerGameGridCell
static let removalXCoordinate = -16 * unitsPerGameGridCell
let type: ObstacleType
let identifier: Int
let xWidth = 3 * unitsPerGameGridCell
let yWidth = 21 * unitsPerGameGridCell
weak var observer: Observer?
var xCoordinate = Obstacle.spawnXCoordinate {
didSet {
observer?.didChangeProperty("xCoordinate", from: self)
}
}
var yCoordinate = Obstacle.spawnYCoordinate {
didSet {
observer?.didChangeProperty("yCoordinate", from: self)
}
}
init(type: ObstacleType) {
self.type = type
self.identifier = Obstacle.uniqueId
Obstacle.uniqueId += 1
}
} | mit | 4a81fb72d6870d571cb08693c8cf254c | 23.090909 | 66 | 0.644948 | 4.394191 | false | false | false | false |
nakau1/NerobluCore | NerobluCore/NBString.swift | 1 | 16297 | // =============================================================================
// NerobluCore
// Copyright (C) NeroBlu. All rights reserved.
// =============================================================================
import UIKit
// MARK: - String拡張: 文字列長 -
public extension String {
/// 文字列長
///
/// "⏩".length // 1
/// "😻".length // 1
/// "123".length // 3
/// "ABC".length // 3
/// "あいう".length // 3
public var length: Int {
return self.characters.count
}
}
// MARK: - String拡張: ローカライズ -
public extension String {
/// 自身をローカライズのキーとしてローカライズされた文字列を取得する
///
/// "Hoge".localize() // ローカライズ設定があれば、例えば "ほげ" と返す
/// - parameter comment: コメント
/// - returns: ローカライズされた文字列
public func localize(comment: String = "") -> String {
return NSLocalizedString(self, comment: comment)
}
}
// MARK: - String拡張: フォーマット -
public extension String {
/// 自身をフォーマットとしてフォーマット化された文字列を取得する
///
/// "Hello %@".format("World") // "Hello World"
/// - parameter args: 引数
/// - returns: フォーマット化された文字列
public func format(args: CVarArgType...) -> String {
let s = NSString(format: self, arguments: getVaList(args))
return s as String
}
}
// MARK: - String拡張: オプショナル -
extension String {
/// 空文字列であればnilを返す
public var empty2nil: String? {
return self.isEmpty ? nil : self
}
}
// MARK: - String拡張: 文字列操作 -
public extension String {
/// 文字列置換を行う
///
/// "Hello".replace("e", "o") // "Hollo"
/// - parameter search: 検索する文字
/// - parameter replacement: 置換する文字
/// - returns: 置換された文字列
public func replace(search: String, _ replacement: String) -> String {
return self.stringByReplacingOccurrencesOfString(search, withString: replacement, options: NSStringCompareOptions(), range: nil)
}
/// 指定した範囲の文字列置換を行う
///
/// - parameter range: 範囲
/// - parameter replacement: 置換する文字
/// - returns: 置換された文字列
public func replace(range: NSRange, _ replacement: String) -> String {
return self.ns.stringByReplacingCharactersInRange(range, withString: replacement)
}
/// 文字列分割を行う
///
/// "file/path/to/".split("/") // ["file", "path", "to"]
/// - parameter separator: 分割に使用するセパレータ文字
/// - parameter allowEmpty: 空文字を許可するかどうか。falseにすると分割された結果が空文字だった場合は配列に入りません
/// - returns: 分割された結果の文字列配列
public func split(separator: String, allowEmpty: Bool = true) -> [String] {
let ret = self.componentsSeparatedByString(separator)
if allowEmpty {
return ret
}
return ret.filter { !$0.isEmpty }
}
/// 改行コードで文字列分割を行う
/// - returns: 分割された結果の文字列配列
public func splitCarriageReturn() -> [String] {
return self.split("\r\n")
}
/// カンマで文字列分割を行う
/// - returns: 分割された結果の文字列配列
public func splitComma() -> [String] {
return self.split(",")
}
/// スラッシュで文字列分割を行う
/// - returns: 分割された結果の文字列配列
public func splitSlash() -> [String] {
return self.split("/")
}
/// 空白文字で文字列分割を行う
/// - returns: 分割された結果の文字列配列
public func splitWhitespace() -> [String] {
return self.split(" ")
}
/// 文字列のトリムを行う
///
/// " hello world ".trim() // "hello world"
/// // 以下のようにすると改行コードもトリムできる
/// "hello world\n".trim(NSCharacterSet.whitespaceAndNewlineCharacterSet())
///
/// - parameter characterSet: トリムに使用するキャラクタセット(省略すると半角スペースのみがトリム対象となる)
/// - returns: トリムされた文字列
public func trim(characterSet: NSCharacterSet = NSCharacterSet.whitespaceCharacterSet()) -> String {
return self.stringByTrimmingCharactersInSet(characterSet)
}
}
// MARK: - String拡張: 部分取得 -
public extension String {
/// 文字列の部分取得を行う
///
/// "hello".substringWithRange(1, end: 3) // "el"
/// - parameter start: 開始インデックス
/// - parameter end: 終了インデックス
/// - returns: 部分取得された文字列
public func substringWithRange(start: Int, end: Int) -> String {
if (start < 0 || start > self.characters.count) {
return ""
}
else if end < 0 || end > self.characters.count {
return ""
}
let range = Range(start: self.startIndex.advancedBy(start), end: self.startIndex.advancedBy(end))
return self.substringWithRange(range)
}
/// 文字列の部分取得を行う
///
/// "hello".substringWithRange(1, length: 3) // "ell"
/// - parameter start: 開始インデックス
/// - parameter length: 文字列長
/// - returns: 部分取得された文字列
public func substringWithRange(start: Int, length: Int) -> String {
if (start < 0 || start > self.characters.count) {
return ""
}
else if length < 0 || start + length > self.characters.count {
return ""
}
let range = Range(start: self.startIndex.advancedBy(start), end: self.startIndex.advancedBy(start + length))
return self.substringWithRange(range)
}
/// 文字列の部分取得を行う
///
/// "hello".substringWithRange(fromIndex: 1) // "ello"
/// - parameter start: 開始インデックス
/// - returns: 開始インデックスから文字列の最後までを部分取得した文字列
public func substringWithRange(fromIndex start: Int) -> String {
let length = self.length - start
return length > 0 ? self.substringWithRange(start, length: length) : ""
}
/// 文字列の部分取得を行う
///
/// - parameter range: NSRange構造体
/// - returns: 部分取得した文字列
public func substringWithRange(range range: NSRange) -> String {
return self.substringWithRange(range.location, length: range.length)
}
}
// MARK: - String拡張: 正規表現 -
public extension String {
/// 文字列から正規表現パターンに合った文字列を配列で取り出す
///
/// - parameter pattern: 正規表現パターン
/// - parameter regularExpressionOptions: 正規表現オプション
/// - parameter matchingOptions: 正規表現マッチングオプション
/// - returns: 正規表現パターンに合った文字列の配列
public func stringsMatchedRegularExpression(pattern: String, regularExpressionOptions: NSRegularExpressionOptions? = nil, matchingOptions: NSMatchingOptions? = nil) -> [String] {
guard let regExp = try? NSRegularExpression(pattern: pattern, options: regularExpressionOptions ?? NSRegularExpressionOptions()) else { return [] }
let results = regExp.matchesInString(self, options: matchingOptions ?? NSMatchingOptions(), range: NSMakeRange(0, self.length))
var ret = [String]()
for result in results {
ret.append(self.substringWithRange(range: result.rangeAtIndex(0)))
}
return ret
}
/// 文字列から正規表現パターンに合った文字列を配列で取り出す
///
/// - parameter pattern: 正規表現パターン
/// - parameter regularExpressionOptions: 正規表現オプション
/// - parameter matchingOptions: 正規表現マッチングオプション
/// - returns: 正規表現パターンに合った文字列の配列
public func stringMatchedRegularExpression(pattern: String, regularExpressionOptions: NSRegularExpressionOptions? = nil, matchingOptions: NSMatchingOptions? = nil) -> String? {
return self.stringsMatchedRegularExpression(pattern, regularExpressionOptions: regularExpressionOptions, matchingOptions: matchingOptions).first
}
/// 指定した正規表現パターンに合うかどうかを返す
///
/// - parameter pattern: 正規表現パターン
/// - returns: 文字列から正規表現パターンに合うかどうか
public func isMatchedRegularExpression(pattern: String) -> Bool {
let range = self.ns.rangeOfString(pattern, options: .RegularExpressionSearch)
return range.location != NSNotFound
}
/// 文字列から正規表現パターンに合った箇所を置換した文字列を返す
///
/// - parameter pattern: 正規表現パターン
/// - parameter replacement: 置換する文字
/// - parameter regularExpressionOptions: 正規表現オプション
/// - parameter matchingOptions: 正規表現マッチングオプション
/// - returns: 置換した文字列
public func replaceMatchedRegularExpression(pattern: String, replacement: String, regularExpressionOptions: NSRegularExpressionOptions? = nil, matchingOptions: NSMatchingOptions? = nil) -> String {
let mutableSelf = self.mutable
guard let regExp = try? NSRegularExpression(pattern: pattern, options: regularExpressionOptions ?? NSRegularExpressionOptions()) else {
return "\(self)"
}
regExp.replaceMatchesInString(mutableSelf, options: matchingOptions ?? NSMatchingOptions(), range: NSMakeRange(0, self.length), withTemplate: replacement)
return mutableSelf as String
}
/// 文字列から正規表現パターンに合った箇所を削除した文字列を返す
///
/// - parameter pattern: 正規表現パターン
/// - parameter regularExpressionOptions: 正規表現オプション
/// - parameter matchingOptions: 正規表現マッチングオプション
/// - returns: 削除した文字列
public func removeMatchedRegularExpression(pattern: String, regularExpressionOptions: NSRegularExpressionOptions? = nil, matchingOptions: NSMatchingOptions? = nil) -> String {
return self.replaceMatchedRegularExpression(pattern, replacement: "", regularExpressionOptions: regularExpressionOptions, matchingOptions: matchingOptions)
}
}
// MARK: - String拡張: トランスフォーム -
public extension String {
/// 指定した変換方法で変換した文字列を返す
///
/// - parameter transform: 変換方法
/// - parameter reverse: 変換順序
/// - returns: 変換した文字列
public func stringTransformWithTransform(transform: CFStringRef, reverse: Bool) -> String {
let mutableSelf = self.mutable as CFMutableString
CFStringTransform(mutableSelf, nil, transform, reverse)
return mutableSelf as String
}
/// 半角文字を全角文字に変換した文字列を返す
/// - returns: 変換した文字列
public func stringToFullwidth() -> String {
return self.stringTransformWithTransform(kCFStringTransformFullwidthHalfwidth, reverse: true)
}
/// 全角文字を半角文字に変換した文字列を返す
/// - returns: 変換した文字列
public func stringToHalfwidth() -> String {
return self.stringTransformWithTransform(kCFStringTransformFullwidthHalfwidth, reverse: false)
}
/// カタカタをひらがなに変換した文字列を返す
/// - returns: 変換した文字列
public func stringKatakanaToHiragana() -> String {
return self.stringTransformWithTransform(kCFStringTransformHiraganaKatakana, reverse: true)
}
/// ひらがなをカタカナに変換した文字列を返す
/// - returns: 変換した文字列
public func stringHiraganaToKatakana() -> String {
return self.stringTransformWithTransform(kCFStringTransformHiraganaKatakana, reverse: false)
}
/// ローマ字をひらがなに変換した文字列を返す
/// - returns: 変換した文字列
public func stringHiraganaToLatin() -> String {
return self.stringTransformWithTransform(kCFStringTransformLatinHiragana, reverse: true)
}
/// ひらがなをローマ字に変換した文字列を返す
/// - returns: 変換した文字列
public func stringLatinToHiragana() -> String {
return self.stringTransformWithTransform(kCFStringTransformLatinHiragana, reverse: false)
}
/// ローマ字をカタカナに変換した文字列を返す
/// - returns: 変換した文字列
public func stringKatakanaToLatin() -> String {
return self.stringTransformWithTransform(kCFStringTransformLatinKatakana, reverse: true)
}
/// カタカナをローマ字に変換した文字列を返す
/// - returns: 変換した文字列
public func stringLatinToKatakana() -> String {
return self.stringTransformWithTransform(kCFStringTransformLatinKatakana, reverse: false)
}
}
// MARK: - String拡張: URLエンコード -
public extension String {
/// URLエンコードした文字列
public var urlEncode: String {
return self.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.alphanumericCharacterSet()) ?? ""
}
/// URLデコードした文字列
public var urlDecode: String {
return self.stringByRemovingPercentEncoding ?? ""
}
}
// MARK: - String拡張: 記法変換 -
public extension String {
/// スネーク記法をキャメル記法に変換した文字列
public var snakeToCamel: String {
if self.isEmpty { return "" }
let r = NSMakeRange(0, 1)
var ret = self.capitalizedString.stringByReplacingOccurrencesOfString("_", withString: "")
ret = ret.ns.stringByReplacingCharactersInRange(r, withString: ret.ns.substringWithRange(r).lowercaseString)
return ret
}
/// キャメル記法をスネーク記法に変換した文字列
public var camelToSnake: String {
if self.isEmpty { return "" }
return self.replaceMatchedRegularExpression("(?<=\\w)([A-Z])", replacement: "_$1").lowercaseString
}
}
// MARK: - String拡張: Objective-C連携 -
public extension String {
/// NSStringにキャストした新しい文字列オブジェクト
public var ns: NSString { return NSString(string: self) }
/// NSMutableStringにキャストした新しい文字列オブジェクト
public var mutable: NSMutableString { return NSMutableString(string: self) }
}
// MARK: - String汎用関数 -
/// 文字列分割を行う
///
/// split("file/path/to", "/") // ["file", "path", "to"]
/// - parameter string: 対象の文字列
/// - parameter separator: 分割に使用するセパレータ文字
/// - parameter allowEmpty: 空文字を許可するかどうか。falseにすると分割された結果が空文字だった場合は配列に入りません
/// - returns: 分割された結果の文字列配列
public func split(string: String, _ separator: String, allowEmpty: Bool = true) -> [String] {
return string.split(separator, allowEmpty: allowEmpty)
}
/// 文字列結合を行う
///
/// join(["file", "path", "to"], "/") // "file/path/to"
/// - parameter strings: 対象の文字列
/// - parameter glue: 結合に使用する文字
/// - returns: 結合した結果の文字列
public func join(strings: [String], _ glue: String) -> String {
return (strings as NSArray).componentsJoinedByString(glue)
}
| apache-2.0 | c200b99625d5414b013ad5b9fdf38d51 | 33.350515 | 201 | 0.641807 | 3.805825 | false | false | false | false |
ontouchstart/swift3-playground | Learn to Code 1.playgroundbook/Contents/Chapters/Document7.playgroundchapter/Pages/Challenge2.playgroundpage/Sources/Assessments.swift | 1 | 1296 | //
// Assessments.swift
//
// Copyright (c) 2016 Apple Inc. All Rights Reserved.
//
let success = "### Right on! \nDeveloping your own solutions for new problems enables you to figure out what types of tools work in certain situations. As your skills grow, you’ll be able to choose those tools more quickly and intelligently. How awesome is that? \n\n[**Next Page**](@next)"
let solution: String? = nil
public func assessmentPoint() -> AssessmentResults {
pageIdentifier = "Turned_Around"
var hints = [
"Think of all the tools you've learned about so far: functions, `for` loops, `while` loops, conditional code, and operators. How can you use these existing tools to solve this puzzle?",
"This puzzle is a **Challenge** and has no provided solution. Strengthen your coding skills by creating your own approach to solve it."
]
switch currentPageRunCount {
case 0..<5:
break
case 5...7:
hints[0] = "When you work hard to figure something out, you remember it far better than if you'd found the answer more easily. Keep trying now, or come back later to solve this challenge."
default:
break
}
return updateAssessment(successMessage: success, failureHints: hints, solution: solution)
}
| mit | 6cee8ab2b138486ee845de40ef73f45e | 37.058824 | 290 | 0.690108 | 4.270627 | false | false | false | false |
ringohub/swift-todo | ToDo/ToDoItemViewController.swift | 1 | 1492 | import UIKit
class ToDoItemViewController: UIViewController {
@IBOutlet weak var todoField: UITextField!
var task: ToDo? = nil
override func viewDidLoad() {
super.viewDidLoad()
if let taskTodo = task {
todoField.text = taskTodo.item
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func cancel(_ sender: UIBarButtonItem) {
navigationController!.popViewController(animated: true)
}
@IBAction func save(_ sender: UIBarButtonItem) {
switch task {
case .none: createTask()
case .some(_): editTask()
}
navigationController!.popViewController(animated: true)
}
fileprivate func createTask() -> Void {
print("CREATAE TASK")
let newTask: ToDo = ToDo.mr_createEntity() as ToDo
newTask.item = todoField.text!
newTask.managedObjectContext!.mr_saveToPersistentStoreAndWait()
}
fileprivate func editTask() -> Void {
print("EDIT TASK")
task?.item = todoField.text!
task?.managedObjectContext!.mr_saveToPersistentStoreAndWait()
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| mit | 7ea41fb851b0f34def66cd1e4fe532c0 | 25.642857 | 104 | 0.700402 | 4.751592 | false | false | false | false |
thanhtanh/OwlCollectionView | Example/UIColorExtension.swift | 1 | 1784 | //
// UIColorExtension.swift
// OwlCollectionView
//
// Created by t4nhpt on 9/28/16.
// Copyright © 2016 T4nhpt. All rights reserved.
//
import Foundation
import UIKit
extension UIColor {
convenience init(hexString: String) {
let hex = hexString.trimmingCharacters(in: CharacterSet.alphanumerics.inverted)
var int = UInt32()
Scanner(string: hex).scanHexInt32(&int)
let a, r, g, b: UInt32
switch hex.characters.count {
case 3: // RGB (12-bit)
(a, r, g, b) = (255, (int >> 8) * 17, (int >> 4 & 0xF) * 17, (int & 0xF) * 17)
case 6: // RGB (24-bit)
(a, r, g, b) = (255, int >> 16, int >> 8 & 0xFF, int & 0xFF)
case 8: // ARGB (32-bit)
(a, r, g, b) = (int >> 24, int >> 16 & 0xFF, int >> 8 & 0xFF, int & 0xFF)
default:
(a, r, g, b) = (1, 1, 1, 0)
}
self.init(red: CGFloat(r) / 255, green: CGFloat(g) / 255, blue: CGFloat(b) / 255, alpha: CGFloat(a) / 255)
}
class func generateRandomColorHexString() -> String {
var redLevel = String(Int(arc4random_uniform(255)), radix: 16)
var greenLevel = String(Int(arc4random_uniform(255)), radix: 16)
var blueLevel = String(Int(arc4random_uniform(255)), radix: 16)
redLevel = appendZeroToShortColor(color: redLevel)
greenLevel = appendZeroToShortColor(color: greenLevel)
blueLevel = appendZeroToShortColor(color: blueLevel)
let color = String(format:"%@%@%@", redLevel, greenLevel, blueLevel)
return color
}
private class func appendZeroToShortColor(color: String) -> String {
if color.characters.count == 1 {
return "0\(color)"
}
return color
}
}
| mit | 90948c86832910b7ceefdcf40cf91e73 | 34.66 | 114 | 0.567583 | 3.409178 | false | false | false | false |
wyxy2005/SEGSegmentedViewController | SegmentedViewControllerTests/UIViewControllerExtensionsTests.swift | 1 | 4120 | //
// UIViewControllerExtensionsTests.swift
// SegmentedViewController
//
// Created by Thomas Sherwood on 07/09/2014.
// Copyright (c) 2014 Thomas Sherwood. All rights reserved.
//
import SegmentedViewController
import UIKit
import XCTest
class UIViewControllerExtensionsTests: XCTestCase {
func testGetNavigationAndTabBarInsetsWithNoNavOrTabBars() {
let controller = UIViewController()
let insets = controller.navigationAndTabBarInsets
let statusBarHeight = CGRectGetHeight(UIApplication.sharedApplication().statusBarFrame)
let expectedInsets = UIEdgeInsetsMake(statusBarHeight, 0, 0, 0)
XCTAssertTrue(UIEdgeInsetsEqualToEdgeInsets(insets, expectedInsets), "Controller returned unexpected insets")
}
func testGetNavigationAndTabBarInsetsWithNavBar() {
let controller = UIViewController()
let navController = UINavigationController(rootViewController: controller)
let insets = controller.navigationAndTabBarInsets
let statusBarHeight = CGRectGetHeight(UIApplication.sharedApplication().statusBarFrame)
let navBarHeight = CGRectGetHeight(navController.navigationBar.frame)
let expectedInsets = UIEdgeInsetsMake(statusBarHeight + navBarHeight, 0, 0, 0)
XCTAssertTrue(UIEdgeInsetsEqualToEdgeInsets(insets, expectedInsets), "Controller returned unexpected insets")
}
func testGetNavigationAndTabBarInsetsWithTabBar() {
let controller = UIViewController()
let tabController = UITabBarController()
tabController.addChildViewController(controller)
let insets = controller.navigationAndTabBarInsets
let statusBarHeight = CGRectGetHeight(UIApplication.sharedApplication().statusBarFrame)
let tabBarHeight = CGRectGetHeight(tabController.tabBar.frame)
let expectedInsets = UIEdgeInsetsMake(statusBarHeight, 0, tabBarHeight, 0)
XCTAssertTrue(UIEdgeInsetsEqualToEdgeInsets(insets, expectedInsets), "Controller returned unexpected insets")
}
func testGetNavigationAndTabBarInsetsWithNavAndTabBars() {
let controller = UIViewController()
let navController = UINavigationController(rootViewController: controller)
let tabController = UITabBarController()
tabController.addChildViewController(navController)
let insets = controller.navigationAndTabBarInsets
let statusBarHeight = CGRectGetHeight(UIApplication.sharedApplication().statusBarFrame)
let navBarHeight = CGRectGetHeight(navController.navigationBar.frame)
let tabBarHeight = CGRectGetHeight(tabController.tabBar.frame)
let expectedInsets = UIEdgeInsetsMake(statusBarHeight + navBarHeight, 0, tabBarHeight, 0)
XCTAssertTrue(UIEdgeInsetsEqualToEdgeInsets(insets, expectedInsets), "Controller returned unexpected insets")
}
func testGetSegmentedViewControllerNoParent() {
let controller = UIViewController()
let segmentController = controller.segmentedViewController
XCTAssertNil(segmentController, "No segmented parent should be within the view hiearchy")
}
func testGetSegmentedViewControllerNoSegmentedController() {
let controller = UIViewController()
let navController = UINavigationController(rootViewController: controller)
let segmentController = controller.segmentedViewController
XCTAssertNil(segmentController, "No segmented parent should be within the view hiearchy")
}
func testGetSegmentedViewControllerWithSegmentedController() {
let controller = UIViewController()
let segmentController = SegmentedViewController()
segmentController.addChildViewController(controller)
let detectedSegmentController = controller.segmentedViewController
XCTAssertNotNil(detectedSegmentController, "Segmented parent should have been detected")
XCTAssertEqual(segmentController, detectedSegmentController!, "Same segment controller should be detected")
}
func testGetSegmentedViewControllerSelfIsSegmentdController() {
let controller = SegmentedViewController()
let detectedSegmentController = controller.segmentedViewController
XCTAssertNotNil(detectedSegmentController, "Segmented parent should have been detected")
XCTAssertEqual(controller, detectedSegmentController!, "Same segment controller should be detected")
}
}
| mit | 1a982569aef3e7617d8a0aa39384b914 | 42.368421 | 111 | 0.824029 | 5.364583 | false | true | false | false |
Swinject/SwinjectMVVMExample | ExampleViewModelTests/DummyResponse.swift | 2 | 1411 | //
// DummyResponse.swift
// SwinjectMVVMExample
//
// Created by Yoichi Tagaya on 8/23/15.
// Copyright © 2015 Swinject Contributors. All rights reserved.
//
@testable import ExampleModel
@testable import ExampleViewModel
let dummyResponse: ResponseEntity = {
let image0 = ImageEntity(
id: 10000, pageURL: "https://somewhere.com/page0/", pageImageWidth: 1000, pageImageHeight: 2000,
previewURL: "https://somewhere.com/preview0.jpg", previewWidth: 250, previewHeight: 500,
imageURL: "https://somewhere.com/image0.jpg", imageWidth: 100, imageHeight: 200,
viewCount: 99, downloadCount: 98, likeCount: 97, tags: ["a", "b"], username: "User0")
let image1 = ImageEntity(
id: 10001, pageURL: "https://somewhere.com/page1/", pageImageWidth: 1500, pageImageHeight: 3000,
previewURL: "https://somewhere.com/preview1.jpg", previewWidth: 350, previewHeight: 700,
imageURL: "https://somewhere.com/image1.jpg", imageWidth: 150, imageHeight: 300,
viewCount: 123456789, downloadCount: 12345678, likeCount: 1234567, tags: ["x", "y"], username: "User1")
return ResponseEntity(totalCount: 123, images: [image0, image1])
}()
let image1x1: UIImage = {
UIGraphicsBeginImageContextWithOptions(CGSize(width: 1, height: 1), true, 0)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image!
}()
| mit | 9846e52c906021c810e830f6948f297c | 44.483871 | 111 | 0.704255 | 3.895028 | false | true | false | false |
lucascarletti/Pruuu | Pruuu/Resources/Core Data/PRStoreAccess.swift | 1 | 3260 | //
// PRStoreAccess.swift
// Pruuu
//
// Created by Lucas Teixeira Carletti on 26/10/2017.
// Copyright © 2017 PR. All rights reserved.
//
import Foundation
import CoreData
class PRStoreAccess {
// MARK: - Initialization
var context: NSManagedObjectContext // = PRStorageManager.shared.childManagedObjectContext()
init(context: NSManagedObjectContext = PRStorageManager.shared.managedObjectContext) {
self.context = context
}
// init(childContext context: NSManagedObjectContext? = PRStorageManager.shared.childManagedObjectContext()) {
// self.context = context
// }
// MARK: - Core Data fetch methods
func getAllManagedObjects<T: NSManagedObject>(predicate: NSPredicate? = nil, order: String? = nil, entityType: T.Type) -> [T]? {
let entityName = NSStringFromClass(entityType)
let fetchRequest: NSFetchRequest<T> = NSFetchRequest<T>(entityName: entityName)
if predicate != nil {
fetchRequest.predicate = predicate
}
if let sortOrder = order {
let sortDescriptor = NSSortDescriptor(key: sortOrder, ascending: true, selector: #selector(NSString.caseInsensitiveCompare))
fetchRequest.sortDescriptors = [sortDescriptor]
}
do {
let searchResults = try context.fetch(fetchRequest)
return searchResults
} catch {
print("Error reading \(entityName) data on store: \(error)")
}
return nil
}
func getManagedObject<T: NSManagedObject>(itemId: Int32, entityType: T.Type) -> T? {
let predicate = NSPredicate(format: "id = \(itemId)")
return getAllManagedObjects(predicate: predicate, entityType: T.self)?.first
}
// MARK: - Core Data delete methods
func removeEntriesOnStore<T: NSManagedObject>(objects: [T]) {
for object in objects {
removeEntryOnStore(object: object)
}
}
func removeEntryOnStore<T: NSManagedObject>(object: T) {
context.performAndWait {
self.context.delete(object)
}
}
// MARK: Core Data creation methods
func createManagedObject<T: NSManagedObject>(objectID: Int32? = nil, entityType: T.Type) -> T? {
var object: T? = nil
context.performAndWait {
let entityName = NSStringFromClass(entityType)
guard let entityDescription = NSEntityDescription.entity(forEntityName: entityName, in: self.context) else {
return
}
object = NSManagedObject(entity: entityDescription, insertInto: self.context) as? T
if entityDescription.attributesByName.keys.contains("id") {
object?.setValue(objectID, forKey: "id")
}
}
return object
}
func updateEntryOnStore<T: NSManagedObject>(object: T) {
}
func createChildContext() -> NSManagedObjectContext {
return PRStorageManager.shared.childManagedObjectContext()
}
// MARK: Core Data save methods
func saveChanges() {
PRStorageManager.shared.save()
}
}
| mit | 358a3c55b6cbb8ddfd1b5e3bb40013fe | 28.627273 | 136 | 0.613992 | 5.084243 | false | false | false | false |
helloglance/betterbeeb | BetterBeeb/HighlightingButton.swift | 1 | 1893 | //
// HighlightingButton.swift
// BetterBeeb
//
// Created by Hudzilla on 15/10/2014.
// Copyright (c) 2014 Paul Hudson. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import UIKit
class HighlightingButton: UIButton {
var offColor: UIColor!
var onColor: UIColor!
init(off: UIColor, on: UIColor) {
//let frame = CGRectMake(0.0, 0.0, 0.0, 0.0)
super.init(frame:CGRectZero)
offColor = off
onColor = on
backgroundColor = off
}
override init(frame: CGRect) {
super.init(frame: frame)
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)!
}
override var highlighted: Bool {
get {
return super.highlighted
}
set {
if newValue {
backgroundColor = onColor
} else {
backgroundColor = offColor
}
super.highlighted = newValue
}
}
}
| mit | b0fd87e5e357099b81d10fec5e657dd8 | 28.123077 | 81 | 0.712097 | 3.879098 | false | false | false | false |
LittoCats/coffee-mobile | CoffeeMobile/Base/Base/CMView.swift | 1 | 14860 | //
// CMView.swift
// CoffeeMobile
//
// Created by 程巍巍 on 5/20/15.
// Copyright (c) 2015 Littocats. All rights reserved.
//
import UIKit
import XMLNode
typealias XMLViewAttributeAnalyzer = @objc_block (view: UIView, value: String?)->AnyObject?
typealias XMLViewConstructor = @objc_block ()->UIView
/**
MARK: 只有实现了该协议的 View 类,才能通过 XML 配制自动构建
*/
@objc protocol XMLViewProtocol: NSObjectProtocol {
/**
MARK: Children 构造器,如果与 superview 提供的构造器名称相同,则覆盖 superview 提供的构造器,运行时确定,因此可以在同一个类的不同实例中提供不同的构造器,但不建议这么做
*/
optional var XMLViewConstructorMap: [String: XMLViewConstructor] {get}
/**
MARK: 私用属性存取器,运行时确定,属性名相同时,可覆盖 superview 的属性存取器
*/
optional func XMLViewAttributeAnalyzerMap()->[String:XMLViewAttributeAnalyzer]
/**
MARK: 是否忽略 Children 自动构建, 例如:标准 button 中 imageView/titleLabel 是不需要自动构建的。可以在这里自行处理一些资源解析,对自定义控件十分有用
*/
optional func shouldIgnoreAutoLoadXMLChild(child: XMLElement)-> Bool
/**
MARK: 此方法主要用于一些特殊的自定义界面,使其可以定制 constraint.
如果没有实现该方法或返回 nil , 则使用预定义的解析方法
*/
optional func constrainForName(name: String, script: String)-> NSLayoutConstraint?
}
//MARK:
extension UIView {
struct XMLStatic {
private static var xmlAssociatedKey = "xmlAssociatedKey"
private static var contextAssociatedKey = "contextAssociatedKey"
private static var uidMap = NSMapTable.strongToWeakObjectsMapTable()
private static var constraintUIDMap = NSMapTable.strongToWeakObjectsMapTable()
private static var XMLViewRootClassMap: [String: XMLViewConstructor] = [
"View": {CMView()}
]
private static var XMLViewAttributeAnalyzerMap: [String: XMLViewAttributeAnalyzer] = [
"color": { (view: UIView, value: String?)->AnyObject? in
if value != nil {
view.backgroundColor = UIColor(script: value!)
}
return view.backgroundColor?.hex
},
"bordercolor": { (view: UIView, value: String?)->AnyObject? in
if value != nil {
view.layer.borderColor = UIColor(script: value!).CGColor
}
return UIColor(CGColor: view.layer.borderColor)?.hex
},
"borderwidth": { (view: UIView, value: String?)->AnyObject? in
if value != nil {
view.layer.borderWidth = CGFloat(("\(value!)" as NSString).floatValue)
}
return view.layer.borderWidth
},
"cornerradius": { (view: UIView, value: String?)->AnyObject? in
if value != nil {
view.layer.cornerRadius = CGFloat(("\(value!)" as NSString).floatValue)
}
return view.layer.cornerRadius
},
"contentmode": {(view: UIView, value: String?)->AnyObject? in
if value != nil {
view.contentMode = UIViewContentMode(rawValue: ("\(value!)" as NSString).integerValue)!
}
return view.contentMode.rawValue
},
"hidden": {(view: UIView, value: String?)->AnyObject? in
if value != nil {
view.hidden = ("\(value!)" as NSString).boolValue
}
return view.hidden
},
"alpha": {(view: UIView, value: String?)->AnyObject? in
if value != nil {
view.alpha = CGFloat(("\(value!)" as NSString).floatValue)
}
return view.alpha
},
"clipstobounds": {(view: UIView, value: String?)->AnyObject? in
if value != nil {
view.clipsToBounds = ("\(value!)" as NSString).boolValue
}
return view.clipsToBounds
}
]
private static var XMLViewConstraintAttributeMap: [String: [NSLayoutAttribute]] = [
"width": [NSLayoutAttribute.Width],
"height": [NSLayoutAttribute.Height],
"top": [NSLayoutAttribute.Top],
"bottom": [NSLayoutAttribute.Bottom],
"left": [NSLayoutAttribute.Left],
"right": [NSLayoutAttribute.Right],
"leading": [NSLayoutAttribute.Leading],
"trailing": [NSLayoutAttribute.Trailing],
"centerx": [NSLayoutAttribute.CenterX],
"centery": [NSLayoutAttribute.CenterY],
"ratio": [NSLayoutAttribute.Height,NSLayoutAttribute.Width]
]
}
/**
MARK: 自动构建时,绑定到 View 的 XML DOM 元素,主要用于自动搜索
*/
final var xml: XMLElement? {
return objc_getAssociatedObject(self, &XMLStatic.xmlAssociatedKey) as? XMLElement
}
/**
MARK: View 实例的唯一标识符,如果是由 XMLElement 自动构建的,则会绑定到 对应的 XMLElement
*/
final var uid: String {
return String(format: "uid_%p", self)
}
//
private func hostViewController() ->UIViewController? {
var target: AnyObject? = self
while target != nil {
if let next = (target as? UIResponder)?.nextResponder() {
target = next
if target is UIViewController {
break
}
}else{
target = nil
break
}
}
return target as? UIViewController
}
/**
MARK: XMLView 运行时上下文
*/
final var context: CMContext? {
return (hostViewController() as? CMViewController)?.context
}
/**
MARK: convenience init with xml
*/
static func view(xmlString: String)-> UIView{
var error = NSErrorPointer()
var xmlDoc = XMLDocument(XMLString: xmlString, options: 0, error: error)
if error != nil {
println(error.memory)
return UIView()
}
if let root = xmlDoc.rootElement() {
if let view = loadXMLView(xmlele: root, constructorMap: XMLStatic.XMLViewRootClassMap){
view.loadXMLConstraints()
return view
}
}
return UIView()
}
private static func loadXMLView(#xmlele: XMLElement, constructorMap map: [String: XMLViewConstructor])->UIView? {
if let name = xmlele.name() {
if let constructor = map[name] {
var view = constructor()
objc_setAssociatedObject(view, &XMLStatic.xmlAssociatedKey, xmlele, objc_AssociationPolicy(OBJC_ASSOCIATION_RETAIN_NONATOMIC))
// 将 native id 添加到 xnlelement 中,方便 选择器 查找
var nativeId = XMLNode.attributeWithName("_uid", stringValue: view.uid) as! XMLNode
xmlele.addAttribute(nativeId)
view.loadXMLAttribute()
if let children = xmlele.children() {
var childrenMap = map
if let map = (view as? XMLViewProtocol)?.XMLViewConstructorMap {
for (key, value) in map {
childrenMap[key] = value
}
}
for child in children as! [XMLNode] {
if let subele = child as? XMLElement {
if let ignore = (view as? XMLViewProtocol)?.shouldIgnoreAutoLoadXMLChild?(subele) {
if ignore {continue}
}
if let subview = loadXMLView(xmlele: subele, constructorMap: childrenMap){
view.addSubview(subview)
}
}
}
}
return view
}
}
return nil
}
/**
MARK: 根据 xml 属性,设置 view 的属性
子类中必须调用 super 方法
*/
private func loadXMLAttribute() {
var analyzerMap = XMLStatic.XMLViewAttributeAnalyzerMap
if let xmlView = self as? XMLViewProtocol {
if let map = xmlView.XMLViewAttributeAnalyzerMap?() {
for (name,analyzer) in map {
analyzerMap[name] = analyzer
}
}
}
if let attributes = xml?.attributes() as? [XMLNode] {
for node in attributes {
if let analyzer = analyzerMap[node.name().lowercaseString] {
analyzer(view: self, value: node.stringValue())
}
}
}
}
/**
MARK: 根据 xml 属性,添加约束, 自动调用,不要手动调用
*/
private func loadXMLConstraints() {
for name in ["width", "height", "centerx", "centery", "left", "right", "top", "bottom", "ratio"] {
var constraintNode = xml?.attributeForName(name)
if let script: String = constraintNode?.stringValue() {
if script.isEmpty {continue}
/**
解析 constraint script 为 [first, firstattribute, relation, second, secondattribute, constant, multiper]。
first 为当前控件,即 self, firstattribute 为当前 xmlnode 的 name, second 需跟据 id 在 context 中查找,constant 位于 + 或 - 号 与 * 号之间,默认为0, multiper * 号以后的数字部分,默认为 1
multiper 不能为负值
script 仅存在两种情况,数字开头,例: width='44*1.2';非数字开头,例: centerx=root.centerx-10*2
@discussion 为使简化结构,所有约束,仅允许同级(兄弟)及与父级之间存在约束,自定义控件内,自已实现的,不受限制
@discussion 如果 second 为 super ,则 second 为 superview
*/
var conf = [String: AnyObject]()
conf["first"] = self
conf["firstattribute"] = name
conf["constant"] = 0
conf["multiplier"] = 1
conf["secondattribute"] = NSLayoutAttribute.NotAnAttribute.rawValue
// second secondattribute
if let range = script.rangeOfString("^[a-zA-Z\\.]+", options: .RegularExpressionSearch, range: nil, locale: nil) {
if !range.isEmpty {
var sub = script.substringWithRange(range)
var arr = sub.componentsSeparatedByString(".")
// 此处出可以设置为: second attribute 与 first attribute 相同,可以省略
conf["second"] = arr[0]
if arr.count > 1 && !arr[1].isEmpty{
conf["secondattribute"] = arr[1]
}else{
conf["secondattribute"] = name
}
}
}
if let range = script.rangeOfString("[0-9-+*]+[0-9\\.]*$", options: .RegularExpressionSearch, range: nil, locale: nil){
if !range.isEmpty {
var sub = script.substringWithRange(range)
var arr = sub.componentsSeparatedByString("*")
if arr.count > 0 { conf["constant"] = (arr[0] as NSString).floatValue}
if arr.count > 1 { conf["multiplier"] = (arr[1] as NSString).floatValue}
}
}
if let secondattribute = conf["secondattribute"] as? String {
if let attArr = XMLStatic.XMLViewConstraintAttributeMap[secondattribute]{
conf["secondattribute"] = attArr[0].rawValue
}
}
if let attArr = XMLStatic.XMLViewConstraintAttributeMap[conf["firstattribute"] as! String] {
conf["firstattribute"] = attArr[0].rawValue
if attArr.count > 1 { conf["secondattribute"] = attArr[1].rawValue}
}
// 查找 second
if let secondId = conf["second"] as? String {
if secondId == "super" || secondId == self.superview?.xml?.attributeForName("id").stringValue(){
conf["second"] = self.superview! // superview 一定要存在,如果不存在,则这个时候是不能设置约束的
}else{
// 在兄弟间查找
for brother in self.superview!.subviews as! [UIView] {
if secondId == brother.xml?.attributeForName("id")?.stringValue() {
conf["second"] = brother
}
}
}
}else if name == "ratio" {
conf["second"] = self
}
var firstView = conf["first"] as! UIView
var secondView = conf["second"] as? UIView
firstView.setTranslatesAutoresizingMaskIntoConstraints(false)
var constraint = NSLayoutConstraint(item: firstView, attribute: NSLayoutAttribute(rawValue: conf["firstattribute"] as! Int)!, relatedBy: NSLayoutRelation.Equal, toItem: secondView, attribute: NSLayoutAttribute(rawValue: conf["secondattribute"] as! Int)!, multiplier: CGFloat(conf["multiplier"] as! Float), constant: CGFloat(conf["constant"] as! Float))
if secondView == nil {
firstView.addConstraint(constraint)
}else{
firstView.superview?.addConstraint(constraint)
}
// 将 constraint 关联至 xmlnode 中,以便搜索到
var layoutConstraintid = String(format:"%@:%p",script,constraint)
XMLStatic.constraintUIDMap.setObject(constraint, forKey: layoutConstraintid)
constraintNode?.setStringValue(layoutConstraintid)
}
}
for subview in self.subviews as! [UIView]{
if subview is XMLViewProtocol {
subview.loadXMLConstraints()
}
}
}
}
class CMView: UIView, XMLViewProtocol {
} | apache-2.0 | f7d2947aa9b974e53fc9c170712de6a7 | 40.286567 | 368 | 0.527043 | 4.862869 | false | false | false | false |
naithar/Kitura-net | Sources/KituraNet/HTTPParser/Query/Query.swift | 1 | 5165 | /**
* Copyright IBM Corporation 2016
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
import Foundation
// MARK: Query
/// Type for storing query key - parameter values
///
///
public struct Query: CustomStringConvertible {
#if os(Linux)
typealias RegularExpressionType = RegularExpression
#else
typealias RegularExpressionType = NSRegularExpression
#endif
/// Regular expression used to parse dicrionary or array passed as query object
static var indexedParameterRegex: RegularExpressionType? = {
return try? RegularExpressionType(pattern: "([^\\[\\]\\,\\.\\s]*)\\[([^\\[\\]\\,\\.\\s]*)\\]", options: .caseInsensitive)
}()
public static let null = Query()
/// Query parameter types
///
///
public enum ParameterType {
/// Parameter with invalid object or of unknown type
case null(object: Any)
/// Parameter of array type
case array([Any])
/// Parameter of dictionary type
case dictionary([String : Any])
/// Parameter of integer type
case int(Int)
/// Parameter of string type
case string(String)
/// Parameter of floating-point type
case double(Double)
/// Parameter of boolean type
case bool(Bool)
}
fileprivate(set) public var type: ParameterType = .null(object: NSNull())
private init() { }
/// Initialize a new Query instance.
///
/// - Parameter object: object to be parsed as query parameter.
public init(_ object: Any) {
self.object = object
}
/// Formatted description of the parsed query parameter.
public var description: String {
return "\(self.object)"
}
}
extension Query {
/// Object contained in query parameter.
fileprivate(set) public var object: Any {
get {
switch self.type {
case .string(let value):
return value
case .int(let value):
return value
case .double(let value):
return value
case .bool(let value):
return value
case .array(let value):
return value
case .dictionary(let value):
return value
case .null(let object):
return object
}
}
set {
switch newValue {
case let string as String where !string.isEmpty:
if let int = Int(string) {
self.type = .int(int)
} else if let double = Double(string) {
self.type = .double(double)
} else if let bool = Bool(string) {
self.type = .bool(bool)
} else {
self.type = .string(string)
}
case let int as Int:
self.type = .int(int)
case let double as Double:
self.type = .double(double)
case let bool as Bool:
self.type = .bool(bool)
case let array as [Any]:
self.type = .array(array)
case let dictionary as [String : Any]:
self.type = .dictionary(dictionary)
default:
self.type = .null(object: newValue)
}
}
}
internal(set) public subscript(key: QueryKeyProtocol) -> Query {
set {
let realKey = key.queryKey
switch (realKey, self.type) {
case (.key(let key), .dictionary(var dictionary)):
dictionary[key] = newValue.object
self.type = .dictionary(dictionary)
default:
break
}
}
get {
let realKey = key.queryKey
switch (realKey, self.type) {
case (.key(let key), .dictionary(let dictionary)):
guard let value = dictionary[key] else {
return Query.null
}
return Query(value)
case (.index(let index), .array(let array)):
guard array.count > index,
index >= 0 else {
return Query.null
}
return Query(array[index])
default:
break
}
return Query.null
}
}
public subscript(keys: [QueryKeyProtocol]) -> Query {
get {
return keys.reduce(self) { $0[$1] }
}
}
public subscript(keys: QueryKeyProtocol...) -> Query {
get {
return self[keys]
}
}
}
| apache-2.0 | e9ead48fc67dca6867e6e1ff89c239c7 | 28.016854 | 129 | 0.533011 | 4.872642 | false | false | false | false |
duliodenis/HackingWithSwift | project-14/Whack-a-Penguin/Whack-a-Penguin/GameViewController.swift | 1 | 2152 | //
// GameViewController.swift
// Whack-a-Penguin
//
// Created by Dulio Denis on 1/25/15.
// Copyright (c) 2015 ddApps. All rights reserved.
//
import UIKit
import SpriteKit
extension SKNode {
class func unarchiveFromFile(file : NSString) -> SKNode? {
if let path = NSBundle.mainBundle().pathForResource(file, ofType: "sks") {
var sceneData = NSData(contentsOfFile: path, options: .DataReadingMappedIfSafe, error: nil)!
var archiver = NSKeyedUnarchiver(forReadingWithData: sceneData)
archiver.setClass(self.classForKeyedUnarchiver(), forClassName: "SKScene")
let scene = archiver.decodeObjectForKey(NSKeyedArchiveRootObjectKey) as GameScene
archiver.finishDecoding()
return scene
} else {
return nil
}
}
}
class GameViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
if let scene = GameScene.unarchiveFromFile("GameScene") as? GameScene {
// Configure the view.
let skView = self.view as SKView
//skView.showsFPS = true
//skView.showsNodeCount = true
/* Sprite Kit applies additional optimizations to improve rendering performance */
skView.ignoresSiblingOrder = true
/* Set the scale mode to scale to fit the window */
scene.scaleMode = .AspectFill
skView.presentScene(scene)
}
}
override func shouldAutorotate() -> Bool {
return true
}
override func supportedInterfaceOrientations() -> Int {
if UIDevice.currentDevice().userInterfaceIdiom == .Phone {
return Int(UIInterfaceOrientationMask.AllButUpsideDown.rawValue)
} else {
return Int(UIInterfaceOrientationMask.All.rawValue)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Release any cached data, images, etc that aren't in use.
}
override func prefersStatusBarHidden() -> Bool {
return true
}
}
| mit | e8f436b808e8e3a252533c5efad32948 | 30.188406 | 104 | 0.623141 | 5.517949 | false | false | false | false |
vakoc/particle-swift-cli | Sources/WebhookCommands.swift | 1 | 5869 | // This source file is part of the vakoc.com open source project(s)
//
// Copyright © 2016 Mark Vakoc. All rights reserved.
// Licensed under Apache License v2.0
//
// See http://www.vakoc.com/LICENSE.txt for license information
import Foundation
import ParticleSwift
fileprivate let productIdArgument = Argument(name: .productId, helpText: "Product ID or slug (only for product webhooks)", options: [.hasValue])
fileprivate let subHelp = "Get a list of the webhooks that you have created, either as a user or for a product."
let showWebhooksCommand = Command(name: .showWebhooks, summary: "Show Webhooks", arguments: [productIdArgument], subHelp: subHelp) {(arguments, extras, callback) in
let particleCloud = ParticleCloud(secureStorage: CliSecureStorage.shared)
particleCloud.webhooks(productIdOrSlug: arguments[productIdArgument]) { (result) in
switch (result) {
case .success(let webhooks):
let stringValue = "\(webhooks)"
callback( .success(string: stringValue, json: webhooks.map { $0.jsonRepresentation } ))
case .failure(let err):
callback( .failure(Errors.showWebhooksFailed(err)))
}
}
}
fileprivate let webhookIdArgument = Argument(name: .webhookId, helpText: "The webhook identifier", options: [.hasValue])
fileprivate let subHelp2 = "Get the webhook by identifier that you have created, either as a user or for a product."
let getWebhookCommand = Command(name: .getWebhook, summary: "Get Webhook", arguments: [productIdArgument, webhookIdArgument], subHelp: subHelp2) {(arguments, extras, callback) in
guard let webhookID = arguments[webhookIdArgument] else {
callback( .failure(Errors.invalidWebhookId))
return
}
let particleCloud = ParticleCloud(secureStorage: CliSecureStorage.shared)
particleCloud.webhook(webhookID, productIdOrSlug: arguments[productIdArgument]) { (result) in
switch (result) {
case .success(let webhook):
let stringValue = "\(webhook)"
callback( .success(string: stringValue, json: webhook.jsonRepresentation ))
case .failure(let err):
callback( .failure(Errors.getWebhookFailed(err)))
}
}
}
fileprivate let jsonFileArgument = Argument(name: .jsonFile, helpText: "Filename of JSON file defining the webhook relative to the current working directory", options: [.hasValue])
fileprivate let eventArgument = Argument(name: .event, helpText: "The name of the event", options: [.hasValue])
fileprivate let urlArgument = Argument(name: .url, helpText: "The name URL webhook", options: [.hasValue])
fileprivate let requestTypeArgument = Argument(name: .requestType, helpText: "The HTTP method type (GET/POST/PUT/DELETE)", options: [.hasValue])
fileprivate let subHelp3 = "Creates a webhook using either a JSON file, arguments, or a combination of both. If --event and --url arguments are specified those will be used, otherwise all parameters must come from a JSON file that includes at least those two entries. If event, url, and a JSON file are supplied the JSON file will augment the webhook definition."
// TODO: document the JSON file structure
let createWebhookCommand = Command(name: .createWebhook, summary: "Create a Webhook", arguments: [productIdArgument, jsonFileArgument, eventArgument, urlArgument, requestTypeArgument], subHelp: subHelp3) {(arguments, extras, callback) in
var webhook: Webhook?
if let event = arguments[eventArgument], let url = arguments[urlArgument], let parsedURL = URL(string: url) {
let requestType = Webhook.RequestType(rawValue: arguments[requestTypeArgument] ?? "GET")
webhook = Webhook(event: event, url: parsedURL, requestType: requestType ?? .get)
}
if let json = arguments[jsonFileArgument] {
let current = URL(fileURLWithPath: FileManager.default.currentDirectoryPath)
if let jsonUrl = URL(string: json, relativeTo: current), let data = try? Data(contentsOf: jsonUrl), let json = try? JSONSerialization.jsonObject(with: data, options: []) as? Dictionary<String,Any>, let j = json {
if var hook = webhook {
hook.configure(with: j)
} else {
webhook = Webhook(with: j)
}
} else {
return callback(.failure(Errors.failedToParseJsonFile))
}
}
guard let hook = webhook else {
return callback(.failure(Errors.failedToDefinedWebhook))
}
let particleCloud = ParticleCloud(secureStorage: CliSecureStorage.shared)
particleCloud.create(webhook: hook, productIdOrSlug: arguments[productIdArgument]) { result in
switch (result) {
case .success(let webhook):
let stringValue = "\(webhook)"
callback( .success(string: stringValue, json: webhook.jsonRepresentation ))
case .failure(let err):
callback( .failure(Errors.createWebhookFailed(err)))
}
}
}
fileprivate let subHelp4 = "Deletes a Webhook with the specified id"
let deleteWebhookCommand = Command(name: .deleteWebhook, summary: "Delete a Webhook", arguments: [productIdArgument,webhookIdArgument], subHelp: subHelp4) {(arguments, extras, callback) in
guard let webhookId = arguments[webhookIdArgument] else {
return callback(.failure(Errors.invalidWebhookId))
}
let particleCloud = ParticleCloud(secureStorage: CliSecureStorage.shared)
particleCloud.delete(webhookID: webhookId, productIdOrSlug: arguments[productIdArgument]) { result in
switch (result) {
case .success:
callback(.success(string: "ok", json:["ok" : true]))
case .failure(let err):
callback(.failure(Errors.deleteWebhookFailed(err)))
}
}
}
| apache-2.0 | 53df7f57ec9624b07afb90661f0896b5 | 48.728814 | 365 | 0.691036 | 4.445455 | false | false | false | false |
Quivr/iOS-Week-View | QVRWeekView/Classes/Common/EventData.swift | 1 | 13471 | //
// EventData.swift
// Pods
//
// Created by Reinert Lemmens on 7/25/17.
//
//
import Foundation
/**
Class event data stores basic data needed by the rest of the code to calculate and draw events in the dayViewCells in the dayScrollView.
*/
open class EventData: NSObject, NSCoding {
// Id of the event
public let id: String
// Title of the event
public let title: String
// Start date of the event
public let startDate: Date
// End date of the event
public let endDate: Date
// Location of the event
public let location: String
// Color of the event
public let color: UIColor
// Stores if event is an all day event
public let allDay: Bool
// Stores an optional gradient layer which will be used to draw event. Can only be set once.
private(set) var gradientLayer: CAGradientLayer? { didSet { gradientLayer = oldValue ?? gradientLayer } }
// String descriptor
override public var description: String {
return "[Event: {id: \(id), startDate: \(startDate), endDate: \(endDate)}]\n"
}
/**
Main initializer. All properties.
*/
public init(id: String, title: String, startDate: Date, endDate: Date, location: String, color: UIColor, allDay: Bool, gradientLayer: CAGradientLayer? = nil) {
self.id = id
self.title = title
self.location = location
self.color = color
self.allDay = allDay
guard startDate.compare(endDate).rawValue <= 0 else {
self.startDate = startDate
self.endDate = startDate
super.init()
return
}
self.startDate = startDate
self.endDate = endDate
super.init()
self.configureGradient(gradientLayer)
}
/**
Convenience initializer. All properties except for Int Id instead of String.
*/
public convenience init(id: Int, title: String, startDate: Date, endDate: Date, location: String, color: UIColor, allDay: Bool) {
self.init(id: String(id), title: title, startDate: startDate, endDate: endDate, location: location, color: color, allDay: allDay)
}
/**
Convenience initializer. String Id + no allDay parameter.
*/
public convenience init(id: String, title: String, startDate: Date, endDate: Date, location: String, color: UIColor) {
self.init(id: id, title: title, startDate: startDate, endDate: endDate, location: location, color: color, allDay: false)
}
/**
Convenience initializer. Int Id + no allDay parameter.
*/
public convenience init(id: Int, title: String, startDate: Date, endDate: Date, location: String, color: UIColor) {
self.init(id: id, title: title, startDate: startDate, endDate: endDate, location: location, color: color, allDay: false)
}
/**
Convenience initializer. String Id + no allDay and location parameter.
*/
public convenience init(id: String, title: String, startDate: Date, endDate: Date, color: UIColor) {
self.init(id: id, title: title, startDate: startDate, endDate: endDate, location: "", color: color, allDay: false)
}
/**
Convenience initializer. Int Id + no allDay and location parameter.
*/
public convenience init(id: Int, title: String, startDate: Date, endDate: Date, color: UIColor) {
self.init(id: id, title: title, startDate: startDate, endDate: endDate, location: "", color: color, allDay: false)
}
/**
Convenience initializer. Int Id + allDay and no location parameter.
*/
public convenience init(id: Int, title: String, startDate: Date, endDate: Date, color: UIColor, allDay: Bool) {
self.init(id: id, title: title, startDate: startDate, endDate: endDate, location: "", color: color, allDay: allDay)
}
/**
Convenience initializer. String Id + allDay and no location parameter.
*/
public convenience init(id: String, title: String, startDate: Date, endDate: Date, color: UIColor, allDay: Bool) {
self.init(id: id, title: title, startDate: startDate, endDate: endDate, location: "", color: color, allDay: allDay)
}
/**
Convenience initializer.
*/
override public convenience init() {
self.init(id: -1, title: "New Event", startDate: Date(), endDate: Date().addingTimeInterval(TimeInterval(exactly: 10000)!), color: UIColor.blue)
}
public func encode(with coder: NSCoder) {
coder.encode(id, forKey: EventDataEncoderKey.id)
coder.encode(title, forKey: EventDataEncoderKey.title)
coder.encode(startDate, forKey: EventDataEncoderKey.startDate)
coder.encode(endDate, forKey: EventDataEncoderKey.endDate)
coder.encode(location, forKey: EventDataEncoderKey.location)
coder.encode(color, forKey: EventDataEncoderKey.color)
coder.encode(allDay, forKey: EventDataEncoderKey.allDay)
coder.encode(gradientLayer, forKey: EventDataEncoderKey.gradientLayer)
}
public required convenience init?(coder: NSCoder) {
if let dId = coder.decodeObject(forKey: EventDataEncoderKey.id) as? String,
let dTitle = coder.decodeObject(forKey: EventDataEncoderKey.title) as? String,
let dStartDate = coder.decodeObject(forKey: EventDataEncoderKey.startDate) as? Date,
let dEndDate = coder.decodeObject(forKey: EventDataEncoderKey.endDate) as? Date,
let dLocation = coder.decodeObject(forKey: EventDataEncoderKey.location) as? String,
let dColor = coder.decodeObject(forKey: EventDataEncoderKey.color) as? UIColor {
let dGradientLayer = coder.decodeObject(forKey: EventDataEncoderKey.gradientLayer) as? CAGradientLayer
let dAllDay = coder.decodeBool(forKey: EventDataEncoderKey.allDay)
self.init(id: dId,
title: dTitle,
startDate: dStartDate,
endDate: dEndDate,
location: dLocation,
color: dColor,
allDay: dAllDay,
gradientLayer: dGradientLayer)
} else {
return nil
}
}
// Static equal comparison operator
public static func isEqual(lhs: EventData, rhs: EventData) -> Bool {
return (lhs.id == rhs.id) &&
(lhs.startDate == rhs.startDate) &&
(lhs.endDate == rhs.endDate) &&
(lhs.title == rhs.title) &&
(lhs.location == rhs.location) &&
(lhs.allDay == rhs.allDay) &&
(lhs.color.isEqual(rhs.color))
}
public override var hash: Int {
var hasher = Hasher()
hasher.combine(id)
return hasher.finalize()
}
/**
Returns the string that will be displayed by this event. Overridable.
*/
open func getDisplayString(withMainFont mainFont: UIFont, infoFont: UIFont, andColor color: UIColor) -> NSAttributedString {
let df = DateFormatter()
df.dateFormat = "HH:mm"
let mainFontAttributes: [NSAttributedString.Key: Any] = [NSAttributedString.Key.font: mainFont, NSAttributedString.Key.foregroundColor: color.cgColor]
let infoFontAttributes: [NSAttributedString.Key: Any] = [NSAttributedString.Key.font: infoFont, NSAttributedString.Key.foregroundColor: color.cgColor]
let mainAttributedString = NSMutableAttributedString(string: self.title, attributes: mainFontAttributes)
if !self.allDay {
mainAttributedString.append(NSMutableAttributedString(
string: " (\(df.string(from: self.startDate)) - \(df.string(from: self.endDate)))",
attributes: infoFontAttributes)
)
}
if self.location != "" {
mainAttributedString.append(NSMutableAttributedString(string: " | \(self.location)", attributes: infoFontAttributes))
}
return mainAttributedString
}
// Configures the gradient based on the provided color and given endColor.
public func configureGradient(_ endColor: UIColor) {
let gradient = CAGradientLayer()
gradient.colors = [self.color.cgColor, endColor.cgColor]
gradient.startPoint = CGPoint(x: 0, y: 0)
gradient.endPoint = CGPoint(x: 1, y: 1)
self.gradientLayer = gradient
}
// Configures the gradient based on provided gradient. Only preserves colors, start and endpoint.
public func configureGradient(_ gradient: CAGradientLayer?) {
if let grad = gradient {
let newGrad = CAGradientLayer()
newGrad.colors = grad.colors
newGrad.startPoint = grad.startPoint
newGrad.endPoint = grad.endPoint
self.gradientLayer = newGrad
}
}
public func remakeEventData(withStart start: Date, andEnd end: Date) -> EventData {
let newEvent = EventData(id: self.id, title: self.title, startDate: start, endDate: end, location: self.location, color: self.color, allDay: self.allDay)
newEvent.configureGradient(self.gradientLayer)
return newEvent
}
public func remakeEventData(withColor color: UIColor) -> EventData {
let newEvent = EventData(id: self.id, title: self.title, startDate: self.startDate, endDate: self.endDate, location: self.location, color: color, allDay: self.allDay)
newEvent.configureGradient(self.gradientLayer)
return newEvent
}
public func remakeEventDataAsAllDay(forDate date: Date) -> EventData {
let newEvent = EventData(id: self.id, title: self.title, startDate: date.getStartOfDay(), endDate: date.getEndOfDay(), location: self.location, color: self.color, allDay: true)
newEvent.configureGradient(self.gradientLayer)
return newEvent
}
/**
In case this event spans multiple days this function will be called to split it into multiple events
which can be assigned to individual dayViewCells.b
*/
func checkForSplitting (andAutoConvert autoConvertAllDayEvents: Bool) -> [DayDate: EventData] {
var splitEvents: [DayDate: EventData] = [:]
let startDayDate = DayDate(date: startDate)
if startDate.isSameDayAs(endDate) {
// Case: regular event that starts and ends in same day
splitEvents[startDayDate] = self
}
else if !startDate.isSameDayAs(endDate) && endDate.isMidnight(afterDate: startDate) {
// Case: an event that goes from to 00:00 the next day. Gets recreated to end with 23:59:59.
let newData = self.remakeEventData(withStart: startDate, andEnd: startDate.getEndOfDay())
splitEvents[startDayDate] = newData
}
else if !endDate.isMidnight(afterDate: startDate) {
// Case: an event that goes across multiple days
let dateRange = DateSupport.getAllDates(between: startDate, and: endDate)
// Iterate over all days that the event traverses
for date in dateRange {
if self.allDay {
// If the event is an allday event remake it as all day for this day.
splitEvents[DayDate(date: date)] = self.remakeEventDataAsAllDay(forDate: date)
}
else {
var newData = EventData()
if date.isSameDayAs(startDate) {
// The first fragment of a split event
newData = self.remakeEventData(withStart: startDate, andEnd: date.getEndOfDay())
}
else if date.isSameDayAs(endDate) {
// The last fragment of a split event
newData = self.remakeEventData(withStart: date.getStartOfDay(), andEnd: endDate)
}
else {
// A fragment in the middle
if autoConvertAllDayEvents {
// If enabled, split the day into an all day event
newData = self.remakeEventDataAsAllDay(forDate: date)
} else {
// If not enabled, let the event run the full length of the day
newData = self.remakeEventData(withStart: date.getStartOfDay(), andEnd: date.getEndOfDay())
}
}
splitEvents[DayDate(date: date)] = newData
}
}
}
return splitEvents
}
func getGradientLayer(withFrame frame: CGRect) -> CAGradientLayer? {
guard let gradient = self.gradientLayer else {
return nil
}
let newGrad = CAGradientLayer()
newGrad.colors = gradient.colors
newGrad.startPoint = gradient.startPoint
newGrad.endPoint = gradient.endPoint
CATransaction.begin()
CATransaction.setValue(kCFBooleanTrue, forKey: kCATransactionDisableActions)
newGrad.frame = frame
CATransaction.commit()
return newGrad
}
}
struct EventDataEncoderKey {
static let id = "EVENT_DATA_ID"
static let title = "EVENT_DATA_TITLE"
static let startDate = "EVENT_DATA_START_DATE"
static let endDate = "EVENT_DATA_END_DATE"
static let location = "EVENT_DATA_LOCATION"
static let color = "EVENT_DATA_COLOR"
static let allDay = "EVENT_DATA_ALL_DAY"
static let gradientLayer = "EVENT_DATA_GRADIENT_LAYER"
}
| mit | f7360a87bb5a70776d3e6fadca5a9a04 | 43.754153 | 184 | 0.632099 | 4.641971 | false | false | false | false |
jjochen/photostickers | MessagesExtension/Services/PSError.swift | 1 | 2423 | //
// CastOrFail.swift
// EasyHue
//
// Created by Jochen Pfeiffer on 19/12/2016.
// Copyright © 2016 Jochen Pfeiffer. All rights reserved.
//
import Foundation
import Log
public enum PSError:
Swift.Error,
CustomDebugStringConvertible {
/// Unknown error has occurred.
case unknown
/// Invalid operation was attempted.
case invalidOperation(object: Any)
/// Casting error.
case castingError(object: Any, targetType: Any.Type)
}
// MARK: Debug descriptions
extension PSError {
/// A textual representation of `self`, suitable for debugging.
public var debugDescription: String {
switch self {
case .unknown:
return "Unknown error occurred."
case let .invalidOperation(object):
return "Invalid operation was attempted on `\(object)`."
case let .castingError(object, targetType):
return "Error casting `\(object)` to `\(targetType)`"
}
}
}
// MARK: casts or fatal error
// workaround for Swift compiler bug
func castOptionalOrFatalError<T>(_ value: Any?) -> T? {
if value == nil {
return nil
}
let v: T = castOrFatalError(value)
return v
}
func castOrThrow<T>(_ resultType: T.Type, _ object: Any) throws -> T {
guard let returnValue = object as? T else {
throw PSError.castingError(object: object, targetType: resultType)
}
return returnValue
}
func castOptionalOrThrow<T>(_ resultType: T.Type, _ object: AnyObject) throws -> T? {
if NSNull().isEqual(object) {
return nil
}
guard let returnValue = object as? T else {
throw PSError.castingError(object: object, targetType: resultType)
}
return returnValue
}
func castOrFatalError<T>(_ value: AnyObject!, message: String) -> T {
let maybeResult: T? = value as? T
guard let result = maybeResult else {
psFatalError(message)
}
return result
}
func castOrFatalError<T>(_ value: Any!) -> T {
let maybeResult: T? = value as? T
guard let result = maybeResult else {
psFatalError("Failure converting from \(String(describing: value)) to \(T.self)")
}
return result
}
func psFatalError(_ lastMessage: String) -> Never {
fatalError(lastMessage)
}
func fatalErrorWhileDebugging(_ lastMessage: String) {
#if DEBUG
fatalError(lastMessage)
#else
Logger.shared.error(lastMessage)
#endif
}
| mit | 5baa8d2bdf75bf4a955712beef8b4167 | 23.714286 | 89 | 0.649463 | 4.309609 | false | false | false | false |
FlexMonkey/Filterpedia | Filterpedia/customFilters/FilmicEffects.swift | 1 | 5002 | //
// FilmicEffects.swift
// Filterpedia
//
// Created by Simon Gladman on 09/02/2016.
// Copyright © 2016 Simon Gladman. All rights reserved.
//
// 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 CoreImage
// MARKL Bleach Bypass
// Based on http://developer.download.nvidia.com/shaderlibrary/webpages/shader_library.html#post_bleach_bypass
class BleachBypassFilter: CIFilter
{
var inputImage : CIImage?
var inputAmount = CGFloat(1)
override var attributes: [String : AnyObject]
{
return [
kCIAttributeFilterDisplayName: "Bleach Bypass Filter",
"inputImage": [kCIAttributeIdentity: 0,
kCIAttributeClass: "CIImage",
kCIAttributeDisplayName: "Image",
kCIAttributeType: kCIAttributeTypeImage],
"inputAmount": [kCIAttributeIdentity: 0,
kCIAttributeClass: "NSNumber",
kCIAttributeDefault: 1,
kCIAttributeDisplayName: "Amount",
kCIAttributeMin: 0,
kCIAttributeSliderMin: 0,
kCIAttributeSliderMax: 1,
kCIAttributeType: kCIAttributeTypeScalar]
]
}
override func setDefaults()
{
inputAmount = 1
}
let bleachBypassKernel = CIColorKernel(string:
"kernel vec4 bleachBypassFilter(__sample image, float amount) \n" +
"{ \n" +
" float luma = dot(image.rgb, vec3(0.2126, 0.7152, 0.0722));" +
" float l = min(1.0, max (0.0, 10.0 * (luma - 0.45))); \n" +
" vec3 result1 = vec3(2.0) * image.rgb * vec3(luma); \n" +
" vec3 result2 = 1.0 - 2.0 * (1.0 - luma) * (1.0 - image.rgb); \n" +
" vec3 newColor = mix(result1,result2,l); \n" +
" return mix(image, vec4(newColor.r, newColor.g, newColor.b, image.a), amount); \n" +
"}"
)
override var outputImage: CIImage!
{
guard let inputImage = inputImage,
bleachBypassKernel = bleachBypassKernel else
{
return nil
}
let extent = inputImage.extent
let arguments = [inputImage, inputAmount]
return bleachBypassKernel.applyWithExtent(extent, arguments: arguments)
}
}
// MARK: 3 Strip TechnicolorFilter
// Based on shader code from http://001.vade.info/
class TechnicolorFilter: CIFilter
{
var inputImage : CIImage?
var inputAmount = CGFloat(1)
override var attributes: [String : AnyObject]
{
return [
kCIAttributeFilterDisplayName: "Technicolor Filter",
"inputImage": [kCIAttributeIdentity: 0,
kCIAttributeClass: "CIImage",
kCIAttributeDisplayName: "Image",
kCIAttributeType: kCIAttributeTypeImage],
"inputAmount": [kCIAttributeIdentity: 0,
kCIAttributeClass: "NSNumber",
kCIAttributeDefault: 1,
kCIAttributeDisplayName: "Amount",
kCIAttributeMin: 0,
kCIAttributeSliderMin: 0,
kCIAttributeSliderMax: 1,
kCIAttributeType: kCIAttributeTypeScalar]
]
}
override func setDefaults()
{
inputAmount = 1
}
let technicolorKernel = CIColorKernel(string:
"kernel vec4 technicolorFilter(__sample image, float amount)" +
"{" +
" vec3 redmatte = 1.0 - vec3(image.r - ((image.g + image.b)/2.0));" +
" vec3 greenmatte = 1.0 - vec3(image.g - ((image.r + image.b)/2.0));" +
" vec3 bluematte = 1.0 - vec3(image.b - ((image.r + image.g)/2.0)); " +
" vec3 red = greenmatte * bluematte * image.r; " +
" vec3 green = redmatte * bluematte * image.g; " +
" vec3 blue = redmatte * greenmatte * image.b; " +
" return mix(image, vec4(red.r, green.g, blue.b, image.a), amount);" +
"}"
)
override var outputImage: CIImage!
{
guard let inputImage = inputImage,
technicolorKernel = technicolorKernel else
{
return nil
}
let extent = inputImage.extent
let arguments = [inputImage, inputAmount]
return technicolorKernel.applyWithExtent(extent, arguments: arguments)
}
}
| gpl-3.0 | ccd787d337dd299374ca057a1744aec9 | 32.563758 | 110 | 0.584683 | 4.259796 | false | false | false | false |
vector-im/vector-ios | Riot/Managers/URLPreviews/URLPreviewService.swift | 1 | 7950 | //
// Copyright 2021 New Vector Ltd
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import Foundation
import AFNetworking
enum URLPreviewServiceError: Error {
case missingResponse
}
@objcMembers
/// A service for URL preview data that handles fetching, caching and clean-up
/// as well as remembering which previews have been closed by the user.
class URLPreviewService: NSObject {
// MARK: - Properties
/// The shared service object.
static let shared = URLPreviewService()
/// A persistent store backed by Core Data to reduce network requests
private let store = URLPreviewStore()
// MARK: - Public
/// Generates preview data for a URL to be previewed as part of the supplied event,
/// first checking the cache, and if necessary making a request to the homeserver.
/// You should call `hasClosedPreview` first to ensure that a preview is required.
/// - Parameters:
/// - url: The URL to generate the preview for.
/// - event: The event that the preview is for.
/// - session: The session to use to contact the homeserver.
/// - success: The closure called when the operation complete. The generated preview data is passed in.
/// - failure: The closure called when something goes wrong. The error that occured is passed in.
func preview(for url: URL,
and event: MXEvent,
with session: MXSession,
success: @escaping (URLPreviewData) -> Void,
failure: @escaping (Error?) -> Void) {
// Sanitize the URL before checking the store or performing lookup
let sanitizedURL = sanitize(url)
// Check for a valid preview in the store, and use this if found
if let preview = store.preview(for: sanitizedURL, and: event) {
MXLog.debug("[URLPreviewService] Using cached preview.")
success(preview)
return
}
// Otherwise make a request to the homeserver to generate a preview
session.matrixRestClient.preview(for: sanitizedURL, success: { previewResponse in
MXLog.debug("[URLPreviewService] Cached preview not found. Requesting from homeserver.")
guard let previewResponse = previewResponse else {
failure(URLPreviewServiceError.missingResponse)
return
}
// Convert the response to preview data, fetching the image if provided.
self.makePreviewData(from: previewResponse, for: sanitizedURL, and: event, with: session) { previewData in
self.store.cache(previewData)
success(previewData)
}
}, failure: { error in
self.checkForDisabledAPI(in: error)
failure(error)
})
}
/// Removes any cached preview data that has expired.
func removeExpiredCacheData() {
store.removeExpiredItems()
}
/// Deletes all cached preview data and closed previews from the store,
/// re-enabling URL previews if they have been disabled by `checkForDisabledAPI`.
func clearStore() {
store.deleteAll()
MXKAppSettings.standard().enableBubbleComponentLinkDetection = true
}
/// Store the `eventId` and `roomId` of a closed preview.
func closePreview(for eventId: String, in roomId: String) {
store.closePreview(for: eventId, in: roomId)
}
/// Whether a preview for the given event should be shown or not.
func shouldShowPreview(for event: MXEvent) -> Bool {
!store.hasClosedPreview(for: event.eventId, in: event.roomId)
}
// MARK: - Private
/// Convert an `MXURLPreview` object into `URLPreviewData` whilst also getting the image via the media manager.
/// - Parameters:
/// - previewResponse: The `MXURLPreview` object to convert.
/// - url: The URL that response was for.
/// - event: The event that the URL preview is for.
/// - session: The session to use to for media management.
/// - completion: A closure called when the operation completes. This contains the preview data.
private func makePreviewData(from previewResponse: MXURLPreview,
for url: URL,
and event: MXEvent,
with session: MXSession,
completion: @escaping (URLPreviewData) -> Void) {
// Create the preview data and return if no image is needed.
let previewData = URLPreviewData(url: url,
eventID: event.eventId,
roomID: event.roomId,
siteName: previewResponse.siteName,
title: previewResponse.title,
text: previewResponse.text)
guard let imageURL = previewResponse.imageURL else {
completion(previewData)
return
}
// Check for an image in the media cache and use this if found.
if let cachePath = MXMediaManager.cachePath(forMatrixContentURI: imageURL, andType: previewResponse.imageType, inFolder: nil),
let image = MXMediaManager.loadThroughCache(withFilePath: cachePath) {
previewData.image = image
completion(previewData)
return
}
// Don't de-dupe image downloads as the service should de-dupe preview generation.
// Otherwise download the image from the homeserver, treating an error as a preview without an image.
session.mediaManager.downloadMedia(fromMatrixContentURI: imageURL, withType: previewResponse.imageType, inFolder: nil) { path in
guard let image = MXMediaManager.loadThroughCache(withFilePath: path) else {
completion(previewData)
return
}
previewData.image = image
completion(previewData)
} failure: { error in
completion(previewData)
}
}
/// Returns a URL created from the URL passed in, with sanitizations applied to reduce
/// queries and duplicate cache data for URLs that will return the same preview data.
private func sanitize(_ url: URL) -> URL {
// Remove the fragment from the URL.
var components = URLComponents(url: url, resolvingAgainstBaseURL: false)
components?.fragment = nil
return components?.url ?? url
}
/// Checks an error returned from `MXRestClient` to see whether the previews API
/// has been disabled on the homeserver. If this is true, link detection will be disabled
/// to prevent further requests being made and stop any previews loaders being presented.
private func checkForDisabledAPI(in error: Error?) {
// The error we're looking for is a generic 404 and not a matrix error.
guard
!MXError.isMXError(error),
let response = MXHTTPOperation.urlResponse(fromError: error)
else { return }
if response.statusCode == 404 {
MXLog.debug("[URLPreviewService] Disabling link detection as homeserver does not support URL previews.")
MXKAppSettings.standard().enableBubbleComponentLinkDetection = false
}
}
}
| apache-2.0 | 205cba3809b1b2ad263d6f02df146c8f | 42.922652 | 136 | 0.63044 | 5.054037 | false | false | false | false |
xxxAIRINxxx/Cmg | Sources/UIImage+CmgShorthand.swift | 1 | 2730 | //
// UIImage+CmgShorthand.swift
// Cmg
//
// Created by xxxAIRINxxx on 2016/02/24.
// Copyright © 2016 xxxAIRINxxx. All rights reserved.
//
import Foundation
import UIKit
import CoreImage
extension UIImage {
// MARK: - Blur
@available(iOS 9.0, *)
public func cmg_boxBlur(_ radius: Float = 10) -> UIImage? {
var filter = BoxBlur()
filter.radius = radius
return filter.processing(self)
}
public func cmg_gaussianBlur(_ radius: Float = 10) -> UIImage? {
var filter = GaussianBlur()
filter.radius = radius
return filter.processing(self)
}
@available(iOS 9.0, *)
public func cmg_median() -> UIImage? {
return Median().processing(self)
}
// Geometry Adjustment
public func cmg_resize(_ newSize: CGSize) -> UIImage? {
let scale = CGPoint(x: newSize.width / self.size.width, y: newSize.height / self.size.height)
let bounds = CGRect(origin: CGPoint.zero, size: newSize)
let filter = AffineTransform()
filter.setScale(scale.x, scale.y)
return filter.processingIntoCIImage(self)?.cropped(to: bounds).generateUIImage(self)
}
public func cmg_resizeAtAspectFit(_ newSize: CGSize) -> UIImage? {
var destWidth: CGFloat = newSize.width
var destHeight: CGFloat = newSize.height
if self.size.width > self.size.height {
destHeight = (self.size.height * newSize.width / self.size.width)
} else {
destWidth = (self.size.width * newSize.height / self.size.height)
}
if destWidth > newSize.width {
destWidth = newSize.width
destHeight = (self.size.height * newSize.width / self.size.width)
}
if (destHeight > newSize.height) {
destHeight = newSize.height
destWidth = (self.size.width * newSize.height / self.size.height)
}
return self.cmg_resize(CGSize(width: destWidth, height: destHeight))
}
public func cmg_resizeAtAspectFill(_ newSize: CGSize) -> UIImage? {
var destWidth: CGFloat = newSize.width
var destHeight: CGFloat = newSize.height
let widthRatio = newSize.width / self.size.width
let heightRatio = newSize.height / self.size.height
if heightRatio > widthRatio {
destHeight = newSize.height
destWidth = (self.size.width * newSize.height / self.size.height)
} else {
destWidth = newSize.width;
destHeight = (self.size.height * newSize.width / self.size.width)
}
return self.cmg_resize(CGSize(width: destWidth, height: destHeight))
}
}
| mit | 3687806e7ea97c04fd8d1b4013a08efb | 31.879518 | 101 | 0.60535 | 4.237578 | false | false | false | false |
amosavian/FileProvider | Sources/WebDAVFileProvider.swift | 2 | 30894 | //
// WebDAVFileProvider.swift
// FileProvider
//
// Created by Amir Abbas Mousavian.
// Copyright © 2016 Mousavian. Distributed under MIT license.
//
import Foundation
#if os(macOS) || os(iOS) || os(tvOS)
import CoreGraphics
#endif
/**
Allows accessing to WebDAV server files. This provider doesn't cache or save files internally, however you can
set `useCache` and `cache` properties to use Foundation `NSURLCache` system.
WebDAV system supported by many cloud services including [Box.com](https://www.box.com/home)
and [Yandex disk](https://disk.yandex.com) and [ownCloud](https://owncloud.org).
- Important: Because this class uses `URLSession`, it's necessary to disable App Transport Security
in case of using this class with unencrypted HTTP connection.
[Read this to know how](http://iosdevtips.co/post/121756573323/ios-9-xcode-7-http-connect-server-error).
*/
open class WebDAVFileProvider: HTTPFileProvider, FileProviderSharing {
override open class var type: String { return "WebDAV" }
/// An enum which defines HTTP Authentication method, usually you should it default `.digest`.
/// If the server uses OAuth authentication, credential must be set with token as `password`, like Dropbox.
public var credentialType: URLRequest.AuthenticationType = .digest
/**
Initializes WebDAV provider.
- Parameters:
- baseURL: Location of WebDAV server.
- credential: An `URLCredential` object with `user` and `password`.
- cache: A URLCache to cache downloaded files and contents.
*/
public init? (baseURL: URL, credential: URLCredential?, cache: URLCache? = nil) {
if !["http", "https"].contains(baseURL.uw_scheme.lowercased()) {
return nil
}
let refinedBaseURL = (baseURL.absoluteString.hasSuffix("/") ? baseURL : baseURL.appendingPathComponent(""))
super.init(baseURL: refinedBaseURL.absoluteURL, credential: credential, cache: cache)
}
public required convenience init?(coder aDecoder: NSCoder) {
guard let baseURL = aDecoder.decodeObject(of: NSURL.self, forKey: "baseURL") as URL? else {
if #available(macOS 10.11, iOS 9.0, tvOS 9.0, *) {
aDecoder.failWithError(CocoaError(.coderValueNotFound,
userInfo: [NSLocalizedDescriptionKey: "Base URL is not set."]))
}
return nil
}
self.init(baseURL: baseURL,
credential: aDecoder.decodeObject(of: URLCredential.self, forKey: "credential"))
self.useCache = aDecoder.decodeBool(forKey: "useCache")
self.validatingCache = aDecoder.decodeBool(forKey: "validatingCache")
}
override open func copy(with zone: NSZone? = nil) -> Any {
let copy = WebDAVFileProvider(baseURL: self.baseURL!, credential: self.credential, cache: self.cache)!
copy.delegate = self.delegate
copy.fileOperationDelegate = self.fileOperationDelegate
copy.useCache = self.useCache
copy.validatingCache = self.validatingCache
return copy
}
/**
Returns an Array of `FileObject`s identifying the the directory entries via asynchronous completion handler.
If the directory contains no entries or an error is occured, this method will return the empty array.
- Parameters:
- path: path to target directory. If empty, root will be iterated.
- completionHandler: a closure with result of directory entries or error.
- contents: An array of `FileObject` identifying the the directory entries.
- error: Error returned by system.
*/
override open func contentsOfDirectory(path: String, completionHandler: @escaping (([FileObject], Error?) -> Void)) {
let query = NSPredicate(format: "TRUEPREDICATE")
_ = searchFiles(path: path, recursive: false, query: query, including: [], foundItemHandler: nil, completionHandler: completionHandler)
}
/**
Returns an Array of `FileObject`s identifying the the directory entries via asynchronous completion handler.
If the directory contains no entries or an error is occured, this method will return the empty array.
- Parameter path: path to target directory. If empty, root will be iterated.
- Parameter including: An array which determines which file properties should be considered to fetch.
- Parameter completionHandler: a closure with result of directory entries or error.
- Parameter contents: An array of `FileObject` identifying the the directory entries.
- Parameter error: Error returned by system.
*/
open func contentsOfDirectory(path: String, including: [URLResourceKey], completionHandler: @escaping (_ contents: [FileObject], _ error: Error?) -> Void) {
let query = NSPredicate(format: "TRUEPREDICATE")
_ = searchFiles(path: path, recursive: false, query: query, including: including, foundItemHandler: nil, completionHandler: completionHandler)
}
override open func attributesOfItem(path: String, completionHandler: @escaping (_ attributes: FileObject?, _ error: Error?) -> Void) {
self.attributesOfItem(path: path, including: [], completionHandler: completionHandler)
}
/**
Returns a `FileObject` containing the attributes of the item (file, directory, symlink, etc.) at the path in question via asynchronous completion handler.
If the directory contains no entries or an error is occured, this method will return the empty `FileObject`.
- Parameters:
- path: path to target directory. If empty, attributes of root will be returned.
- completionHandler: a closure with result of directory entries or error.
- attributes: A `FileObject` containing the attributes of the item.
- error: Error returned by system.
*/
open func attributesOfItem(path: String, including: [URLResourceKey], completionHandler: @escaping (_ attributes: FileObject?, _ error: Error?) -> Void) {
let url = self.url(of: path)
var request = URLRequest(url: url)
request.httpMethod = "PROPFIND"
request.setValue("0", forHTTPHeaderField: "Depth")
request.setValue(authentication: credential, with: credentialType)
request.setValue(contentType: .xml, charset: .utf8)
request.httpBody = WebDavFileObject.xmlProp(including)
runDataTask(with: request, completionHandler: { (data, response, error) in
var responseError: FileProviderHTTPError?
if let code = (response as? HTTPURLResponse)?.statusCode, code >= 300, let rCode = FileProviderHTTPErrorCode(rawValue: code) {
responseError = self.serverError(with: rCode, path: path, data: data)
}
if let data = data {
let xresponse = DavResponse.parse(xmlResponse: data, baseURL: self.baseURL)
if let attr = xresponse.first {
completionHandler(WebDavFileObject(attr), responseError ?? error)
return
}
}
completionHandler(nil, responseError ?? error)
})
}
/// Returns volume/provider information asynchronously.
/// - Parameter volumeInfo: Information of filesystem/Provider returned by system/server.
override open func storageProperties(completionHandler: @escaping (_ volumeInfo: VolumeObject?) -> Void) {
// Not all WebDAV clients implements RFC2518 which allows geting storage quota.
// In this case you won't get error. totalSize is NSURLSessionTransferSizeUnknown
// and used space is zero.
guard let baseURL = baseURL else {
return
}
var request = URLRequest(url: baseURL)
request.httpMethod = "PROPFIND"
request.setValue("0", forHTTPHeaderField: "Depth")
request.setValue(authentication: credential, with: credentialType)
request.setValue(contentType: .xml, charset: .utf8)
request.httpBody = WebDavFileObject.xmlProp([.volumeTotalCapacityKey, .volumeAvailableCapacityKey, .creationDateKey])
runDataTask(with: request, completionHandler: { (data, response, error) in
guard let data = data, let attr = DavResponse.parse(xmlResponse: data, baseURL: self.baseURL).first else {
completionHandler(nil)
return
}
let volume = VolumeObject(allValues: [:])
volume.creationDate = attr.prop["creationdate"].flatMap { Date(rfcString: $0) }
volume.availableCapacity = attr.prop["quota-available-bytes"].flatMap({ Int64($0) }) ?? 0
if let usage = attr.prop["quota-used-bytes"].flatMap({ Int64($0) }) {
volume.totalCapacity = volume.availableCapacity + usage
}
completionHandler(volume)
})
}
/**
Search files inside directory using query asynchronously.
Sample predicates:
```
NSPredicate(format: "(name CONTAINS[c] 'hello') && (fileSize >= 10000)")
NSPredicate(format: "(modifiedDate >= %@)", Date())
NSPredicate(format: "(path BEGINSWITH %@)", "folder/child folder")
```
- Note: Don't pass Spotlight predicates to this method directly, use `FileProvider.convertSpotlightPredicateTo()` method to get usable predicate.
- Important: A file name criteria should be provided for Dropbox.
- Parameters:
- path: location of directory to start search
- recursive: Searching subdirectories of path
- query: An `NSPredicate` object with keys like `FileObject` members, except `size` which becomes `filesize`.
- foundItemHandler: Closure which is called when a file is found
- completionHandler: Closure which will be called after finishing search. Returns an arry of `FileObject` or error if occured.
- files: all files meat the `query` criteria.
- error: `Error` returned by server if occured.
- Returns: An `Progress` to get progress or cancel progress. Use `completedUnitCount` to iterate count of found items.
*/
@discardableResult
open override func searchFiles(path: String, recursive: Bool, query: NSPredicate, foundItemHandler: ((FileObject) -> Void)?, completionHandler: @escaping ([FileObject], Error?) -> Void) -> Progress? {
return searchFiles(path: path, recursive: recursive, query: query, including: [], foundItemHandler: foundItemHandler, completionHandler: completionHandler)
}
/**
Search files inside directory using query asynchronously.
Sample predicates:
```
NSPredicate(format: "(name CONTAINS[c] 'hello') && (fileSize >= 10000)")
NSPredicate(format: "(modifiedDate >= %@)", Date())
NSPredicate(format: "(path BEGINSWITH %@)", "folder/child folder")
```
- Note: Don't pass Spotlight predicates to this method directly, use `FileProvider.convertSpotlightPredicateTo()` method to get usable predicate.
- Important: A file name criteria should be provided for Dropbox.
- Parameters:
- path: location of directory to start search
- recursive: Searching subdirectories of path
- query: An `NSPredicate` object with keys like `FileObject` members, except `size` which becomes `filesize`.
- including: An array which determines which file properties should be considered to fetch.
- foundItemHandler: Closure which is called when a file is found
- completionHandler: Closure which will be called after finishing search. Returns an arry of `FileObject` or error if occured.
- files: all files meat the `query` criteria.
- error: `Error` returned by server if occured.
- Returns: An `Progress` to get progress or cancel progress. Use `completedUnitCount` to iterate count of found items.
*/
@discardableResult
open func searchFiles(path: String, recursive: Bool, query: NSPredicate, including: [URLResourceKey], foundItemHandler: ((FileObject) -> Void)?, completionHandler: @escaping (_ files: [FileObject], _ error: Error?) -> Void) -> Progress? {
let url = self.url(of: path)
var request = URLRequest(url: url)
request.httpMethod = "PROPFIND"
// Depth infinity is disabled on some servers. Implement workaround?!
request.setValue(recursive ? "infinity" : "1", forHTTPHeaderField: "Depth")
request.setValue(authentication: credential, with: credentialType)
request.setValue(contentType: .xml, charset: .utf8)
request.httpBody = WebDavFileObject.xmlProp(including)
let progress = Progress(totalUnitCount: -1)
progress.setUserInfoObject(url, forKey: .fileURLKey)
let queryIsTruePredicate = query.predicateFormat == "TRUEPREDICATE"
let task = session.dataTask(with: request) { (data, response, error) in
// FIXME: paginating results
var responseError: FileProviderHTTPError?
if let code = (response as? HTTPURLResponse)?.statusCode , code >= 300, let rCode = FileProviderHTTPErrorCode(rawValue: code) {
responseError = self.serverError(with: rCode, path: path, data: data)
}
guard let data = data else {
completionHandler([], responseError ?? error)
return
}
let xresponse = DavResponse.parse(xmlResponse: data, baseURL: self.baseURL)
var fileObjects = [WebDavFileObject]()
for attr in xresponse where attr.href.path != url.path {
let fileObject = WebDavFileObject(attr)
if !queryIsTruePredicate && !query.evaluate(with: fileObject.mapPredicate()) {
continue
}
fileObjects.append(fileObject)
progress.completedUnitCount = Int64(fileObjects.count)
foundItemHandler?(fileObject)
}
completionHandler(fileObjects, responseError ?? error)
}
progress.cancellationHandler = { [weak task] in
task?.cancel()
}
progress.setUserInfoObject(Date(), forKey: .startingTimeKey)
task.resume()
return progress
}
override open func isReachable(completionHandler: @escaping (_ success: Bool, _ error: Error?) -> Void) {
var request = URLRequest(url: baseURL!)
request.httpMethod = "PROPFIND"
request.setValue("0", forHTTPHeaderField: "Depth")
request.setValue(authentication: credential, with: credentialType)
request.setValue(contentType: .xml, charset: .utf8)
request.httpBody = WebDavFileObject.xmlProp([.volumeTotalCapacityKey, .volumeAvailableCapacityKey])
runDataTask(with: request, completionHandler: { (data, response, error) in
let status = (response as? HTTPURLResponse)?.statusCode ?? 400
if status >= 400, let code = FileProviderHTTPErrorCode(rawValue: status) {
let errorDesc = data.flatMap({ String(data: $0, encoding: .utf8) })
let error = FileProviderWebDavError(code: code, path: "", serverDescription: errorDesc, url: self.baseURL!)
completionHandler(false, error)
return
}
completionHandler(status < 300, error)
})
}
open func publicLink(to path: String, completionHandler: @escaping ((URL?, FileObject?, Date?, Error?) -> Void)) {
guard self.baseURL?.host?.contains("dav.yandex.") ?? false else {
dispatch_queue.async {
completionHandler(nil, nil, nil, URLError(.resourceUnavailable, url: self.url(of: path)))
}
return
}
let url = self.url(of: path)
var request = URLRequest(url: url)
request.httpMethod = "PROPPATCH"
request.setValue(authentication: credential, with: credentialType)
request.setValue(contentType: .xml, charset: .utf8)
let body = "<propertyupdate xmlns=\"DAV:\">\n<set><prop>\n<public_url xmlns=\"urn:yandex:disk:meta\">true</public_url>\n</prop></set>\n</propertyupdate>"
request.httpBody = body.data(using: .utf8)
runDataTask(with: request, completionHandler: { (data, response, error) in
var responseError: FileProviderHTTPError?
if let code = (response as? HTTPURLResponse)?.statusCode, code >= 300, let rCode = FileProviderHTTPErrorCode(rawValue: code) {
responseError = self.serverError(with: rCode, path: path, data: data)
}
if let data = data {
let xresponse = DavResponse.parse(xmlResponse: data, baseURL: self.baseURL)
if let urlStr = xresponse.first?.prop["public_url"], let url = URL(string: urlStr) {
completionHandler(url, nil, nil, nil)
return
}
}
completionHandler(nil, nil, nil, responseError ?? error)
})
}
override func request(for operation: FileOperationType, overwrite: Bool = true, attributes: [URLResourceKey: Any] = [:]) -> URLRequest {
let method: String
let url: URL
let sourceURL = self.url(of: operation.source)
switch operation {
case .fetch:
method = "GET"
url = sourceURL
case .create:
if sourceURL.absoluteString.hasSuffix("/") {
method = "MKCOL"
url = sourceURL
} else {
fallthrough
}
case .modify:
method = "PUT"
url = sourceURL
break
case .copy(let source, let dest):
if source.hasPrefix("file://") {
method = "PUT"
url = self.url(of: dest)
} else if dest.hasPrefix("file://") {
method = "GET"
url = sourceURL
} else {
method = "COPY"
url = sourceURL
}
case .move:
method = "MOVE"
url = sourceURL
case .remove:
method = "DELETE"
url = sourceURL
default:
fatalError("Unimplemented operation \(operation.description) in \(#file)")
}
var request = URLRequest(url: url)
request.httpMethod = method
request.setValue(authentication: credential, with: credentialType)
request.setValue(overwrite ? "T" : "F", forHTTPHeaderField: "Overwrite")
if let dest = operation.destination, !dest.hasPrefix("file://") {
request.setValue(self.url(of:dest).absoluteString, forHTTPHeaderField: "Destination")
}
return request
}
override func serverError(with code: FileProviderHTTPErrorCode, path: String?, data: Data?) -> FileProviderHTTPError {
return FileProviderWebDavError(code: code, path: path ?? "", serverDescription: data.flatMap({ String(data: $0, encoding: .utf8) }), url: self.url(of: path ?? ""))
}
override func multiStatusError(operation: FileOperationType, data: Data) -> FileProviderHTTPError? {
let xresponses = DavResponse.parse(xmlResponse: data, baseURL: self.baseURL)
for xresponse in xresponses where (xresponse.status ?? 0) >= 300 {
let code = xresponse.status.flatMap { FileProviderHTTPErrorCode(rawValue: $0) } ?? .internalServerError
return self.serverError(with: code, path: operation.source, data: data)
}
return nil
}
/*
fileprivate func registerNotifcation(path: String, eventHandler: (() -> Void)) {
/* There is no unified api for monitoring WebDAV server content change/update
* Microsoft Exchange uses SUBSCRIBE method, Apple uses push notification system.
* while both is unavailable in a mobile platform.
* A messy approach is listing a directory with an interval period and compare
* with previous results
*/
NotImplemented()
}
fileprivate func unregisterNotifcation(path: String) {
NotImplemented()
}*/
// TODO: implements methods for lock mechanism
}
extension WebDAVFileProvider: ExtendedFileProvider {
#if os(macOS) || os(iOS) || os(tvOS)
open func thumbnailOfFileSupported(path: String) -> Bool {
guard self.baseURL?.host?.contains("dav.yandex.") ?? false else {
return false
}
let supportedExt: [String] = ["jpg", "jpeg", "png", "gif"]
return supportedExt.contains(path.pathExtension)
}
@discardableResult
open func thumbnailOfFile(path: String, dimension: CGSize?, completionHandler: @escaping ((ImageClass?, Error?) -> Void)) -> Progress? {
guard self.baseURL?.host?.contains("dav.yandex.") ?? false else {
dispatch_queue.async {
completionHandler(nil, URLError(.resourceUnavailable, url: self.url(of: path)))
}
return nil
}
let dimension = dimension ?? CGSize(width: 64, height: 64)
let url = URL(string: self.url(of: path).absoluteString + "?preview&size=\(dimension.width)x\(dimension.height)")!
var request = URLRequest(url: url)
request.httpMethod = "GET"
request.setValue(authentication: credential, with: credentialType)
let task = session.dataTask(with: request, completionHandler: { (data, response, error) in
var responseError: FileProviderHTTPError?
if let code = (response as? HTTPURLResponse)?.statusCode , code >= 300, let rCode = FileProviderHTTPErrorCode(rawValue: code) {
responseError = self.serverError(with: rCode, path: url.relativePath, data: data)
completionHandler(nil, responseError ?? error)
return
}
completionHandler(data.flatMap({ ImageClass(data: $0) }), nil)
})
task.resume()
return nil
}
#endif
open func propertiesOfFileSupported(path: String) -> Bool {
return false
}
@discardableResult
open func propertiesOfFile(path: String, completionHandler: @escaping (([String : Any], [String], Error?) -> Void)) -> Progress? {
dispatch_queue.async {
completionHandler([:], [], URLError(.resourceUnavailable, url: self.url(of: path)))
}
return nil
}
}
// MARK: WEBDAV XML response implementation
struct DavResponse {
let href: URL
let hrefString: String
let status: Int?
let prop: [String: String]
static let urlAllowed = CharacterSet(charactersIn: " ").inverted
init? (_ node: AEXMLElement, baseURL: URL?) {
func standardizePath(_ str: String) -> String {
let trimmedStr = str.hasPrefix("/") ? String(str[str.index(after: str.startIndex)...]) : str
return trimmedStr.addingPercentEncoding(withAllowedCharacters: .filePathAllowed) ?? str
}
// find node names with namespace
var hreftag = "href"
var statustag = "status"
var propstattag = "propstat"
for node in node.children {
if node.name.lowercased().hasSuffix("href") {
hreftag = node.name
}
if node.name.lowercased().hasSuffix("status") {
statustag = node.name
}
if node.name.lowercased().hasSuffix("propstat") {
propstattag = node.name
}
}
guard let hrefString = node[hreftag].value else { return nil }
// Percent-encoding space, some servers return invalid urls which space is not encoded to %20
let hrefStrPercented = hrefString.addingPercentEncoding(withAllowedCharacters: DavResponse.urlAllowed) ?? hrefString
// trying to figure out relative path out of href
let hrefAbsolute = URL(string: hrefStrPercented, relativeTo: baseURL)?.absoluteURL
let relativePath: String
if hrefAbsolute?.host?.replacingOccurrences(of: "www.", with: "", options: .anchored) == baseURL?.host?.replacingOccurrences(of: "www.", with: "", options: .anchored) {
relativePath = hrefAbsolute?.path.replacingOccurrences(of: baseURL?.absoluteURL.path ?? "", with: "", options: .anchored, range: nil) ?? hrefString
} else {
relativePath = hrefAbsolute?.absoluteString.replacingOccurrences(of: baseURL?.absoluteString ?? "", with: "", options: .anchored, range: nil) ?? hrefString
}
let hrefURL = URL(string: standardizePath(relativePath), relativeTo: baseURL) ?? baseURL
guard let href = hrefURL?.standardized else { return nil }
// reading status and properties
var status: Int?
let statusDesc = (node[statustag].string).components(separatedBy: " ")
if statusDesc.count > 2 {
status = Int(statusDesc[1])
}
var propDic = [String: String]()
let propStatNode = node[propstattag]
for node in propStatNode.children where node.name.lowercased().hasSuffix("status"){
statustag = node.name
break
}
let statusDesc2 = (propStatNode[statustag].string).components(separatedBy: " ")
if statusDesc2.count > 2 {
status = Int(statusDesc2[1])
}
var proptag = "prop"
for tnode in propStatNode.children where tnode.name.lowercased().hasSuffix("prop") {
proptag = tnode.name
break
}
for propItemNode in propStatNode[proptag].children {
let key = propItemNode.name.components(separatedBy: ":").last!.lowercased()
guard propDic.index(forKey: key) == nil else { continue }
propDic[key] = propItemNode.value
if key == "resourcetype" && propItemNode.xml.contains("collection") {
propDic["getcontenttype"] = ContentMIMEType.directory.rawValue
}
}
self.href = href
self.hrefString = hrefString
self.status = status
self.prop = propDic
}
static func parse(xmlResponse: Data, baseURL: URL?) -> [DavResponse] {
guard let xml = try? AEXMLDocument(xml: xmlResponse) else { return [] }
var result = [DavResponse]()
var rootnode = xml.root
var responsetag = "response"
for node in rootnode.all ?? [] where node.name.lowercased().hasSuffix("multistatus") {
rootnode = node
}
for node in rootnode.children where node.name.lowercased().hasSuffix("response") {
responsetag = node.name
break
}
for responseNode in rootnode[responsetag].all ?? [] {
if let davResponse = DavResponse(responseNode, baseURL: baseURL) {
result.append(davResponse)
}
}
return result
}
}
/// Containts path, url and attributes of a WebDAV file or resource.
public final class WebDavFileObject: FileObject {
internal init(_ davResponse: DavResponse) {
let href = davResponse.href
let name = davResponse.prop["displayname"] ?? davResponse.href.lastPathComponent
let relativePath = href.relativePath
let path = relativePath.hasPrefix("/") ? relativePath : ("/" + relativePath)
super.init(url: href, name: name, path: path)
self.size = Int64(davResponse.prop["getcontentlength"] ?? "-1") ?? NSURLSessionTransferSizeUnknown
self.creationDate = davResponse.prop["creationdate"].flatMap { Date(rfcString: $0) }
self.modifiedDate = davResponse.prop["getlastmodified"].flatMap { Date(rfcString: $0) }
self.contentType = davResponse.prop["getcontenttype"].flatMap(ContentMIMEType.init(rawValue:)) ?? .stream
self.isHidden = (Int(davResponse.prop["ishidden"] ?? "0") ?? 0) > 0
self.isReadOnly = (Int(davResponse.prop["isreadonly"] ?? "0") ?? 0) > 0
self.type = (self.contentType == .directory) ? .directory : .regular
self.entryTag = davResponse.prop["getetag"]
}
/// MIME type of the file.
public internal(set) var contentType: ContentMIMEType {
get {
return (allValues[.mimeTypeKey] as? String).flatMap(ContentMIMEType.init(rawValue:)) ?? .stream
}
set {
allValues[.mimeTypeKey] = newValue.rawValue
}
}
/// HTTP E-Tag, can be used to mark changed files.
public internal(set) var entryTag: String? {
get {
return allValues[.entryTagKey] as? String
}
set {
allValues[.entryTagKey] = newValue
}
}
internal class func resourceKeyToDAVProp(_ key: URLResourceKey) -> String? {
switch key {
case URLResourceKey.fileSizeKey:
return "getcontentlength"
case URLResourceKey.creationDateKey:
return "creationdate"
case URLResourceKey.contentModificationDateKey:
return "getlastmodified"
case URLResourceKey.fileResourceTypeKey, URLResourceKey.mimeTypeKey:
return "getcontenttype"
case URLResourceKey.isHiddenKey:
return "ishidden"
case URLResourceKey.entryTagKey:
return "getetag"
case URLResourceKey.volumeTotalCapacityKey:
// WebDAV doesn't have total capacity, but it's can be calculated via used capacity
return "quota-used-bytes"
case URLResourceKey.volumeAvailableCapacityKey:
return "quota-available-bytes"
default:
return nil
}
}
internal class func propString(_ keys: [URLResourceKey]) -> String {
var propKeys = ""
for item in keys {
if let prop = WebDavFileObject.resourceKeyToDAVProp(item) {
propKeys += "<D:prop><D:\(prop)/></D:prop>"
}
}
if propKeys.isEmpty {
propKeys = "<D:allprop/>"
} else {
propKeys += "<D:prop><D:resourcetype/></D:prop>"
}
return propKeys
}
internal class func xmlProp(_ keys: [URLResourceKey]) -> Data {
return "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\n<D:propfind xmlns:D=\"DAV:\">\n\(WebDavFileObject.propString(keys))\n</D:propfind>".data(using: .utf8)!
}
}
/// Error returned by WebDAV server when trying to access or do operations on a file or folder.
public struct FileProviderWebDavError: FileProviderHTTPError {
public let code: FileProviderHTTPErrorCode
public let path: String
public let serverDescription: String?
/// URL of resource caused error.
public let url: URL
}
| mit | 542ae94d8f52fafcecc79829e0460555 | 46.454685 | 242 | 0.631017 | 4.760826 | false | false | false | false |
OneBusAway/onebusaway-iphone | Carthage/Checkouts/IGListKit/Examples/Examples-iOS/IGListKitExamples/ViewControllers/DemosViewController.swift | 2 | 3859 | /**
Copyright (c) Facebook, Inc. and its affiliates.
The examples provided by Facebook are for non-commercial testing and evaluation
purposes only. Facebook reserves all rights not expressly granted.
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
FACEBOOK 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 IGListKit
import UIKit
final class DemosViewController: UIViewController, ListAdapterDataSource {
lazy var adapter: ListAdapter = {
return ListAdapter(updater: ListAdapterUpdater(), viewController: self)
}()
let collectionView = UICollectionView(frame: .zero, collectionViewLayout: UICollectionViewFlowLayout())
let demos: [DemoItem] = [
DemoItem(name: "Tail Loading",
controllerClass: LoadMoreViewController.self),
DemoItem(name: "Search Autocomplete",
controllerClass: SearchViewController.self),
DemoItem(name: "Mixed Data",
controllerClass: MixedDataViewController.self),
DemoItem(name: "Nested Adapter",
controllerClass: NestedAdapterViewController.self),
DemoItem(name: "Empty View",
controllerClass: EmptyViewController.self),
DemoItem(name: "Single Section Controller",
controllerClass: SingleSectionViewController.self),
DemoItem(name: "Storyboard",
controllerClass: SingleSectionViewController.self,
controllerIdentifier: "demo"),
DemoItem(name: "Single Section Storyboard",
controllerClass: SingleSectionStoryboardViewController.self,
controllerIdentifier: "singleSectionDemo"),
DemoItem(name: "Working Range",
controllerClass: WorkingRangeViewController.self),
DemoItem(name: "Diff Algorithm",
controllerClass: DiffTableViewController.self),
DemoItem(name: "Supplementary Views",
controllerClass: SupplementaryViewController.self),
DemoItem(name: "Self-sizing cells",
controllerClass: SelfSizingCellsViewController.self),
DemoItem(name: "Display delegate",
controllerClass: DisplayViewController.self),
DemoItem(name: "Objc Demo",
controllerClass: ObjcDemoViewController.self),
DemoItem(name: "Objc Generated Model Demo",
controllerClass: ObjcGeneratedModelDemoViewController.self),
DemoItem(name: "Calendar (auto diffing)",
controllerClass: CalendarViewController.self),
DemoItem(name: "Dependency Injection",
controllerClass: AnnouncingDepsViewController.self),
DemoItem(name: "Reorder Cells",
controllerClass: ReorderableViewController.self)
]
override func viewDidLoad() {
super.viewDidLoad()
title = "Demos"
view.addSubview(collectionView)
adapter.collectionView = collectionView
adapter.dataSource = self
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
collectionView.frame = view.bounds
}
// MARK: ListAdapterDataSource
func objects(for listAdapter: ListAdapter) -> [ListDiffable] {
return demos
}
func listAdapter(_ listAdapter: ListAdapter, sectionControllerFor object: Any) -> ListSectionController {
return DemoSectionController()
}
func emptyView(for listAdapter: ListAdapter) -> UIView? {
return nil
}
}
| apache-2.0 | 6e9b2517bbe2cd3256e3b08653f492aa | 40.494624 | 109 | 0.677637 | 5.609012 | false | false | false | false |
sgr-ksmt/PullToDismiss | Sources/UIView+EdgeShadow.swift | 1 | 1068 | //
// UIView+EdgeShadow.swift
// PullToDismiss
//
// Created by Suguru Kishimoto on 1/6/17.
// Copyright © 2017 Suguru Kishimoto. All rights reserved.
//
import Foundation
import UIKit
extension UIView {
func applyEdgeShadow(_ shadow: EdgeShadow?) {
guard let shadow = shadow else {
detachEdgeShadow()
return
}
layer.shadowOpacity = shadow.opacity
layer.shadowRadius = shadow.radius
layer.shadowOffset = shadow.offset
layer.shadowColor = shadow.color.cgColor
// layer.shadowPath = UIBezierPath(rect: self.bounds).cgPath
}
func updateEdgeShadow(_ shadow: EdgeShadow?, rate: CGFloat) {
guard let shadow = shadow else {
detachEdgeShadow()
return
}
layer.shadowOpacity = shadow.opacity * Float(rate)
}
func detachEdgeShadow() {
layer.shadowOpacity = 0.0
layer.shadowRadius = 0
layer.shadowOffset = .zero
layer.shadowColor = nil
layer.shadowPath = nil
}
}
| mit | 617c55ae06e89d70720f74974be6bd5c | 25.02439 | 67 | 0.610122 | 4.742222 | false | false | false | false |
WSDOT/wsdot-ios-app | wsdot/AmtrakCascadesScheduleViewController.swift | 1 | 8376 | //
// AmtrakCascadesScheduleViewController.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 CoreLocation
class AmtrakCascadesScheduleViewController: UITableViewController, CLLocationManagerDelegate {
let locationManager = CLLocationManager()
let segueAmtrakCascadesScheduleDetailsViewController = "AmtrakCascadesScheduleDetailsViewController"
let segueAmtrakCascadesSelectionViewController = "AmtrakCascadesSelectionViewController"
let stationItems = AmtrakCascadesStore.getStations()
var usersLocation: CLLocation? = nil
@IBOutlet weak var dayCell: SelectionCell!
@IBOutlet weak var originCell: SelectionCell!
@IBOutlet weak var destinationCell: SelectionCell!
@IBOutlet weak var submitCell: UITableViewCell!
@IBOutlet weak var submitLabel: UILabel!
var originTableData = AmtrakCascadesStore.getOriginData()
var destinationTableData = AmtrakCascadesStore.getDestinationData()
var dayTableData = TimeUtils.nextSevenDaysStrings(Date())
var dayIndex = 0
var originIndex = 0
var destinationIndex = 0
var selectionType = 0 // Used to determine how to populate the AmtrakCascadesSelectionViewController
override func viewDidLoad() {
super.viewDidLoad()
title = "Find Schedules"
submitLabel.textColor = ThemeManager.currentTheme().darkColor
dayCell.selection.text = dayTableData[0]
originCell.selection.text = originTableData[0]
destinationCell.selection.text = destinationTableData[0]
locationManager.delegate = self
locationManager.requestWhenInUseAuthorization()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
MyAnalytics.screenView(screenName: "AmtrakSchedules")
}
// The following 3 methods are called by the AmtrakCascadesSelectionViewContorller to set the selected option.
func daySelected(_ index: Int){
dayIndex = index
dayCell.selection.text = dayTableData[dayIndex]
}
func originSelected(_ index: Int){
originIndex = index
originCell.selection.text = originTableData[originIndex]
}
func destinationSelected(_ index: Int){
destinationIndex = index
destinationCell.selection.text = destinationTableData[destinationIndex]
}
// MARK: Table View Delegate Methods
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
switch indexPath.section {
case 1:
if AmtrakCascadesStore.stationIdsMap[originTableData[originIndex]]! == AmtrakCascadesStore.stationIdsMap[destinationTableData[destinationIndex]]! {
let alert = UIAlertController(title: "Select a different station", message: "Select different origin and destination stations.", preferredStyle: UIAlertController.Style.alert)
alert.addAction(UIAlertAction(title: "OK", style: UIAlertAction.Style.default, handler: nil))
self.present(alert, animated: true, completion: nil)
}
performSegue(withIdentifier: segueAmtrakCascadesScheduleDetailsViewController, sender: self)
tableView.deselectRow(at: indexPath, animated: true)
break
default:
selectionType = indexPath.row
performSegue(withIdentifier: segueAmtrakCascadesSelectionViewController, sender: self)
tableView.deselectRow(at: indexPath, animated: true)
}
}
// MARK: CLLocationManagerDelegate methods
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
usersLocation = manager.location
let userLat: Double = usersLocation!.coordinate.latitude
let userLon: Double = usersLocation!.coordinate.longitude
var closest = (station: AmtrakCascadesStationItem(id: "", name: "", lat: 0.0, lon: 0.0), distance: Int.max)
for station in stationItems {
let distance = LatLonUtils.haversine(userLat, lonA: userLon, latB: station.lat, lonB: station.lon)
if closest.1 > distance{
closest.station = station
closest.distance = distance
}
}
let index = originTableData.firstIndex(of: closest.station.name)
originCell.selection.text = originTableData[index!]
originIndex = index!
manager.stopUpdatingLocation()
}
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
//print("failed to get location")
}
func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
if status == .authorizedWhenInUse {
manager.startUpdatingLocation()
}
}
// MARK: Naviagtion
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == segueAmtrakCascadesSelectionViewController {
let destinationViewController = segue.destination as! AmtrakCascadesSelectionViewController
destinationViewController.my_parent = self
destinationViewController.selectionType = selectionType
switch (selectionType){
case 0: // day selection
destinationViewController.titleText = "Departure Day"
destinationViewController.menu_options = dayTableData
destinationViewController.selectedIndex = dayTableData.firstIndex(of: dayCell.selection.text!)!
break
case 1: // Origin selection
destinationViewController.titleText = "Origin"
destinationViewController.menu_options = originTableData
destinationViewController.selectedIndex = originTableData.firstIndex(of: originCell.selection.text!)!
break
case 2: // Destination selection
destinationViewController.titleText = "Destination"
destinationViewController.menu_options = destinationTableData
destinationViewController.selectedIndex = destinationTableData.firstIndex(of: destinationCell.selection.text!)!
break
default: break
}
}
if segue.identifier == segueAmtrakCascadesScheduleDetailsViewController {
let destinationViewController = segue.destination as! AmtrakCascadesScheduleDetailsViewController
let interval = TimeInterval(60 * 60 * 24 * dayIndex)
destinationViewController.date = Date().addingTimeInterval(interval)
destinationViewController.originId = AmtrakCascadesStore.stationIdsMap[originTableData[originIndex]]!
destinationViewController.destId = AmtrakCascadesStore.stationIdsMap[destinationTableData[destinationIndex]]!
if destinationViewController.destId == "N/A" {
destinationViewController.title = "Departing " + originTableData[originTableData.firstIndex(of: originCell.selection.text!)!]
} else {
destinationViewController.title = originTableData[originIndex] + " to " + destinationTableData[destinationIndex]
}
}
}
// MARK: Presentation
func adaptivePresentationStyleForPresentationController(_ controller: UIPresentationController) -> UIModalPresentationStyle {
return UIModalPresentationStyle.none
}
}
| gpl-3.0 | 9134915dd7379a2ab9e1386d9332b980 | 41.090452 | 191 | 0.681113 | 5.449577 | false | false | false | false |
svenbacia/TraktKit | TraktKit/Sources/Model/WatchedProgress.swift | 1 | 1341 | //
// WatchedProgress.swift
// TraktKit
//
// Created by Sven Bacia on 01.12.17.
// Copyright © 2017 Sven Bacia. All rights reserved.
//
import Foundation
public struct WatchedProgress: Codable {
// MARK: - Types
public struct Season: Codable {
public let number: Int
public let aired: Int
public let completed: Int
public let episodes: [Episode]
}
public struct Episode: Codable {
private enum CodingKeys: String, CodingKey {
case number
case isCompleted = "completed"
case lastWatchedAt = "last_watched_at"
}
public let number: Int
public let isCompleted: Bool
public let lastWatchedAt: Date?
}
// MARK: - Codable
private enum CodingKeys: String, CodingKey {
case aired
case completed
case lastWatchedAt = "last_watched_at"
case seasons
case hiddenSeasons = "hidden_seasons"
case nextEpisode = "next_episode"
case lastEpisode = "last_episode"
}
// MARK: - Properties
public let aired: Int
public let completed: Int
public let lastWatchedAt: Date?
public let seasons: [Season]
public let hiddenSeasons: [Season]
public let nextEpisode: TraktKit.Episode?
public let lastEpisode: TraktKit.Episode?
}
| mit | 88b1606bf69d93d7873f45d1acde6937 | 23.814815 | 53 | 0.627612 | 4.496644 | false | false | false | false |
PerfectServers/APIDocumentationServer | Sources/APIDocumentationServer/Handlers/user/userList.swift | 1 | 984 | //
// userlist.swift
// ServerMonitor
//
// Created by Jonathan Guthrie on 2017-04-30.
//
//
import SwiftMoment
import PerfectHTTP
import PerfectLogger
import LocalAuthentication
extension WebHandlers {
static func userList(data: [String:Any]) throws -> RequestHandler {
return {
request, response in
let contextAccountID = request.session?.userid ?? ""
let contextAuthenticated = !(request.session?.userid ?? "").isEmpty
if !contextAuthenticated { response.redirect(path: "/login") }
let users = Account.listUsers()
var context: [String : Any] = [
"accountID": contextAccountID,
"authenticated": contextAuthenticated,
"userlist?":"true",
"users": users
]
if contextAuthenticated {
for i in WebHandlers.extras(request) {
context[i.0] = i.1
}
}
// add app config vars
for i in WebHandlers.appExtras(request) {
context[i.0] = i.1
}
response.render(template: "views/users", context: context)
}
}
}
| apache-2.0 | 14a05fc09c82ff32cf4b7cd44ad0d3b3 | 20.391304 | 70 | 0.670732 | 3.501779 | false | false | false | false |
HackingGate/PDF-Reader | PDFReader/PopoverTableViewController.swift | 1 | 8834 | //
// PopoverTableViewController.swift
// PDFReader
//
// Created by ERU on 2017/11/20.
// Copyright © 2017年 Hacking Gate. All rights reserved.
//
import UIKit
import PDFKit
class PopoverTableViewController: UITableViewController {
var delegate: SettingsDelegate!
// var pdfDocument: PDFDocument?
// var displayBox: PDFDisplayBox = .cropBox
@IBOutlet weak var brightnessSlider: UISlider!
@IBOutlet weak var whiteStyleButton: UIButton!
@IBOutlet weak var lightStyleButton: UIButton!
@IBOutlet weak var darkStyleButton: UIButton!
@IBOutlet weak var scrollVerticalButton: UIButton!
@IBOutlet weak var scrollHorizontalButton: UIButton!
@IBOutlet weak var scrollDetailLabel: UILabel!
@IBOutlet weak var twoUpSwitch: UISwitch!
@IBOutlet weak var twoUpDetailLabel: UILabel!
@IBOutlet weak var rightToLeftSwitch: UISwitch!
@IBOutlet weak var findOnPageSwitch: UISwitch!
override func viewWillAppear(_ animated: Bool) {
updateInterface()
super.viewWillAppear(animated)
}
override func viewDidLoad() {
super.viewDidLoad()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem
popoverPresentationController?.backgroundColor = tableView.backgroundColor
let center = NotificationCenter.default
center.addObserver(self,
selector: #selector(updateInterface),
name: UIApplication.willEnterForegroundNotification,
object: nil)
center.addObserver(self,
selector: #selector(updateBrightness),
name: UIScreen.brightnessDidChangeNotification,
object: nil)
center.addObserver(self,
selector: #selector(didChangeOrientationHandler),
name: UIApplication.didChangeStatusBarOrientationNotification,
object: nil)
}
// MARK: Update Interfaces
@objc func updateInterface() {
// use same UI style as DocumentBrowserViewController
whiteStyleButton.tintColor = .clear
lightStyleButton.tintColor = .clear
darkStyleButton.tintColor = .clear
presentingViewController?.view.tintColor = presentingViewController?.presentingViewController?.view.tintColor
view.tintColor = presentingViewController?.view.tintColor
presentedViewController?.view.tintColor = presentingViewController?.view.tintColor
let styleRawValue = UserDefaults.standard.integer(forKey: DocumentBrowserViewController.browserUserInterfaceStyleKey)
if styleRawValue == UIDocumentBrowserViewController.BrowserUserInterfaceStyle.white.rawValue {
// popoverPresentationController?.backgroundColor = .white
whiteStyleButton.tintColor = view.tintColor
} else if styleRawValue == UIDocumentBrowserViewController.BrowserUserInterfaceStyle.light.rawValue {
// popoverPresentationController?.backgroundColor = .white
lightStyleButton.tintColor = view.tintColor
} else if styleRawValue == UIDocumentBrowserViewController.BrowserUserInterfaceStyle.dark.rawValue {
// popoverPresentationController?.backgroundColor = .darkGray
darkStyleButton.tintColor = view.tintColor
}
// tableView.backgroundColor = popoverPresentationController?.backgroundColor
updateBrightness()
updateTwoUp()
updateRightToLeft()
updateScrollDirection()
updateFindOnPage()
}
@objc func updateBrightness() {
brightnessSlider.value = Float(UIScreen.main.brightness)
}
func updateScrollDirection() {
if delegate.isHorizontalScroll {
scrollVerticalButton.tintColor = .lightGray
scrollHorizontalButton.tintColor = view.tintColor
scrollDetailLabel.text = NSLocalizedString("Horizontal", comment: "")
} else {
scrollHorizontalButton.tintColor = .lightGray
scrollVerticalButton.tintColor = view.tintColor
scrollDetailLabel.text = NSLocalizedString("Vertical", comment: "")
}
scrollHorizontalButton.isEnabled = delegate.displayMode == .singlePageContinuous
if rightToLeftSwitch.isOn {
scrollHorizontalButton.setImage(#imageLiteral(resourceName: "direction_left"), for: .normal)
if !delegate.allowsDocumentAssembly && delegate.displayMode == .singlePageContinuous {
scrollHorizontalButton.setImage(#imageLiteral(resourceName: "direction_right"), for: .normal)
}
} else {
scrollHorizontalButton.setImage(#imageLiteral(resourceName: "direction_right"), for: .normal)
}
}
func updateTwoUp() {
twoUpSwitch.isOn = delegate.prefersTwoUpInLandscapeForPad
twoUpDetailLabel.text = twoUpSwitch.isOn ? NSLocalizedString("Two pages in landscape", comment: "") : NSLocalizedString("Single page in landscape", comment: "")
}
func updateRightToLeft() {
rightToLeftSwitch.isOn = delegate.isRightToLeft
if delegate.displayMode == .singlePageContinuous {
rightToLeftSwitch.isEnabled = delegate.allowsDocumentAssembly
} else if delegate.displayMode == .twoUpContinuous {
rightToLeftSwitch.isEnabled = true
}
}
func updateFindOnPage() {
findOnPageSwitch.isOn = delegate.isFindOnPageEnabled
}
// MARK: Actions
@IBAction func sliderValueChanged(_ sender: UISlider) {
UIScreen.main.brightness = CGFloat(sender.value)
}
@IBAction func styleButtonAction(_ sender: UIButton) {
whiteStyleButton.tintColor = .clear
lightStyleButton.tintColor = .clear
darkStyleButton.tintColor = .clear
sender.tintColor = view.tintColor
switch sender.tag {
case 1:
UserDefaults.standard.set(0, forKey: (DocumentBrowserViewController.browserUserInterfaceStyleKey))
case 2:
UserDefaults.standard.set(1, forKey: (DocumentBrowserViewController.browserUserInterfaceStyleKey))
case 3:
UserDefaults.standard.set(2, forKey: (DocumentBrowserViewController.browserUserInterfaceStyleKey))
default: break
}
let center = NotificationCenter.default
center.post(name: UIApplication.willEnterForegroundNotification, object: nil)
}
@IBAction func directionButtonAction(_ sender: UIButton) {
scrollVerticalButton.tintColor = .lightGray
scrollHorizontalButton.tintColor = .lightGray
sender.tintColor = view.tintColor
switch sender.tag {
case 1:
delegate.isHorizontalScroll = false
if delegate.displayMode == .singlePageContinuous {
delegate.isRightToLeft = false
}
case 2:
delegate.isHorizontalScroll = true
default: break
}
delegate.updateScrollDirection()
updateRightToLeft()
updateScrollDirection()
}
@IBAction func twoUpSwitchValueChanged(_ sender: UISwitch) {
delegate.setPreferredDisplayMode(sender.isOn)
delegate.updateScrollDirection()
twoUpDetailLabel.text = twoUpSwitch.isOn ? NSLocalizedString("Two pages in landscape", comment: "") : NSLocalizedString("Single page in landscape", comment: "")
updateRightToLeft()
updateScrollDirection()
}
@IBAction func rightToLeftSwitchValueChanged(_ sender: UISwitch) {
delegate.isRightToLeft = sender.isOn
delegate.updateScrollDirection()
updateScrollDirection()
}
@IBAction func findOnPageSwitchValueChanged(_ sender: UISwitch) {
delegate.isFindOnPageEnabled = sender.isOn
}
@objc func didChangeOrientationHandler() {
updateRightToLeft()
updateScrollDirection()
}
// MARK: - UITableViewDelegate
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
if !delegate.isEncrypted && indexPath.row == 3 {
return 0
}
if indexPath.row == 4 {
// temporary disable Find on Page
return 0
}
if UIDevice.current.userInterfaceIdiom != .pad && indexPath.row == 5 {
return 0
}
return super.tableView(tableView, heightForRowAt: indexPath)
}
}
| mit | 5206b72ef1df9e28e42f6350aedc7131 | 39.509174 | 168 | 0.667308 | 5.738142 | false | false | false | false |
luisdelarosa/ImpLight | ImpLight/AFNetworkingClient.swift | 1 | 1350 | //
// AFNetworkingClient.swift
// ImpLight
//
// Created by de la Rosa, Luis on 8/22/14.
//
//
import UIKit
class AFNetworkingClient: NSObject {
// Set this to your agent ID
let agentId = "qnEfEUX85B7J"
// This is how long to let the LED be lit up
let ledTimeout = 10
// variables
var httpRequestOperationManager: AFHTTPRequestOperationManager
// initializer
override init() {
httpRequestOperationManager = AFHTTPRequestOperationManager()
// Electric Imp agent returns text/plain
httpRequestOperationManager.responseSerializer = AFTextResponseSerializer()
}
// Issue an HTTP GET to the Electric Imp agent
func sendHttpRequestToElectricImp(#color: String) {
// translate to RGB hex value
let url = "https://agent.electricimp.com/\(agentId)?led=0&rgb=%23\(color)&timer=\(ledTimeout)&user="
println("url:\(url)")
httpRequestOperationManager.GET(
url,
parameters: nil,
success: { (operation: AFHTTPRequestOperation!, responseObject: AnyObject!) in
println("Success: " + responseObject.description)
},
failure: { (operation: AFHTTPRequestOperation!, error: NSError!) in
println("Error: " + error.localizedDescription)
})
}
}
| mit | 005f566fdbc018e672d65947d6fa0c07 | 29 | 108 | 0.634815 | 4.6875 | false | false | false | false |
mssun/passforios | pass/Controllers/QRScannerController.swift | 1 | 5781 | //
// QRScannerController.swift
// pass
//
// Created by Yishi Lin on 7/4/17.
// Copyright © 2017 Yishi Lin. All rights reserved.
//
import AVFoundation
import OneTimePassword
import passKit
import SVProgressHUD
import UIKit
protocol QRScannerControllerDelegate: AnyObject {
func checkScannedOutput(line: String) -> (accepted: Bool, message: String)
func handleScannedOutput(line: String)
}
class QRScannerController: UIViewController, AVCaptureMetadataOutputObjectsDelegate {
@IBOutlet var scannerOutput: UILabel!
var captureSession: AVCaptureSession?
var videoPreviewLayer: AVCaptureVideoPreviewLayer?
var qrCodeFrameView: UIView?
let supportedCodeTypes = [AVMetadataObject.ObjectType.qr]
weak var delegate: QRScannerControllerDelegate?
override func viewDidLoad() {
super.viewDidLoad()
if AVCaptureDevice.authorizationStatus(for: .video) == .denied {
presentCameraSettings()
}
// Get an instance of the AVCaptureDevice class to initialize a device object and provide the video as the media type parameter.
guard let captureDevice = AVCaptureDevice.default(for: .video) else {
scannerOutput.text = "CameraAccessDenied.".localize()
return
}
do {
// Get an instance of the AVCaptureDeviceInput class using the previous device object.
let input = try AVCaptureDeviceInput(device: captureDevice)
// Initialize the captureSession object.
captureSession = AVCaptureSession()
// Set the input device on the capture session.
captureSession?.addInput(input)
// Initialize a AVCaptureMetadataOutput object and set it as the output device to the capture session.
let captureMetadataOutput = AVCaptureMetadataOutput()
captureSession?.addOutput(captureMetadataOutput)
// Set delegate and use the default dispatch queue to execute the call back
captureMetadataOutput.setMetadataObjectsDelegate(self, queue: DispatchQueue.main)
captureMetadataOutput.metadataObjectTypes = supportedCodeTypes
// Initialize the video preview layer and add it as a sublayer to the viewPreview view's layer.
videoPreviewLayer = AVCaptureVideoPreviewLayer(session: captureSession!)
videoPreviewLayer?.videoGravity = AVLayerVideoGravity.resizeAspectFill
videoPreviewLayer?.frame = view.layer.bounds
view.layer.addSublayer(videoPreviewLayer!)
// Start video capture.
captureSession?.startRunning()
// Move the message label to the front
scannerOutput.layer.cornerRadius = 10
scannerOutput.text = "NoQrCodeDetected.".localize()
view.bringSubviewToFront(scannerOutput)
// Initialize QR Code Frame to highlight the QR code
qrCodeFrameView = UIView()
if let qrCodeFrameView = qrCodeFrameView {
qrCodeFrameView.layer.borderColor = UIColor.green.cgColor
qrCodeFrameView.layer.borderWidth = 2
view.addSubview(qrCodeFrameView)
view.bringSubviewToFront(qrCodeFrameView)
}
} catch {
scannerOutput.text = error.localizedDescription
}
}
// MARK: - AVCaptureMetadataOutputObjectsDelegate Methods
func metadataOutput(_: AVCaptureMetadataOutput, didOutput metadataObjects: [AVMetadataObject], from _: AVCaptureConnection) {
guard let metadataObj = metadataObjects.first as? AVMetadataMachineReadableCodeObject else {
setNotDetected()
return
}
guard supportedCodeTypes.contains(metadataObj.type) else {
setNotDetected()
return
}
guard let barCodeObject = videoPreviewLayer?.transformedMetadataObject(for: metadataObj) else {
setNotDetected()
return
}
// draw a bounds on the found QR code
qrCodeFrameView?.frame = barCodeObject.bounds
// check whether it is a valid result
guard let scanned = metadataObj.stringValue else {
scannerOutput.text = "NoStringValue".localize()
return
}
guard let (accepted, message) = delegate?.checkScannedOutput(line: scanned) else {
// no delegate, show the scanned result
scannerOutput.text = scanned
return
}
scannerOutput.text = message
guard accepted else {
return
}
captureSession?.stopRunning()
delegate?.handleScannedOutput(line: scanned)
DispatchQueue.main.async {
SVProgressHUD.showSuccess(withStatus: "Done".localize())
SVProgressHUD.dismiss(withDelay: 1)
self.navigationController?.popViewController(animated: true)
}
}
private func setNotDetected() {
qrCodeFrameView?.frame = CGRect.zero
scannerOutput.text = "NoQrCodeDetected.".localize()
}
private func presentCameraSettings() {
let alertController = UIAlertController(
title: "Error".localize(),
message: "CameraAccessDenied.".localize() | "WarningToggleCameraPermissionsResetsApp.".localize(),
preferredStyle: .alert
)
alertController.addAction(UIAlertAction(title: "Cancel".localize(), style: .default))
alertController.addAction(UIAlertAction(title: "Settings".localize(), style: .cancel) { _ in
if let url = URL(string: UIApplication.openSettingsURLString) {
UIApplication.shared.open(url)
}
}
)
present(alertController, animated: true)
}
}
| mit | 0f459461fbc77b2fffd5462683c4b763 | 37.278146 | 136 | 0.65917 | 5.791583 | false | false | false | false |
dzahariev/samples-ios | MasterDetail/MasterDetail/DetailViewController.swift | 1 | 2544 | //
// DetailViewController.swift
// MasterDetail
//
// Created by Zahariev, Dobromir on 6/23/14.
// Copyright (c) 2014 dzahariev. All rights reserved.
//
import UIKit
class DetailViewController: UIViewController, UISplitViewControllerDelegate {
@IBOutlet var detailDescriptionLabel: UILabel
var masterPopoverController: UIPopoverController? = nil
var detailItem: AnyObject? {
didSet {
// Update the view.
self.configureView()
if self.masterPopoverController != nil {
self.masterPopoverController!.dismissPopoverAnimated(true)
}
}
}
func configureView() {
// Update the user interface for the detail item.
if let detail: AnyObject = self.detailItem {
if let label = self.detailDescriptionLabel {
label.text = detail.description
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.configureView()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// #pragma mark - Split view
func splitViewController(splitController: UISplitViewController, willHideViewController viewController: UIViewController, withBarButtonItem barButtonItem: UIBarButtonItem, forPopoverController popoverController: UIPopoverController) {
barButtonItem.title = "Master" // NSLocalizedString(@"Master", @"Master")
self.navigationItem.setLeftBarButtonItem(barButtonItem, animated: true)
self.masterPopoverController = popoverController
}
func splitViewController(splitController: UISplitViewController, willShowViewController viewController: UIViewController, invalidatingBarButtonItem barButtonItem: UIBarButtonItem) {
// Called when the view is shown again in the split view, invalidating the button and popover controller.
self.navigationItem.setLeftBarButtonItem(nil, animated: true)
self.masterPopoverController = nil
}
func splitViewController(splitController: UISplitViewController, collapseSecondaryViewController secondaryViewController: UIViewController, ontoPrimaryViewController primaryViewController: UIViewController) -> Bool {
// Return true to indicate that we have handled the collapse by doing nothing; the secondary controller will be discarded.
return true
}
}
| apache-2.0 | ba38949ec730861fb8d63725613e2f46 | 36.970149 | 238 | 0.712264 | 6.042755 | false | false | false | false |
LYM-mg/MGDYZB | MGDYZB简单封装版/MGDYZB/Class/Home/View/ScanBottomView.swift | 1 | 2536 | //
// ScanBottomView.swift
// MGDYZB
//
// Created by i-Techsys.com on 17/4/11.
// Copyright © 2017年 ming. All rights reserved.
//
import UIKit
enum MGButtonType: Int {
case photo, flash, myqrcode
}
class ScanBottomView: UIView {
fileprivate lazy var myButtons: [UIButton] = [UIButton]()
var btnClickBlcok: ((_ view: ScanBottomView, _ type: MGButtonType)->())?
override init(frame: CGRect) {
super.init(frame: frame)
setUpUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
// MARK: - 设置UI
extension ScanBottomView {
func setUpUI() {
// 设置UI
setUpBtn(image: UIImage(named: "MGCodeScan.bundle/qrcode_scan_btn_flash_nor.png")!, highlightedImage: UIImage(named: "MGCodeScan.bundle/qrcode_scan_btn_flash_down.png")!, title: "",type: .flash)
setUpBtn(image: UIImage(named: "MGCodeScan.bundle/qrcode_scan_btn_photo_nor.png")!, highlightedImage: UIImage(named: "MGCodeScan.bundle/qrcode_scan_btn_photo_down.png")!, title: "",type: .photo)
setUpBtn(image: UIImage(named: "MGCodeScan.bundle/qrcode_scan_btn_myqrcode_nor.png")!, highlightedImage: UIImage(named: "MGCodeScan.bundle/qrcode_scan_btn_myqrcode_down.png")!, title: "",type: .myqrcode)
// 布局UI
let margin: CGFloat = 10
let count: CGFloat = CGFloat(myButtons.count)
let width = (self.frame.width - margin*CGFloat(count+1))/count
let height = self.frame.height - margin*2.5
let y = margin
for (i,btn) in myButtons.enumerated() {
let x = CGFloat(i)*width + margin
btn.frame = CGRect(x: x, y: y, width: width, height: height)
}
}
func setUpBtn(image: UIImage,highlightedImage: UIImage,title: String,type: MGButtonType) {
let btn = ScanButton(image: image, highlightedImage: highlightedImage,title: title, target: self, action: #selector(self.btnClick(btn:)))
btn.tag = type.rawValue
self.addSubview(btn)
myButtons.append(btn)
}
@objc func btnClick(btn: UIButton) {
switch btn.tag {
case 0:
btn.isSelected = !btn.isSelected
case 1:
btn.isSelected = !btn.isSelected
case 2:
btn.isSelected = !btn.isSelected
default: break
}
if self.btnClickBlcok != nil {
btnClickBlcok!(self,MGButtonType(rawValue: btn.tag)!)
}
}
}
| mit | ba48b215050e0ebf5e9181b804376f94 | 34.507042 | 211 | 0.617612 | 3.837139 | false | false | false | false |
marklin2012/JDUtil | JDUtilDemo/JDUtilDemo/JDUtil/JDBorder.swift | 3 | 11959 | //
// JDBorder.swift
// JDUtilDemo
//
// Created by O2.LinYi on 15/12/24.
// Copyright © 2015年 jd.com. All rights reserved.
//
import Foundation
import UIKit
import QuartzCore
public extension UIView {
//////////
// Top
//////////
public func createTopBorderWithHeight(height: CGFloat, color: UIColor) -> CALayer {
return getOneSidedBorderWithFrame(CGRectMake(0, 0, self.frame.size.width, height), color:color)
}
public func createViewBackedTopBorderWithHeight(height: CGFloat, color:UIColor) -> UIView {
return getViewBackedOneSidedBorderWithFrame(CGRectMake(0, 0, self.frame.size.width, height), color:color)
}
public func addTopBorderWithHeight(height: CGFloat, color:UIColor) {
addOneSidedBorderWithFrame(CGRectMake(0, 0, self.frame.size.width, height), color:color)
}
public func addViewBackedTopBorderWithHeight(height: CGFloat, color:UIColor) {
addViewBackedOneSidedBorderWithFrame(CGRectMake(0, 0, self.frame.size.width, height), color:color)
}
//////////
// Top + Offset
//////////
public func createTopBorderWithHeight(height:CGFloat, color:UIColor, leftOffset:CGFloat, rightOffset:CGFloat, topOffset:CGFloat) -> CALayer {
// Subtract the bottomOffset from the height and the thickness to get our final y position.
// Add a left offset to our x to get our x position.
// Minus our rightOffset and negate the leftOffset from the width to get our endpoint for the border.
return getOneSidedBorderWithFrame(CGRectMake(0 + leftOffset, 0 + topOffset, self.frame.size.width - leftOffset - rightOffset, height), color:color)
}
public func createViewBackedTopBorderWithHeight(height:CGFloat, color:UIColor, leftOffset:CGFloat, rightOffset:CGFloat, topOffset:CGFloat) -> UIView {
return getViewBackedOneSidedBorderWithFrame(CGRectMake(0 + leftOffset, 0 + topOffset, self.frame.size.width - leftOffset - rightOffset, height), color:color)
}
public func addTopBorderWithHeight(height:CGFloat, color:UIColor, leftOffset:CGFloat, rightOffset:CGFloat, topOffset:CGFloat) {
// Add leftOffset to our X to get start X position.
// Add topOffset to Y to get start Y position
// Subtract left offset from width to negate shifting from leftOffset.
// Subtract rightoffset from width to set end X and Width.
addOneSidedBorderWithFrame(CGRectMake(0 + leftOffset, 0 + topOffset, self.frame.size.width - leftOffset - rightOffset, height), color:color)
}
public func addViewBackedTopBorderWithHeight(height:CGFloat, color:UIColor, leftOffset:CGFloat, rightOffset:CGFloat, topOffset:CGFloat) {
addViewBackedOneSidedBorderWithFrame(CGRectMake(0 + leftOffset, 0 + topOffset, self.frame.size.width - leftOffset - rightOffset, height), color:color)
}
//////////
// Right
//////////
public func createRightBorderWithWidth(width:CGFloat, color:UIColor) -> CALayer {
return getOneSidedBorderWithFrame(CGRectMake(self.frame.size.width-width, 0, width, self.frame.size.height), color:color)
}
public func createViewBackedRightBorderWithWidth(width:CGFloat, color:UIColor) -> UIView {
return getViewBackedOneSidedBorderWithFrame(CGRectMake(self.frame.size.width-width, 0, width, self.frame.size.height), color:color)
}
public func addRightBorderWithWidth(width:CGFloat, color:UIColor){
addOneSidedBorderWithFrame(CGRectMake(self.frame.size.width-width, 0, width, self.frame.size.height), color:color)
}
public func addViewBackedRightBorderWithWidth(width:CGFloat, color:UIColor) {
addViewBackedOneSidedBorderWithFrame(CGRectMake(self.frame.size.width-width, 0, width, self.frame.size.height), color:color)
}
//////////
// Right + Offset
//////////
public func createRightBorderWithWidth(width: CGFloat, color:UIColor, rightOffset:CGFloat, topOffset:CGFloat, bottomOffset:CGFloat) -> CALayer {
// Subtract bottomOffset from the height to get our end.
return getOneSidedBorderWithFrame(CGRectMake(self.frame.size.width-width-rightOffset, 0 + topOffset, width, self.frame.size.height - topOffset - bottomOffset), color:color)
}
public func createViewBackedRightBorderWithWidth(width: CGFloat, color:UIColor, rightOffset:CGFloat, topOffset:CGFloat, bottomOffset:CGFloat) -> UIView {
return getViewBackedOneSidedBorderWithFrame(CGRectMake(self.frame.size.width-width-rightOffset, 0 + topOffset, width, self.frame.size.height - topOffset - bottomOffset), color:color)
}
public func addRightBorderWithWidth(width: CGFloat, color:UIColor, rightOffset:CGFloat, topOffset:CGFloat, bottomOffset:CGFloat) {
// Subtract the rightOffset from our width + thickness to get our final x position.
// Add topOffset to our y to get our start y position.
// Subtract topOffset from our height, so our border doesn't extend past teh view.
// Subtract bottomOffset from the height to get our end.
addOneSidedBorderWithFrame(CGRectMake(self.frame.size.width-width-rightOffset, 0 + topOffset, width, self.frame.size.height - topOffset - bottomOffset), color:color)
}
public func addViewBackedRightBorderWithWidth(width: CGFloat, color:UIColor, rightOffset:CGFloat, topOffset:CGFloat, bottomOffset:CGFloat) {
addViewBackedOneSidedBorderWithFrame(CGRectMake(self.frame.size.width-width-rightOffset, 0 + topOffset, width, self.frame.size.height - topOffset - bottomOffset), color:color)
}
//////////
// Bottom
//////////
public func createBottomBorderWithHeight(height: CGFloat, color:UIColor) -> CALayer {
return getOneSidedBorderWithFrame(CGRectMake(0, self.frame.size.height-height, self.frame.size.width, height), color:color)
}
public func createViewBackedBottomBorderWithHeight(height: CGFloat, color:UIColor) -> UIView {
return getViewBackedOneSidedBorderWithFrame(CGRectMake(0, self.frame.size.height-height, self.frame.size.width, height), color:color)
}
public func addBottomBorderWithHeight(height: CGFloat, color:UIColor) {
return addOneSidedBorderWithFrame(CGRectMake(0, self.frame.size.height-height, self.frame.size.width, height), color:color)
}
public func addViewBackedBottomBorderWithHeight(height: CGFloat, color:UIColor) {
addViewBackedOneSidedBorderWithFrame(CGRectMake(0, self.frame.size.height-height, self.frame.size.width, height), color:color)
}
//////////
// Bottom + Offset
//////////
public func createBottomBorderWithHeight(height: CGFloat, color:UIColor, leftOffset:CGFloat, rightOffset:CGFloat, bottomOffset:CGFloat) -> CALayer {
// Subtract the bottomOffset from the height and the thickness to get our final y position.
// Add a left offset to our x to get our x position.
// Minus our rightOffset and negate the leftOffset from the width to get our endpoint for the border.
return getOneSidedBorderWithFrame(CGRectMake(0 + leftOffset, self.frame.size.height-height-bottomOffset, self.frame.size.width - leftOffset - rightOffset, height), color:color)
}
public func createViewBackedBottomBorderWithHeight(height: CGFloat, color:UIColor, leftOffset:CGFloat, rightOffset:CGFloat, bottomOffset:CGFloat) -> UIView {
return getViewBackedOneSidedBorderWithFrame(CGRectMake(0 + leftOffset, self.frame.size.height-height-bottomOffset, self.frame.size.width - leftOffset - rightOffset, height), color:color)
}
public func addBottomBorderWithHeight(height: CGFloat, color:UIColor, leftOffset:CGFloat, rightOffset:CGFloat, bottomOffset:CGFloat) {
// Subtract the bottomOffset from the height and the thickness to get our final y position.
// Add a left offset to our x to get our x position.
// Minus our rightOffset and negate the leftOffset from the width to get our endpoint for the border.
addOneSidedBorderWithFrame(CGRectMake(0 + leftOffset, self.frame.size.height-height-bottomOffset, self.frame.size.width - leftOffset - rightOffset, height), color:color)
print(self.frame)
}
public func addViewBackedBottomBorderWithHeight(height: CGFloat, color:UIColor, leftOffset:CGFloat, rightOffset:CGFloat, bottomOffset:CGFloat) {
addViewBackedOneSidedBorderWithFrame(CGRectMake(0 + leftOffset, self.frame.size.height-height-bottomOffset, self.frame.size.width - leftOffset - rightOffset, height), color:color)
}
//////////
// Left
//////////
public func createLeftBorderWithWidth(width: CGFloat, color:UIColor) -> CALayer {
return getOneSidedBorderWithFrame(CGRectMake(0, 0, width, self.frame.size.height), color:color)
}
public func createViewBackedLeftBorderWithWidth(width: CGFloat, color:UIColor) -> UIView {
return getViewBackedOneSidedBorderWithFrame(CGRectMake(0, 0, width, self.frame.size.height), color:color)
}
public func addLeftBorderWithWidth(width: CGFloat, color:UIColor) {
addOneSidedBorderWithFrame(CGRectMake(0, 0, width, self.frame.size.height), color:color)
}
public func addViewBackedLeftBorderWithWidth(width: CGFloat, color:UIColor) {
addViewBackedOneSidedBorderWithFrame(CGRectMake(0, 0, width, self.frame.size.height), color:color)
}
/// Left + Offset
public func createLeftBorderWithWidth(width:CGFloat, color:UIColor, leftOffset:CGFloat, topOffset:CGFloat, bottomOffset:CGFloat) -> CALayer {
return getOneSidedBorderWithFrame(CGRectMake(0 + leftOffset, 0 + topOffset, width, self.frame.size.height - topOffset - bottomOffset), color:color)
}
public func createViewBackedLeftBorderWithWidth(width:CGFloat, color:UIColor, leftOffset:CGFloat, topOffset:CGFloat, bottomOffset:CGFloat) -> UIView {
return getViewBackedOneSidedBorderWithFrame(CGRectMake(0 + leftOffset, 0 + topOffset, width, self.frame.size.height - topOffset - bottomOffset), color:color)
}
public func addLeftBorderWithWidth(width:CGFloat, color:UIColor, leftOffset:CGFloat, topOffset:CGFloat, bottomOffset:CGFloat) {
addOneSidedBorderWithFrame(CGRectMake(0 + leftOffset, 0 + topOffset, width, self.frame.size.height - topOffset - bottomOffset), color:color)
}
public func addViewBackedLeftBorderWithWidth(width:CGFloat, color:UIColor, leftOffset:CGFloat, topOffset:CGFloat, bottomOffset:CGFloat) {
addViewBackedOneSidedBorderWithFrame(CGRectMake(0 + leftOffset, 0 + topOffset, width, self.frame.size.height - topOffset - bottomOffset), color:color)
}
/// Private: Our methods call these to add their borders.
private func addOneSidedBorderWithFrame(frame: CGRect, color:UIColor) {
let border = CALayer()
border.frame = frame
border.backgroundColor = color.CGColor
self.layer.addSublayer(border)
}
private func getOneSidedBorderWithFrame(frame: CGRect, color:UIColor) -> CALayer {
let border = CALayer()
border.frame = frame
border.backgroundColor = color.CGColor
return border
}
private func addViewBackedOneSidedBorderWithFrame(frame: CGRect, color: UIColor) {
for subview in self.subviews {
if (subview.tag == 1111) {
subview.removeFromSuperview()
}
}
let border = UIView(frame: frame)
border.backgroundColor = color
border.tag = 1111
self.addSubview(border)
}
private func getViewBackedOneSidedBorderWithFrame(frame: CGRect, color: UIColor) -> UIView {
let border = UIView(frame: frame)
border.backgroundColor = color
return border
}
} | mit | af50e9abec3b61aa39344f39f04176dc | 49.665254 | 194 | 0.711275 | 4.556402 | false | false | false | false |
Rehsco/SnappingStepper | Sources/UIBuilder.swift | 1 | 1609 | /*
* SnappingStepper
*
* Copyright 2015-present Yannick Loriot.
* http://yannickloriot.com
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*/
import UIKit
import StyledLabel
final class UIBuilder {
static func defaultLabel() -> UILabel {
let label = UILabel()
label.textAlignment = .center
label.isUserInteractionEnabled = true
return label
}
static func defaultStyledLabel() -> StyledLabel {
let label = StyledLabel()
label.textAlignment = .center
label.text = ""
return label
}
}
| mit | 0c075ae4e2d9ec186a576d42066fe8c2 | 33.978261 | 80 | 0.717837 | 4.636888 | false | false | false | false |
vegather/MOON-Graph | GraphView.swift | 2 | 65575 | //
// GraphView.swift
// Graph View
//
// Created by Vegard Solheim Theriault on 13/01/2017.
// Copyright © 2017 Vegard Solheim Theriault. All rights reserved.
//
// .___ ___. ______ ______ .__ __.
// | \/ | / __ \ / __ \ | \ | |
// | \ / | | | | | | | | | | \| |
// | |\/| | | | | | | | | | | . ` |
// | | | | | `--' | | `--' | | |\ |
// |__| |__| \______/ \______/ |__| \__|
// ___ _____ _____ _ ___ ___ ___ ___
// | \| __\ \ / / __| | / _ \| _ \ __| _ \
// | |) | _| \ V /| _|| |_| (_) | _/ _|| /
// |___/|___| \_/ |___|____\___/|_| |___|_|_\
//
import MetalKit
import Accelerate
import simd
#if os(iOS)
import UIKit
#elseif os(OSX)
import Cocoa
#endif
// -------------------------------
// MARK: Platform Specific Types
// -------------------------------
#if os(iOS)
public typealias View = UIView
public typealias Color = UIColor
fileprivate typealias Label = UILabel
fileprivate typealias Font = UIFont
fileprivate typealias BezierPath = UIBezierPath
fileprivate typealias Point = CGPoint
fileprivate typealias Rect = CGRect
#elseif os(OSX)
public typealias View = NSView
public typealias Color = NSColor
fileprivate typealias Label = NSTextField
fileprivate typealias Font = NSFont
fileprivate typealias BezierPath = NSBezierPath
fileprivate typealias Point = NSPoint
fileprivate typealias Rect = NSRect
#endif
// -------------------------------
// MARK: Constants
// -------------------------------
fileprivate struct Constants {
static let ValueLabelWidth : CGFloat = 60
static let TopBottomPadding : CGFloat = 16
static let CornerRadius : CGFloat = 10
}
// -------------------------------
// MARK: Data Structures
// -------------------------------
public extension GraphView {
public enum GraphType {
case scatter
/// Line currently only works when using the replace(with: ...)
/// function to set the data.
case line
}
public enum SampleSize {
case small
case large
case custom(size: UInt8)
fileprivate func size() -> UInt8 {
switch self {
case .small: return 2
case .large: return 6
case .custom(let size): return size
}
}
}
}
// -------------------------------
// MARK: Graph View
// -------------------------------
public class GraphView: View {
/// The background color of the graph view. This will be a gradient color,
/// unless `.clear` is selected.
public var backgroundTint = BackgroundTintColor.blue {
didSet {
#if os(iOS)
gradientBackground.gradient.colors = backgroundTint.colors().reversed()
#elseif os(OSX)
gradientBackground.gradient.colors = backgroundTint.colors()
#endif
}
}
/// The color of the samples plotted in the graph. This can either be
/// a `.plain` color, or a `.gradient` one.
public var sampleColor = SampleColor.color(plain: .white) {
didSet {
switch sampleColor {
case .color(let color):
metalGraph.uniforms.topColor = color.vector()
metalGraph.uniforms.bottomColor = color.vector()
case .gradient(let top, let bottom):
metalGraph.uniforms.topColor = top.vector()
metalGraph.uniforms.bottomColor = bottom.vector()
}
#if os(iOS)
metalGraph.setNeedsDisplay()
#elseif os(OSX)
metalGraph.setNeedsDisplay(bounds)
#endif
}
}
/// Whether or not the graph should have rounded corners.
public var roundedCorners = true {
didSet { gradientBackground.gradient.cornerRadius = roundedCorners ? Constants.CornerRadius : 0.0 }
}
/// The title string that appears in the top left of the view
public var title = "" {
didSet {
#if os(iOS)
titleLabel.text = title
#elseif os(OSX)
titleLabel.stringValue = title
#endif
}
}
/// The subtitle string that appears right under the title
public var subtitle = "" {
didSet {
#if os(iOS)
subtitleLabel.text = subtitle
#elseif os(OSX)
subtitleLabel.stringValue = subtitle
#endif
}
}
/// The unit of the samples added to the graph. This appears as a suffix
/// for the value labels on the right hand side.
public var valueUnit = "" {
didSet {
updateMinMaxLabels()
}
}
/// The number of desired decimals displayed for the values. The default is 0.
public var valueUnitDecimals = 0 {
didSet {
updateMinMaxLabels()
}
}
/// The number of samples that fit in the graph view. When more samples than this are
/// added, the oldest samples will slide off the left edge. The default value is 1000.
public var capacity: Int {
get { return Int(_capacity) }
set { _capacity = Float(newValue) }
}
/// How the graph should be plotted. The `.line` option currently does not work propertly
public var graphType = GraphType.scatter {
didSet {
metalGraph.graphType = graphType
#if os(iOS)
metalGraph.setNeedsDisplay()
#elseif os(OSX)
metalGraph.setNeedsDisplay(bounds)
#endif
}
}
/// This is only applicable when `graphType` is set to `.scatter`.
public var sampleSize = SampleSize.small {
didSet {
metalGraph.uniforms.pointSize = sampleSize.size()
#if os(iOS)
metalGraph.setNeedsDisplay()
#elseif os(OSX)
metalGraph.setNeedsDisplay(bounds)
#endif
}
}
/// This property is only available on iOS. It specifies if the user should
/// be able to change the capacity (by pinching horizontally), the minimum
/// and maximum value (by pinching vertically), and moving up and down the
/// y-axis (by swiping). When the user has started interacting, an "Auto-Scale"
/// button will appear. This button is removed again when the user taps it.
#if os(iOS)
public var gesturesEnabled = true {
didSet {
if gesturesEnabled {
addGestureRecognizers()
} else {
removeGestureRecognizers()
}
}
}
#endif
/// Gets or sets the range of values that can be visible within the graph view.
/// If `isAutoscaling` is set to true, this will change by itself. If you want
/// to set this variable yourself, you should probably set `isAutoscaling` to false.
public var visibleRange: ClosedRange<Float> {
get {
return ClosedRange<Float>(uncheckedBounds: (metalGraph.uniforms.minValue, metalGraph.uniforms.maxValue))
}
set {
guard newValue.upperBound > newValue.lowerBound else { return }
metalGraph.uniforms.maxValue = newValue.upperBound
metalGraph.uniforms.minValue = newValue.lowerBound
#if os(iOS)
metalGraph.setNeedsDisplay()
#elseif os(OSX)
metalGraph.setNeedsDisplay(bounds)
#endif
updateMinMaxLabels()
}
}
/// Whether or not the graph should be autoscaling. This will be false if the
/// user is currently using gestures
public var isAutoscaling = true {
didSet {
metalGraph.isAutoscaling = isAutoscaling
#if os(iOS)
if isAutoscaling {
removeAutoScaleButton()
} else {
addAutoScaleButton()
}
#endif
}
}
/// Horizontal lines will be drawn with the y-axis values corresponding
/// to the values in this array.
public var horizontalLines: [Float] = [] {
didSet { drawHorizontalLines() }
}
// -------------------------------
// MARK: Public Methods
// -------------------------------
/// Adds a new sample to the graph. If the number of samples added is the
/// same as the value of `capacity`, the oldest value will be pushed out to
/// the left side of the graph view.
public func add(sample: Float) {
metalGraph.add(sample: sample)
}
/// Replaces all the current samples in the graph. This will also modify
/// `capacity` to the numper of samples in this call. Calling this function
/// is much faster than manually calling `add(...)` for each individual sample.
public func replace(with samples: [Float]) {
guard samples.count > 0 else { return }
_capacity = Float(samples.count)
metalGraph.set(samples: samples)
}
/// Removes every sample from the graph.
public func clear() {
metalGraph.clear()
}
// -------------------------------
// MARK: Private Properties
// -------------------------------
#if os(iOS)
private var pinchRecognizer : UIPinchGestureRecognizer?
private var panRecognizer : UIPanGestureRecognizer?
private var doubleTapRecognizer : UITapGestureRecognizer?
private var previousPinchPosY : CGFloat?
#endif
// This is here so it can be set independently of the user facing capacity
// It's also a Float so that scaling will work properly
private var _capacity: Float = 1000 {
didSet {
// Clamping value to [2, Int32.max]
if _capacity < 2 { _capacity = 2 }
else if _capacity > Float(Int32.max) { _capacity = Float(Int32.max) }
metalGraph.changeCapacity(to: UInt32(_capacity))
}
}
private var updateMinMaxLabelsTimer: Timer!
// Subviews
private var gradientBackground : _GradientView!
private var accessoriesView : _AccessoriesView!
fileprivate var metalGraph : _MetalGraphView!
fileprivate var horizontalLineView : _HorizontalLinesView!
fileprivate var maximumValueLabel : Label!
fileprivate var midValueLabel : Label!
fileprivate var minimumValueLabel : Label!
fileprivate var titleLabel : Label!
fileprivate var subtitleLabel : Label!
#if os(iOS)
fileprivate var autoScaleButton : GraphButton?
#endif
// -------------------------------
// MARK: Initialization
// -------------------------------
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup()
}
override init(frame: CGRect) {
super.init(frame: frame)
setup()
}
private func setup() {
#if os(iOS)
isOpaque = false
backgroundColor = .clear
#elseif os(OSX)
wantsLayer = true
layer?.isOpaque = false
layer?.backgroundColor = Color.clear.cgColor
#endif
addBackgroundView()
addHorizontalLineView()
addMetalGraphView()
addAccessoriesView()
addValueLabels()
addTitleAndSubtitleLabels()
#if os(iOS)
if gesturesEnabled { addGestureRecognizers() }
#endif
updateMinMaxLabelsTimer = Timer.scheduledTimer(withTimeInterval: 0.25, repeats: true) { _ in
self.updateMinMaxLabels()
}
}
private func addBackgroundView() {
gradientBackground = _GradientView(frame: bounds)
#if os(iOS)
gradientBackground.gradient.colors = backgroundTint.colors().reversed()
#elseif os(OSX)
gradientBackground.gradient.colors = backgroundTint.colors()
#endif
gradientBackground.gradient.cornerRadius = roundedCorners ? Constants.CornerRadius : 0.0
addSubview(gradientBackground)
gradientBackground.translatesAutoresizingMaskIntoConstraints = false
gradientBackground.topAnchor .constraint(equalTo: topAnchor) .isActive = true
gradientBackground.bottomAnchor .constraint(equalTo: bottomAnchor).isActive = true
gradientBackground.trailingAnchor.constraint(equalTo: trailingAnchor) .isActive = true
gradientBackground.leadingAnchor .constraint(equalTo: leadingAnchor) .isActive = true
}
private func addHorizontalLineView() {
horizontalLineView = _HorizontalLinesView(frame: bounds)
addSubview(horizontalLineView)
horizontalLineView.translatesAutoresizingMaskIntoConstraints = false
horizontalLineView.topAnchor .constraint(equalTo: topAnchor, constant: Constants.TopBottomPadding).isActive = true
horizontalLineView.bottomAnchor .constraint(equalTo: bottomAnchor, constant: -Constants.TopBottomPadding).isActive = true
horizontalLineView.leadingAnchor .constraint(equalTo: leadingAnchor, constant: 0) .isActive = true
horizontalLineView.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -Constants.ValueLabelWidth) .isActive = true
}
private func addMetalGraphView() {
let uniforms = _MetalGraphView.Uniforms(
offset : 0,
capacity : UInt32(capacity),
minValue : 0,
maxValue : 1,
pointSize : sampleSize.size(),
topColor : vector_float4(1, 1, 1, 1),
bottomColor : vector_float4(1, 1, 1, 1)
)
metalGraph = _MetalGraphView(frame: bounds, uniforms: uniforms)
switch sampleColor {
case .color(let color):
metalGraph.uniforms.topColor = color.vector()
metalGraph.uniforms.bottomColor = color.vector()
case .gradient(let top, let bottom):
metalGraph.uniforms.topColor = top .vector()
metalGraph.uniforms.bottomColor = bottom.vector()
}
addSubview(metalGraph)
metalGraph.translatesAutoresizingMaskIntoConstraints = false
metalGraph.topAnchor .constraint(equalTo: topAnchor, constant: Constants.TopBottomPadding).isActive = true
metalGraph.bottomAnchor .constraint(equalTo: bottomAnchor, constant: -Constants.TopBottomPadding).isActive = true
metalGraph.leadingAnchor .constraint(equalTo: leadingAnchor, constant: 0) .isActive = true
metalGraph.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -Constants.ValueLabelWidth) .isActive = true
}
private func addAccessoriesView() {
accessoriesView = _AccessoriesView(frame: bounds)
addSubview(accessoriesView)
accessoriesView.translatesAutoresizingMaskIntoConstraints = false
accessoriesView.topAnchor .constraint(equalTo: topAnchor) .isActive = true
accessoriesView.bottomAnchor .constraint(equalTo: bottomAnchor) .isActive = true
accessoriesView.trailingAnchor.constraint(equalTo: trailingAnchor).isActive = true
accessoriesView.widthAnchor .constraint(equalToConstant: Constants.ValueLabelWidth).isActive = true
}
private func addValueLabels() {
let maxValue = metalGraph.uniforms.maxValue
let minValue = metalGraph.uniforms.minValue
let midValue = Int32((Double(maxValue - minValue)/2 + Double(minValue)).rounded())
#if os(iOS)
maximumValueLabel = Label()
midValueLabel = Label()
minimumValueLabel = Label()
maximumValueLabel.text = "\(maxValue)"
midValueLabel .text = "\(midValue)"
minimumValueLabel.text = "\(minValue)"
#elseif os(OSX)
maximumValueLabel = Label(labelWithString: "\(maxValue)")
midValueLabel = Label(labelWithString: "\(midValue)")
minimumValueLabel = Label(labelWithString: "\(minValue)")
#endif
addSubview(maximumValueLabel)
addSubview(midValueLabel)
addSubview(minimumValueLabel)
maximumValueLabel.translatesAutoresizingMaskIntoConstraints = false
midValueLabel .translatesAutoresizingMaskIntoConstraints = false
minimumValueLabel.translatesAutoresizingMaskIntoConstraints = false
maximumValueLabel.font = Font.systemFont(ofSize: 15)
midValueLabel .font = Font.systemFont(ofSize: 15)
minimumValueLabel.font = Font.systemFont(ofSize: 15)
maximumValueLabel.textColor = Color(white: 1, alpha: 0.7)
midValueLabel .textColor = Color(white: 1, alpha: 0.7)
minimumValueLabel.textColor = Color(white: 1, alpha: 0.7)
maximumValueLabel.leadingAnchor.constraint(equalTo: accessoriesView.leadingAnchor, constant: 20).isActive = true
midValueLabel .leadingAnchor.constraint(equalTo: accessoriesView.leadingAnchor, constant: 20).isActive = true
minimumValueLabel.leadingAnchor.constraint(equalTo: accessoriesView.leadingAnchor, constant: 20).isActive = true
maximumValueLabel.widthAnchor.constraint(equalToConstant: Constants.ValueLabelWidth).isActive = true
midValueLabel .widthAnchor.constraint(equalToConstant: Constants.ValueLabelWidth).isActive = true
minimumValueLabel.widthAnchor.constraint(equalToConstant: Constants.ValueLabelWidth).isActive = true
maximumValueLabel.topAnchor .constraint(equalTo: topAnchor, constant: Constants.TopBottomPadding - 10).isActive = true
minimumValueLabel.bottomAnchor .constraint(equalTo: bottomAnchor, constant: -7).isActive = true
midValueLabel .centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true
}
private func addTitleAndSubtitleLabels() {
#if os(iOS)
titleLabel = Label()
subtitleLabel = Label()
titleLabel .text = title
subtitleLabel.text = subtitle
titleLabel .minimumScaleFactor = 0.1
subtitleLabel.minimumScaleFactor = 0.1
titleLabel .adjustsFontSizeToFitWidth = true
subtitleLabel.adjustsFontSizeToFitWidth = true
#elseif os(OSX)
titleLabel = Label(labelWithString: title)
subtitleLabel = Label(labelWithString: subtitle)
titleLabel .preferredMaxLayoutWidth = 1
subtitleLabel.preferredMaxLayoutWidth = 1
#endif
titleLabel .translatesAutoresizingMaskIntoConstraints = false
subtitleLabel.translatesAutoresizingMaskIntoConstraints = false
titleLabel .font = Font.systemFont(ofSize: 30)
subtitleLabel.font = Font.systemFont(ofSize: 20)
titleLabel .textColor = Color(white: 1, alpha: 1)
subtitleLabel.textColor = Color(white: 1, alpha: 0.6)
addSubview(titleLabel)
addSubview(subtitleLabel)
titleLabel .leadingAnchor.constraint(equalTo: leadingAnchor, constant: 20).isActive = true
subtitleLabel.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 20).isActive = true
titleLabel .topAnchor.constraint(equalTo: topAnchor, constant: 20).isActive = true
subtitleLabel.topAnchor.constraint(equalTo: titleLabel.bottomAnchor, constant: 5) .isActive = true
titleLabel .trailingAnchor.constraint(equalTo: metalGraph.trailingAnchor, constant: -20).isActive = true
subtitleLabel.trailingAnchor.constraint(equalTo: metalGraph.trailingAnchor, constant: -20).isActive = true
}
#if os(iOS)
private func addAutoScaleButton() {
guard autoScaleButton == nil else { return }
autoScaleButton = GraphButton(frame: CGRect(x: 0, y: 0, width: 1, height: 1))
autoScaleButton?.text = "Auto Scale"
autoScaleButton?.addTarget(self, action: #selector(autoScaleButtonTapped), for: .touchUpInside)
autoScaleButton?.translatesAutoresizingMaskIntoConstraints = false
autoScaleButton?.alpha = 0
addSubview(autoScaleButton!)
autoScaleButton?.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -(Constants.ValueLabelWidth + 16)).isActive = true
autoScaleButton?.bottomAnchor.constraint(equalTo: bottomAnchor, constant: -16).isActive = true
autoScaleButton?.widthAnchor.constraint(equalToConstant: 110).isActive = true
autoScaleButton?.heightAnchor.constraint(equalToConstant: 30).isActive = true
UIView.animate(withDuration: 0.5) {
self.autoScaleButton?.alpha = 1
}
}
#endif
#if os(iOS)
private func removeAutoScaleButton() {
UIView.animate(
withDuration: 0.5,
delay: 0.1,
options: [],
animations: {
self.autoScaleButton?.alpha = 0
}, completion: { _ in
self.autoScaleButton?.removeFromSuperview()
self.autoScaleButton = nil
}
)
}
#endif
/// Calling this will draw a constant horizontal line across the entire graph
/// for each of the specified values. It will also override any previous
/// horizontal lines.
fileprivate func drawHorizontalLines() {
horizontalLineView.lines = horizontalLines.map {
($0 - visibleRange.lowerBound) / (visibleRange.upperBound - visibleRange.lowerBound)
}
}
// -------------------------------
// MARK: Gesture Recognizers
// -------------------------------
#if os(iOS)
private func addGestureRecognizers() {
pinchRecognizer = UIPinchGestureRecognizer(target: self, action: #selector(pinchRecognizerDidPinch))
pinchRecognizer?.delegate = self
addGestureRecognizer(pinchRecognizer!)
panRecognizer = UIPanGestureRecognizer(target: self, action: #selector(panRecognizerDidPan))
panRecognizer?.delegate = self
panRecognizer?.minimumNumberOfTouches = 1
panRecognizer?.maximumNumberOfTouches = 1
addGestureRecognizer(panRecognizer!)
doubleTapRecognizer = UITapGestureRecognizer(target: self, action: #selector(doubleTapRecognizerDidRecognize))
doubleTapRecognizer?.numberOfTapsRequired = 2
doubleTapRecognizer?.numberOfTouchesRequired = 1
addGestureRecognizer(doubleTapRecognizer!)
}
#endif
#if os(iOS)
private func removeGestureRecognizers() {
if let pinch = pinchRecognizer {
removeGestureRecognizer(pinch)
}
if let pan = panRecognizer {
removeGestureRecognizer(pan)
}
if let doubleTap = doubleTapRecognizer {
removeGestureRecognizer(doubleTap)
}
}
#endif
#if os(iOS)
@objc private func pinchRecognizerDidPinch() {
guard let pinch = pinchRecognizer else { return }
switch pinch.state {
case .began:
isAutoscaling = false
fallthrough
case .changed:
guard pinch.numberOfTouches >= 2 else { return }
let a = pinch.location(ofTouch: 0, in: self)
let b = pinch.location(ofTouch: 1, in: self)
let dx = abs(a.x - b.x)
let dy = abs(a.y - b.y)
let midpointY = abs(a.y - b.y) / 2 + min(a.y, b.y)
// Calculate new capacity
let dxScale = (dx / (dx+dy)) * (1-pinch.scale) + 1
let dyScale = (dy / (dx+dy)) * (1-pinch.scale) + 1
let newCapacity = Float(CGFloat(_capacity) * dxScale)
if newCapacity >= 2 {
_capacity = newCapacity
}
// Calculate new visible range, based on pinch location
let oldMin = metalGraph.uniforms.minValue
let oldMax = metalGraph.uniforms.maxValue
let oldRange = visibleRange
let oldYSpread = oldRange.upperBound - oldRange.lowerBound
let newYSpread = oldYSpread * Float(dyScale)
let spreadChange = oldYSpread - newYSpread
let pinchLocationRatio = midpointY / bounds.height
let newMax = oldMax - Float(pinchLocationRatio) * spreadChange
let newMin = oldMin + Float(1-pinchLocationRatio) * spreadChange
visibleRange = newMin...newMax
// Do panning, works even when one finger is lifted
if let prevPos = previousPinchPosY {
translate(with: Float(midpointY - prevPos))
}
previousPinchPosY = midpointY
pinchRecognizer?.scale = 1.0
default:
// When released, cancelled, failed etc
previousPinchPosY = nil
}
}
#endif
#if os(iOS)
@objc private func doubleTapRecognizerDidRecognize() {
switch sampleSize {
case .custom: sampleSize = .small
case .large : sampleSize = .small
case .small : sampleSize = .large
}
}
#endif
#if os(iOS)
@objc private func panRecognizerDidPan() {
guard let pan = panRecognizer else { return }
switch pan.state {
case .began:
isAutoscaling = false
fallthrough
case .changed:
guard pan.numberOfTouches == 1 else { return }
translate(with: Float(pan.translation(in: self).y))
panRecognizer?.setTranslation(.zero, in: self)
default: break
}
}
#endif
private func translate(with translation: Float) {
let oldRange = visibleRange
let visibleHeight = bounds.height - Constants.TopBottomPadding * 2
let valuesPerPoint = abs(oldRange.upperBound - oldRange.lowerBound) / Float(visibleHeight)
let valuesToMove = translation * valuesPerPoint
let newMin = oldRange.lowerBound + valuesToMove
let newMax = oldRange.upperBound + valuesToMove
visibleRange = newMin...newMax
}
@objc private func autoScaleButtonTapped() {
isAutoscaling = true
}
}
#if os(iOS)
extension GraphView: UIGestureRecognizerDelegate {
public override func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
// True unless we find a finger on the auto-scale button
if let autoScaleButton = autoScaleButton {
for i in 0..<gestureRecognizer.numberOfTouches {
let point = gestureRecognizer.location(ofTouch: i, in: self)
if autoScaleButton.frame.contains(point) {
return false
}
}
}
return true
}
}
#endif
extension GraphView {
@objc fileprivate func updateMinMaxLabels() {
drawHorizontalLines()
let minValue = metalGraph.uniforms.minValue
let maxValue = metalGraph.uniforms.maxValue
let midValue = (maxValue - minValue)/2 + minValue
let minValueText = String(format: "%.\(valueUnitDecimals)f", minValue) + " " + self.valueUnit
let midValueText = String(format: "%.\(valueUnitDecimals)f", midValue) + " " + self.valueUnit
let maxValueText = String(format: "%.\(valueUnitDecimals)f", maxValue) + " " + self.valueUnit
#if os(iOS)
self.minimumValueLabel.text = minValueText
self.midValueLabel .text = midValueText
self.maximumValueLabel.text = maxValueText
#elseif os(OSX)
self.minimumValueLabel.stringValue = minValueText
self.midValueLabel .stringValue = midValueText
self.maximumValueLabel.stringValue = maxValueText
#endif
}
}
// -------------------------------
// MARK: Colors
// -------------------------------
public extension GraphView {
public enum BackgroundTintColor: Int {
case gray = 0
case red
case green
case blue
case turquoise
case yellow
case purple
case clear
fileprivate func colors() -> [CGColor] {
switch self {
case .gray:
return [Color(red: 141.0/255.0, green: 140.0/255.0, blue: 146.0/255.0, alpha: 1.0).cgColor,
Color(red: 210.0/255.0, green: 209.0/255.0, blue: 215.0/255.0, alpha: 1.0).cgColor]
case .red:
return [Color(red: 253.0/255.0, green: 58.0/255.0, blue: 52.0/255.0, alpha: 1.0).cgColor,
Color(red: 255.0/255.0, green: 148.0/255.0, blue: 86.0/255.0, alpha: 1.0).cgColor]
case .green:
return [Color(red: 28.0/255.0, green: 180.0/255.0, blue: 28.0/255.0, alpha: 1.0).cgColor,
Color(red: 78.0/255.0, green: 238.0/255.0, blue: 92.0/255.0, alpha: 1.0).cgColor]
case .blue:
return [Color(red: 0.0/255.0, green: 108.0/255.0, blue: 250.0/255.0, alpha: 1.0).cgColor,
Color(red: 90.0/255.0, green: 202.0/255.0, blue: 251.0/255.0, alpha: 1.0).cgColor]
case .turquoise:
return [Color(red: 54.0/255.0, green: 174.0/255.0, blue: 220.0/255.0, alpha: 1.0).cgColor,
Color(red: 82.0/255.0, green: 234.0/255.0, blue: 208.0/255.0, alpha: 1.0).cgColor]
case .yellow:
return [Color(red: 255.0/255.0, green: 160.0/255.0, blue: 33.0/255.0, alpha: 1.0).cgColor,
Color(red: 254.0/255.0, green: 209.0/255.0, blue: 48.0/255.0, alpha: 1.0).cgColor]
case .purple:
return [Color(red: 140.0/255.0, green: 70.0/255.0, blue: 250.0/255.0, alpha: 1.0).cgColor,
Color(red: 217.0/255.0, green: 168.0/255.0, blue: 252.0/255.0, alpha: 1.0).cgColor]
case .clear:
return [Color.clear.cgColor]
}
}
public static var count: Int { return BackgroundTintColor.clear.rawValue + 1 }
}
public enum SampleColor {
case color(plain: Color)
case gradient(top: Color, bottom: Color)
}
}
// -------------------------------
// MARK: Gradient View
// -------------------------------
// This has to be a separate class to work properly with rotation animation
fileprivate class _GradientView: View {
var gradient: CAGradientLayer {
get { return layer as! CAGradientLayer }
}
#if os(iOS)
override class var layerClass: AnyClass {
get { return CAGradientLayer.self }
}
#elseif os(OSX)
override init(frame frameRect: NSRect) {
super.init(frame: frameRect)
setup()
}
required init?(coder: NSCoder) {
super.init(coder: coder)
setup()
}
private func setup() {
wantsLayer = true
layerContentsRedrawPolicy = .onSetNeedsDisplay
}
fileprivate override func makeBackingLayer() -> CALayer {
return CAGradientLayer()
}
#endif
}
// -------------------------------
// MARK: RenderCycle
// -------------------------------
fileprivate protocol RenderCycleObserver: class {
func renderCycle()
}
class RenderCycle {
private struct WeakRenderCycleObserver {
weak var value : RenderCycleObserver?
init (value: RenderCycleObserver) {
self.value = value
}
}
static let shared = RenderCycle()
private var observers = [WeakRenderCycleObserver]()
private var mutex = pthread_mutex_t()
#if os(iOS)
private var displayLink: CADisplayLink?
#elseif os(OSX)
private var displayLink: CVDisplayLink?
#endif
private init() {
pthread_mutex_init(&mutex, nil)
}
private func initializeDisplayLink() {
#if os(iOS)
displayLink = CADisplayLink(target: self, selector: #selector(renderCycle))
if #available(iOS 10, *) {
displayLink?.preferredFramesPerSecond = 30
} else {
displayLink?.frameInterval = 2
}
displayLink?.add(to: .main, forMode: .commonModes)
#elseif os(OSX)
var dl: CVDisplayLink?
CVDisplayLinkCreateWithActiveCGDisplays(&dl)
guard let displayLink = dl else { return }
self.displayLink = displayLink
CVDisplayLinkSetOutputCallback(displayLink, { _, _, _, _, _, context in
if let context = context {
let me = Unmanaged<RenderCycle>.fromOpaque(context).takeUnretainedValue()
me.renderCycle()
}
return kCVReturnSuccess
}, Unmanaged.passUnretained(self).toOpaque())
CVDisplayLinkStart(displayLink)
#endif
}
private func destroyDisplayLink() {
#if os(iOS)
displayLink?.invalidate()
displayLink = nil
#elseif os(OSX)
guard let displayLink = displayLink else { return }
CVDisplayLinkStop(displayLink)
self.displayLink = nil
#endif
}
@objc private func renderCycle() {
DispatchQueue.main.async {
pthread_mutex_lock(&self.mutex)
self.observers.forEach { $0.value?.renderCycle() }
pthread_mutex_unlock(&self.mutex)
}
}
fileprivate func add(cycleObserver: RenderCycleObserver) {
pthread_mutex_lock(&mutex)
observers.append(WeakRenderCycleObserver(value: cycleObserver))
if observers.count == 1 {
// Just added the first observer
initializeDisplayLink()
}
pthread_mutex_unlock(&mutex)
}
fileprivate func remove(cycleObserver: RenderCycleObserver) {
pthread_mutex_lock(&mutex)
if let idx = observers.index(where: { $0.value === cycleObserver }) {
observers.remove(at: idx)
}
if observers.count == 0 {
// Just removed the last observer
destroyDisplayLink()
}
pthread_mutex_unlock(&mutex)
}
}
// -------------------------------
// MARK: Metal Graph
// -------------------------------
fileprivate class _MetalGraphView: View, RenderCycleObserver {
struct Uniforms {
var offset : UInt32
var capacity : UInt32
var minValue : Float
var maxValue : Float
var pointSize : UInt8
var topColor : vector_float4
var bottomColor: vector_float4
// On macOS, the uniforms must be 256 byte aligned
#if os(OSX)
let pad0 = matrix_double4x4()
let pad1 = matrix_double2x3()
#endif
}
// User Data
fileprivate var vertices: [Float]!
private var verticesSemaphore: DispatchSemaphore!
private var samplesAdded = 0
private var needsRedraw = true
private var needsRedrawMutex = pthread_mutex_t()
var uniforms: Uniforms!
var graphType = GraphView.GraphType.scatter
var isAutoscaling = true {
didSet {
if isAutoscaling {
guard case .success = verticesSemaphore.wait(timeout: .now() + .milliseconds(100)) else {
Swift.print("❌ Semaphore wait timed out \(self)")
return
}
refreshMin()
refreshMax()
verticesSemaphore.signal()
#if os(iOS)
setNeedsDisplay()
#elseif os(OSX)
setNeedsDisplay(bounds)
#endif
}
}
}
// Metal State
private var commandQueue: MTLCommandQueue!
private var pipeline: MTLRenderPipelineState!
private let multisamplingEnabled = true // Currently not in use
// Buffers
private var vertexBuffer: MTLBuffer!
private var uniformBuffers: [MTLBuffer]!
private let bufferOptions: MTLResourceOptions = [.cpuCacheModeWriteCombined, .storageModeShared]
// Inflight Buffers
private let numberOfInflightBuffers = 3
private var inflightBufferSemaphore = DispatchSemaphore(value: 3) // Used for triple buffering
private var inflightBufferIndex = 0
private var device: MTLDevice!
private var metalLayer: CAMetalLayer { return layer as! CAMetalLayer }
// -------------------------------
// MARK: Setup
// -------------------------------
required init(coder: NSCoder) {
// _MetalGraphView will only be initialized by GraphView
fatalError("❌ init(coder:) has not been implemented")
}
init(frame frameRect: CGRect, uniforms: Uniforms) {
super.init(frame: frameRect)
self.uniforms = uniforms
setup()
}
private func setup() {
#if os(iOS)
layer.isOpaque = false
#elseif os(OSX)
wantsLayer = true
layer?.isOpaque = false
#endif
pthread_mutex_init(&needsRedrawMutex, nil)
// Setup user data
vertices = [Float](repeating: 0, count: Int(uniforms.capacity))
// Setup metal state
device = MTLCreateSystemDefaultDevice()
guard device != nil else {
fatalError("❌ GraphView has to run on a device with Metal support")
}
metalLayer.device = device
metalLayer.pixelFormat = .bgra8Unorm
metalLayer.framebufferOnly = true
commandQueue = device?.makeCommandQueue()
setupBuffers()
setupPipeline()
// Setup semaphores
verticesSemaphore = DispatchSemaphore(value: 1)
inflightBufferSemaphore = DispatchSemaphore(value: numberOfInflightBuffers)
RenderCycle.shared.add(cycleObserver: self)
}
deinit {
RenderCycle.shared.remove(cycleObserver: self)
}
#if os(iOS)
override class var layerClass: AnyClass {
return CAMetalLayer.self
}
override func layoutSublayers(of layer: CALayer) {
super.layoutSublayers(of: layer)
let screen = window?.screen ?? UIScreen.main
setNewScale(screen.scale)
#if os(iOS)
setNeedsDisplay()
#elseif os(OSX)
setNeedsDisplay(bounds)
#endif
}
#elseif os(OSX)
override fileprivate func makeBackingLayer() -> CALayer {
return CAMetalLayer()
}
fileprivate override func layout() {
super.layout()
setNewScale(window?.backingScaleFactor ?? 1)
}
fileprivate override func viewDidMoveToWindow() {
setNewScale(window?.backingScaleFactor ?? 1)
}
#endif
private func setNewScale(_ scale: CGFloat) {
metalLayer.contentsScale = scale
var drawableSize = bounds.size
drawableSize.width = round(scale * drawableSize.width)
drawableSize.height = round(scale * drawableSize.height)
metalLayer.drawableSize = drawableSize
#if os(iOS)
setNeedsDisplay()
#elseif os(OSX)
setNeedsDisplay(bounds)
#endif
}
#if os(iOS)
fileprivate override func setNeedsDisplay() {
pthread_mutex_lock(&needsRedrawMutex)
needsRedraw = true
pthread_mutex_unlock(&needsRedrawMutex)
super.setNeedsDisplay()
}
#elseif os(OSX)
fileprivate override func setNeedsDisplay(_ invalidRect: NSRect) {
pthread_mutex_lock(&needsRedrawMutex)
needsRedraw = true
pthread_mutex_unlock(&needsRedrawMutex)
super.setNeedsDisplay(invalidRect)
}
#endif
// -------------------------------
// MARK: 🤘 Setup
// -------------------------------
private func setupPipeline() {
#if swift(>=4.0)
guard let library = device!.makeDefaultLibrary() else {
Swift.print("❌ There doesn't appear to be a .metal file in your project")
return
}
#else
guard let library = device!.newDefaultLibrary() else {
Swift.print("❌ There doesn't appear to be a .metal file in your project")
return
}
#endif
guard let vertexFunction = library.makeFunction(name: "vertexShader") else {
Swift.print("❌ Make sure that the .metal file in your project contains a function called \"vertexShader\"")
return
}
guard let fragmentFunction = library.makeFunction(name: "fragmentShader") else {
Swift.print("❌ Make sure that the .metal file in your project contains a function called \"fragmentShader\"")
return
}
let pipelineDescriptor = MTLRenderPipelineDescriptor()
pipelineDescriptor.colorAttachments[0].pixelFormat = .bgra8Unorm
pipelineDescriptor.vertexFunction = vertexFunction
pipelineDescriptor.fragmentFunction = fragmentFunction
do {
pipeline = try device!.makeRenderPipelineState(descriptor: pipelineDescriptor)
} catch let error as NSError {
Swift.print("❌ Failed to create a render pipeline state with error: \(error)")
}
}
private func setupBuffers() {
// Vertices
let vertexByteCount = MemoryLayout<Float>.size * Int(uniforms.capacity)
vertexBuffer = device!.makeBuffer(length: vertexByteCount, options : bufferOptions)
vertexBuffer.label = "Vertex Buffer"
// Uniforms
uniformBuffers = (0..<numberOfInflightBuffers).map {
let byteCount = MemoryLayout<Uniforms>.size
#if swift(>=4.0)
guard let buffer = device!.makeBuffer(length: byteCount, options: bufferOptions) else {
fatalError("❌ Failed to create buffer of size \(byteCount)")
}
#else
let buffer = device!.makeBuffer(length: byteCount, options: bufferOptions)
#endif
buffer.label = "Uniforms Buffer \($0)"
return buffer
}
}
// -------------------------------
// MARK: Fileprivate Methods
// -------------------------------
// Adds a new sample to the vertices array, and checks to see if the
// sample added is a new min or max sample, or if the oldest sample
// was the current min or max. In either case, a new min or max is
// selected, respectively.
func add(sample: Float) {
// Grab the vertices array lock
guard case .success = verticesSemaphore.wait(timeout: .now() + .milliseconds(100)) else {
Swift.print("❌ Semaphore wait timed out \(self))")
return
}
// Used to check if we need to scan for a new min or max
let sampleToRemove = vertices[Int(uniforms.offset)]
// Write the new sample to the vertices array
vertices[Int(uniforms.offset)] = sample
uniforms.offset = (uniforms.offset + 1) % UInt32(vertices.count)
if samplesAdded == 0 && isAutoscaling {
// This was the first sample
uniforms.minValue = sample - 1
uniforms.maxValue = sample + 1
} else if samplesAdded == 2 {
refreshMin()
refreshMax()
} else {
// This was not the first sample
if isAutoscaling {
if sample < uniforms.minValue {
// The sample added is a new min
uniforms.minValue = sample
} else if sample > uniforms.maxValue {
// The sample added is a new max
uniforms.maxValue = sample
}
// Checking if sampleToRemove is equal to the current min or max.
// Not the best of practises, but hopefully the epsilon large enough to avoid
// inaccuracies, and small enough to not conflict with any actual values.
let epsilon: Float = 0.00001
if abs(sampleToRemove - uniforms.minValue) < epsilon {
// The sample that was removed was the previous min value.
// Rescanning for a new min value
refreshMin()
}
if abs(sampleToRemove - uniforms.maxValue) < epsilon {
// The sample that was removed was the previous max value.
// Rescanning for a new max value
refreshMax()
}
}
}
// Updating this after the sample has been added as a vertex to avoid race conditions.
// If the draw occurs between when the vertex is added, and samplesAdded is updated,
// this sample won't get drawn until the next screen update. This is only an issue in
// the beginning when uniforms.capacity > samplesAdded.
samplesAdded = min(samplesAdded + 1, Int(uniforms.capacity))
// Release the vertices array lock
verticesSemaphore.signal()
#if os(iOS)
setNeedsDisplay()
#elseif os(OSX)
setNeedsDisplay(bounds)
#endif
}
/// Replaces the entire vertices array with new data.
/// uniforms.capacity and the vertex buffer is resized accordingly.
func set(samples: [Float]) {
guard case .success = verticesSemaphore.wait(timeout: .now() + .milliseconds(100)) else {
Swift.print("❌ Semaphore wait timed out \(self))")
return
}
for _ in 0..<3 {
guard case .success = inflightBufferSemaphore.wait(timeout: .now() + .milliseconds(100)) else {
Swift.print("❌ Semaphore wait timed out \(self))")
return
}
}
samplesAdded = samples.count
uniforms.offset = 0
uniforms.capacity = UInt32(samples.count)
vertices = samples
let vertexByteCount = MemoryLayout<Float>.size * Int(uniforms.capacity)
if vertexBuffer.length != vertexByteCount {
vertexBuffer = device!.makeBuffer(length: vertexByteCount, options : bufferOptions)
vertexBuffer.label = "Vertex Buffer"
}
if isAutoscaling {
refreshMin()
refreshMax()
}
for _ in 0..<3 { inflightBufferSemaphore.signal() }
verticesSemaphore.signal()
#if os(iOS)
setNeedsDisplay()
#elseif os(OSX)
setNeedsDisplay(bounds)
#endif
}
// Changes the size of the vertices array, and the vertex buffers.
// It stops all drawing, and waits until the buffers are available
// before resizing.
func changeCapacity(to newCapacity: UInt32) {
// Make sure we have a new capacity
guard newCapacity != uniforms.capacity else { return }
guard case .success = verticesSemaphore.wait(timeout: .now() + .milliseconds(100)) else {
Swift.print("❌ Semaphore wait timed out \(self))")
return
}
// We will re-alloc the metal buffers, so stop all drawing.
for _ in 0..<3 {
guard case .success = inflightBufferSemaphore.wait(timeout: .now() + .milliseconds(100)) else {
Swift.print("❌ Semaphore wait timed out \(self))")
return
}
}
// First resize the vertices array
if newCapacity > uniforms.capacity {
// Increase the buffer size
let count = Int(newCapacity - uniforms.capacity)
if samplesAdded < Int(uniforms.capacity) {
// All the elements in the vertices array are not yet populated
vertices.append(contentsOf: [Float](repeating: 0, count: count))
} else {
// All the elements in the vertices array are populated
let suffix = vertices.suffix(from: Int(uniforms.offset))
let prefix = vertices.prefix(upTo: Int(uniforms.offset))
vertices = suffix + prefix + [Float](repeating: 0, count: count)
uniforms.offset = UInt32(samplesAdded - 1)
}
} else {
// Remove samples
let count = Int(uniforms.capacity - newCapacity)
let rightStartIndex = Int(uniforms.offset) // This is the oldest sample in the verticesArray
// The elements we're removing could be spread over both
// the right side, and the left side of the vertices array,
// so it gets sort of tricky.
// Remove the portion on the right-hand side
let rightEndIndex = min(rightStartIndex + count - 1, vertices.count - 1)
vertices.removeSubrange(rightStartIndex...rightEndIndex)
// Check if we need to remove from the left-hand side as well
if rightStartIndex + count > Int(uniforms.capacity) {
let leftCount = rightStartIndex + count - Int(uniforms.capacity)
vertices.removeFirst(leftCount)
}
// If we've removed everything on the right-hand side, then
// the write index should be set to zero.
if rightStartIndex + count >= Int(uniforms.capacity) {
uniforms.offset = 0
}
}
// New that the vertices array has been resized, re-alloc the vertex buffers
let newBufferSize = MemoryLayout<Float>.size * Int(newCapacity)
vertexBuffer = device!.makeBuffer(length: newBufferSize, options : bufferOptions)
vertexBuffer.label = "Vertex Buffer"
uniforms.capacity = newCapacity
samplesAdded = min(samplesAdded, Int(uniforms.capacity))
refreshMin()
refreshMax()
// All the buffers have been re-alloced, and are ready for drawing
for _ in 0..<3 { inflightBufferSemaphore.signal() }
verticesSemaphore.signal()
#if os(iOS)
setNeedsDisplay()
#elseif os(OSX)
setNeedsDisplay(bounds)
#endif
}
func clear() {
guard case .success = verticesSemaphore.wait(timeout: .now() + .milliseconds(100)) else {
Swift.print("❌ Semaphore wait timed out \(self))")
return
}
vertices = [Float](repeating: 0, count: Int(uniforms.capacity))
uniforms.offset = 0
samplesAdded = 0
verticesSemaphore.signal()
uniforms.minValue = 0
uniforms.maxValue = 1
#if os(iOS)
setNeedsDisplay()
#elseif os(OSX)
setNeedsDisplay(bounds)
#endif
}
// -------------------------------
// MARK: Drawing
// -------------------------------
private func updateUniforms() {
memcpy(
uniformBuffers[inflightBufferIndex].contents(),
&uniforms,
MemoryLayout<Uniforms>.size
)
}
private func updateVertexBuffer() {
guard case .success = verticesSemaphore.wait(timeout: .now() + .milliseconds(100)) else {
Swift.print("❌ Semaphore wait timed out \(self))")
return
}
_ = vertices.withUnsafeBytes {
memcpy(
self.vertexBuffer.contents(),
$0.baseAddress,
MemoryLayout<Float>.size * vertices.count
)
}
verticesSemaphore.signal()
}
func renderCycle() {
guard (bounds.size.width > 0 && bounds.size.height > 0 && bounds.size.width <= 16384) &&
samplesAdded > 0 &&
uniformBuffers != nil &&
window != nil
else { return }
pthread_mutex_lock(&needsRedrawMutex)
let shouldDraw = needsRedraw
needsRedraw = false
pthread_mutex_unlock(&needsRedrawMutex)
if shouldDraw {
autoreleasepool { self.render() }
}
}
private func render() {
guard case .success = inflightBufferSemaphore.wait(timeout: .now() + .milliseconds(100)) else {
Swift.print("❌ Semaphore wait timed out \(self))")
return
}
updateUniforms()
updateVertexBuffer()
#if swift(>=4.0)
guard let commandBuffer = commandQueue.makeCommandBuffer() else {
Swift.print("❌ Failed to create command buffer")
return
}
#else
let commandBuffer = commandQueue.makeCommandBuffer()
#endif
commandBuffer.label = "Graph Command Buffer"
guard let drawable = metalLayer.nextDrawable() else {
Swift.print("❌ No drawable")
inflightBufferSemaphore.signal()
return
}
let passDescriptor = MTLRenderPassDescriptor()
passDescriptor.colorAttachments[0].texture = drawable.texture
passDescriptor.colorAttachments[0].loadAction = .clear
passDescriptor.colorAttachments[0].storeAction = .store
passDescriptor.colorAttachments[0].clearColor = MTLClearColorMake(0, 0, 0, 0)
#if swift(>=4.0)
guard let encoder = commandBuffer.makeRenderCommandEncoder(descriptor: passDescriptor) else {
Swift.print("❌ Failed to create render command encoder with pass descriptor \(passDescriptor)")
return
}
#else
let encoder = commandBuffer.makeRenderCommandEncoder(descriptor: passDescriptor)
#endif
encoder.label = "Graph Encoder"
encoder.setRenderPipelineState(pipeline)
#if swift(>=4.0)
encoder.setVertexBuffer(vertexBuffer, offset: 0, index: 0)
encoder.setVertexBuffer(uniformBuffers[inflightBufferIndex], offset: 0, index: 1)
#else
encoder.setVertexBuffer(vertexBuffer, offset: 0, at: 0)
encoder.setVertexBuffer(uniformBuffers[inflightBufferIndex], offset: 0, at: 1)
#endif
switch graphType {
case .scatter:
encoder.drawPrimitives(type: .point, vertexStart: 0, vertexCount: samplesAdded)
case .line:
// - Draw in two parts based on the verticesWriteIndex to avoid the line from start to finish.
// - Probably use setVertexOffset or something.
// - Take a look at offset byte alignment in the documentation for setVertexBufferOffset.
// - The problem with this approach is that the vid in the vertex shader gets reset for every
// drawPrimitives call. The result is that two lines are being drawn on top of each other.
// - Perhaps the solution is to change the uniforms buffer, or even to have a separate
// uniforms buffer that is used when drawing as a line.
#if swift(>=4.0)
encoder.setVertexBufferOffset(MemoryLayout<Float>.size * Int(uniforms.offset), index: 0)
#else
encoder.setVertexBufferOffset(MemoryLayout<Float>.size * Int(uniforms.offset), at: 0)
#endif
encoder.drawPrimitives(
type : .lineStrip,
vertexStart : 0,
vertexCount : samplesAdded - Int(uniforms.offset)
)
#if swift(>=4.0)
encoder.setVertexBufferOffset(0, index: 0)
#else
encoder.setVertexBufferOffset(0, at: 0)
#endif
encoder.drawPrimitives(
type : .lineStrip,
vertexStart : 0,
vertexCount : Int(uniforms.offset) + 1
)
}
encoder.endEncoding()
commandBuffer.addCompletedHandler { _ in
self.inflightBufferSemaphore.signal()
}
commandBuffer.present(drawable)
commandBuffer.commit()
inflightBufferIndex = (inflightBufferIndex + 1) % numberOfInflightBuffers
}
// -------------------------------
// MARK: Private Helpers
// -------------------------------
private func refreshMin() {
guard samplesAdded > 0 && isAutoscaling else { return }
var minimum = Float.greatestFiniteMagnitude
if samplesAdded == 1 {
minimum = vertices[0] - 1
} else {
vDSP_minv(vertices, vDSP_Stride(1), &minimum, vDSP_Length(samplesAdded))
}
uniforms.minValue = minimum
}
private func refreshMax() {
guard samplesAdded > 0 && isAutoscaling else { return }
var maximum = -Float.greatestFiniteMagnitude
if samplesAdded == 1 {
maximum = vertices[0] + 1
} else {
vDSP_maxv(vertices, vDSP_Stride(1), &maximum, vDSP_Length(samplesAdded))
}
uniforms.maxValue = maximum
}
}
// -------------------------------
// MARK: Accessories View
// -------------------------------
fileprivate class _AccessoriesView: View {
// -------------------------------
// MARK: Setup
// -------------------------------
override init(frame: CGRect) {
super.init(frame: frame)
setup()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup()
}
private func setup() {
#if os(iOS)
backgroundColor = .clear
isOpaque = false
contentMode = .redraw
#elseif os(OSX)
wantsLayer = true
layer?.backgroundColor = .clear
#endif
}
// -------------------------------
// MARK: Draw
// -------------------------------
fileprivate override func draw(_ rect: CGRect) {
// Constants for the accessories view
let lineWidth: CGFloat = 2
let tickLength: CGFloat = 10
// Set up the path
let path = BezierPath()
path.lineWidth = lineWidth
Color(white: 1, alpha: 0.3).setStroke()
#if os(iOS)
// Vertical Line
path.move( to: Point(x: 0, y: 0))
path.addLine(to: Point(x: 0, y: bounds.size.height))
// Top
path.move( to: Point(x: lineWidth/2, y: Constants.TopBottomPadding))
path.addLine(to: Point(x: lineWidth/2 + tickLength, y: Constants.TopBottomPadding))
// Middle
path.move( to: Point(x: lineWidth/2, y: bounds.size.height / 2))
path.addLine(to: Point(x: lineWidth/2 + tickLength, y: bounds.size.height / 2))
// Bottom
path.move( to: Point(x: lineWidth/2, y: bounds.size.height - Constants.TopBottomPadding))
path.addLine(to: Point(x: lineWidth/2 + tickLength, y: bounds.size.height - Constants.TopBottomPadding))
#elseif os(OSX)
// Vertical Line
path.move(to: Point(x: 0, y: 0))
path.line(to: Point(x: 0, y: bounds.size.height))
// Top
path.move(to: Point(x: lineWidth/2, y: bounds.size.height - Constants.TopBottomPadding))
path.line(to: Point(x: lineWidth/2 + tickLength, y: bounds.size.height - Constants.TopBottomPadding))
// Middle
path.move(to: Point(x: lineWidth/2, y: bounds.size.height / 2))
path.line(to: Point(x: lineWidth/2 + tickLength, y: bounds.size.height / 2))
// Bottom
path.move(to: Point(x: lineWidth/2, y: Constants.TopBottomPadding))
path.line(to: Point(x: lineWidth/2 + tickLength, y: Constants.TopBottomPadding))
#endif
// Stroke the path
path.stroke()
}
}
// -------------------------------
// MARK: Horizontal Lines
// -------------------------------
fileprivate class _HorizontalLinesView: View {
/// Should be values between 0 (bottom) and 1 (top)
var lines = [Float]() {
didSet { setNeedsDisplay(bounds) }
}
override init(frame frameRect: Rect) {
super.init(frame: frameRect)
setup()
}
required init?(coder: NSCoder) {
super.init(coder: coder)
setup()
}
private func setup() {
#if os(iOS)
backgroundColor = .clear
isOpaque = false
contentMode = .redraw
#elseif os(OSX)
wantsLayer = true
layer?.backgroundColor = .clear
#endif
}
override func draw(_ dirtyRect: Rect) {
super.draw(dirtyRect)
for line in lines {
#if os(OSX)
let y = CGFloat(line) * bounds.height
#elseif os(iOS)
let y = CGFloat(1-line) * bounds.height
#endif
let path = BezierPath()
path.move(to: Point(x: 0, y: y))
#if os(OSX)
path.line(to: Point(x: bounds.width, y: y))
#elseif os(iOS)
path.addLine(to: Point(x: bounds.width, y: y))
#endif
Color(white: 1, alpha: 0.7).setStroke()
path.lineWidth = 2
path.stroke()
}
}
}
// -------------------------------
// MARK: Graph Button
// -------------------------------
#if os(iOS)
@IBDesignable
class GraphButton: UIButton {
@IBInspectable
var text: String = ""
@IBInspectable
var fontSize: CGFloat = 17
override var isHighlighted: Bool {
didSet { setNeedsDisplay() }
}
// Overrides the case when a touch is near the bottom or top of the screen, and
// iOS waits to check if the user want to open Control Center or Notification Center.
override func point(inside point: CGPoint, with event: UIEvent?) -> Bool {
if bounds.contains(point) {
isHighlighted = true
return true
} else {
return false
}
}
override func draw(_ rect: CGRect) {
// Set fill color
Color(white: 1, alpha: isHighlighted ? 0.3 : 0.5).setFill()
// Draw the background
BezierPath(roundedRect: bounds, cornerRadius: 5).fill()
// Get the context
if let context = UIGraphicsGetCurrentContext() {
// Prepare text attributes
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.alignment = .center
let attributes: [NSAttributedStringKey: Any] = [
.font : UIFont.systemFont(ofSize: fontSize, weight: .medium),
.paragraphStyle : paragraphStyle
]
let textSize = (text as NSString).size(withAttributes: attributes)
// Finding the rect to draw in, so the text is centered
var drawingRect = bounds
drawingRect.origin.y = bounds.height/2 - textSize.height/2
drawingRect.size.height = textSize.height
// Draw text
context.saveGState()
context.setBlendMode(.destinationOut)
(text as NSString).draw(in: drawingRect, withAttributes: attributes)
context.restoreGState()
}
}
}
#endif
// -------------------------------
// MARK: Helpful Extensions
// -------------------------------
fileprivate extension Color {
func vector() -> vector_float4 {
#if os(iOS)
var r: CGFloat = 0
var g: CGFloat = 0
var b: CGFloat = 0
var a: CGFloat = 0
getRed(&r, green: &g, blue: &b, alpha: &a)
return [Float(r), Float(g), Float(b), Float(a)]
#elseif os(OSX)
let color = usingColorSpace(.deviceRGB)!
return [
Float(color.redComponent),
Float(color.greenComponent),
Float(color.blueComponent),
Float(color.alphaComponent)
]
#endif
}
}
| mit | 6ff396862583e97267f030f95614d574 | 33.709216 | 136 | 0.562619 | 5.02924 | false | false | false | false |
mpimenov/omim | iphone/Maps/UI/Welcome/WhatsNew/WhatsNewBuilder.swift | 4 | 2060 | class WhatsNewBuilder {
static var configs:[WhatsNewPresenter.WhatsNewConfig] {
return [
WhatsNewPresenter.WhatsNewConfig(image: UIImage(named: "img_whatsnew_lp"),
title: "whatsnew_lp_title",
text: "whatsnew_lp_message",
buttonNextTitle: "whatsnew_trial_cta",
isCloseButtonHidden: false,
action: {
let subscribeViewController = SubscriptionViewBuilder.buildLonelyPlanet(parentViewController: MapViewController.shared(),
source: kStatWhatsNew,
successDialog: .goToCatalog,
completion: nil)
MapViewController.shared().present(subscribeViewController, animated: true)
}),
WhatsNewPresenter.WhatsNewConfig(image: UIImage(named: "img_whatsnew_lp"),
title: "whatsnew_lp_title",
text: "whatsnew_lp_message",
buttonNextTitle: "done")
]
}
static func build(delegate: WelcomeViewDelegate) -> [UIViewController] {
return WhatsNewBuilder.configs.map { (config) -> UIViewController in
let sb = UIStoryboard.instance(.welcome)
let vc = sb.instantiateViewController(ofType: WelcomeViewController.self);
let router = WelcomeRouter(viewController: vc, delegate: delegate)
let presenter = WhatsNewPresenter(view: vc,
router: router,
config: config)
vc.presenter = presenter
return vc
}
}
}
| apache-2.0 | 7dce2a7cdf490262310eac95204a45bb | 54.675676 | 161 | 0.454369 | 6.776316 | false | true | false | false |
akeaswaran/Countr | Countdown/SnapshotHelper.swift | 1 | 4689 | //
// SnapshotHelper.swift
// Example
//
// Created by Felix Krause on 10/8/15.
// Copyright © 2015 Felix Krause. All rights reserved.
//
import Foundation
import XCTest
var deviceLanguage = ""
var locale = ""
@available(*, deprecated, message: "use setupSnapshot: instead")
func setLanguage(app: XCUIApplication) {
setupSnapshot(app: app)
}
func setupSnapshot(app: XCUIApplication) {
Snapshot.setupSnapshot(app: app)
}
func snapshot(name: String, waitForLoadingIndicator: Bool = true) {
Snapshot.snapshot(name: name, waitForLoadingIndicator: waitForLoadingIndicator)
}
public class Snapshot: NSObject {
public class func setupSnapshot(app: XCUIApplication) {
setLanguage(app: app)
setLocale(app: app)
setLaunchArguments(app: app)
}
class func setLanguage(app: XCUIApplication) {
guard let prefix = pathPrefix() else {
return
}
let path = prefix.appendingPathComponent("language.txt")
do {
let trimCharacterSet = NSCharacterSet.whitespacesAndNewlines
deviceLanguage = try NSString(contentsOfFile: path, encoding: String.Encoding.utf8.rawValue).trimmingCharacters(in: trimCharacterSet) as String
app.launchArguments += ["-AppleLanguages", "(\(deviceLanguage))"]
} catch {
print("Couldn't detect/set language...")
}
}
class func setLocale(app: XCUIApplication) {
guard let prefix = pathPrefix() else {
return
}
let path = prefix.appendingPathComponent("locale.txt")
do {
let trimCharacterSet = NSCharacterSet.whitespacesAndNewlines
locale = try NSString(contentsOfFile: path, encoding: String.Encoding.utf8.rawValue).trimmingCharacters(in: trimCharacterSet) as String
} catch {
print("Couldn't detect/set locale...")
}
if locale.isEmpty {
locale = NSLocale(localeIdentifier: deviceLanguage).localeIdentifier
}
app.launchArguments += ["-AppleLocale", "\"\(locale)\""]
}
class func setLaunchArguments(app: XCUIApplication) {
guard let prefix = pathPrefix() else {
return
}
let path = prefix.appendingPathComponent("snapshot-launch_arguments.txt")
app.launchArguments += ["-FASTLANE_SNAPSHOT", "YES", "-ui_testing"]
do {
let launchArguments = try NSString(contentsOfFile: path, encoding: String.Encoding.utf8.rawValue) as String
let regex = try NSRegularExpression(pattern: "(\\\".+?\\\"|\\S+)", options: [])
let matches = regex.matches(in: launchArguments, options: [], range: NSRange(location:0, length:launchArguments.characters.count))
let results = matches.map { result -> String in
(launchArguments as NSString).substring(with: result.range)
}
app.launchArguments += results
} catch {
print("Couldn't detect/set launch_arguments...")
}
}
public class func snapshot(name: String, waitForLoadingIndicator: Bool = true) {
if waitForLoadingIndicator {
waitForLoadingIndicatorToDisappear()
}
print("snapshot: \(name)") // more information about this, check out https://github.com/fastlane/fastlane/tree/master/snapshot#how-does-it-work
sleep(1) // Waiting for the animation to be finished (kind of)
#if os(tvOS)
XCUIApplication().childrenMatchingType(.Browser).count
#else
XCUIDevice.shared().orientation = .unknown
#endif
}
class func waitForLoadingIndicatorToDisappear() {
#if os(tvOS)
return;
#endif
let query = XCUIApplication().statusBars.children(matching: .other).element(boundBy: 1).children(matching: .other)
while (0..<query.count).map({ query.element(boundBy: $0) }).contains(where: { $0.isLoadingIndicator }) {
sleep(1)
print("Waiting for loading indicator to disappear...")
}
}
class func pathPrefix() -> NSString? {
if let path = ProcessInfo().environment["SIMULATOR_HOST_HOME"] as NSString? {
return path.appendingPathComponent("Library/Caches/tools.fastlane") as NSString?
}
print("Couldn't find Snapshot configuration files at ~/Library/Caches/tools.fastlane")
return nil
}
}
extension XCUIElement {
var isLoadingIndicator: Bool {
return self.frame.size == CGSize(width: 10, height: 20)
}
}
// Please don't remove the lines below
// They are used to detect outdated configuration files
// SnapshotHelperVersion [1.2]
| mit | f388d96c37b055bb366b755ce91b420c | 32.971014 | 155 | 0.640145 | 4.903766 | false | false | false | false |
OscarSwanros/swift | stdlib/public/SDK/Foundation/FileManager.swift | 18 | 2872 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
@_exported import Foundation // Clang module
import _SwiftFoundationOverlayShims
extension FileManager {
/*
renamed syntax should be:
public func replaceItem(at originalItemURL: URL, withItemAt newItemURL: URL, backupItemName: String? = nil, options : FileManager.ItemReplacementOptions = []) throws -> URL?
*/
@available(*, deprecated, renamed:"replaceItemAt(_:withItemAt:backupItemName:options:)")
public func replaceItemAtURL(originalItemURL: NSURL, withItemAtURL newItemURL: NSURL, backupItemName: String? = nil, options: FileManager.ItemReplacementOptions = []) throws -> NSURL? {
var error: NSError? = nil
guard let result = __NSFileManagerReplaceItemAtURL(self, originalItemURL as URL, newItemURL as URL, backupItemName, options, &error) else { throw error! }
return result as NSURL
}
@available(swift, obsoleted: 4)
@available(OSX 10.6, iOS 4.0, *)
public func replaceItemAt(_ originalItemURL: URL, withItemAt newItemURL: URL, backupItemName: String? = nil, options: FileManager.ItemReplacementOptions = []) throws -> NSURL? {
var error: NSError?
guard let result = __NSFileManagerReplaceItemAtURL(self, originalItemURL, newItemURL , backupItemName, options, &error) else { throw error! }
return result as NSURL
}
@available(swift, introduced: 4)
@available(OSX 10.6, iOS 4.0, *)
public func replaceItemAt(_ originalItemURL: URL, withItemAt newItemURL: URL, backupItemName: String? = nil, options: FileManager.ItemReplacementOptions = []) throws -> URL? {
var error: NSError?
guard let result = __NSFileManagerReplaceItemAtURL(self, originalItemURL, newItemURL , backupItemName, options, &error) else { throw error! }
return result
}
@available(OSX 10.6, iOS 4.0, *)
@nonobjc
public func enumerator(at url: URL, includingPropertiesForKeys keys: [URLResourceKey]?, options mask: FileManager.DirectoryEnumerationOptions = [], errorHandler handler: ((URL, Error) -> Bool)? = nil) -> FileManager.DirectoryEnumerator? {
return __NSFileManagerEnumeratorAtURL(self, url, keys, mask, { (url, error) in
var errorResult = true
if let h = handler {
errorResult = h(url as URL, error)
}
return errorResult
})
}
}
| apache-2.0 | 1cbe0a88d2047bb232f19e9d9c94ef56 | 50.285714 | 242 | 0.654596 | 4.739274 | false | false | false | false |
LoopKit/LoopKit | LoopKit/LoopMath.swift | 1 | 12384 | //
// LoopMath.swift
// Naterade
//
// Created by Nathan Racklyeft on 1/24/16.
// Copyright © 2016 Nathan Racklyeft. All rights reserved.
//
import Foundation
import HealthKit
public enum LoopMath {
static func simulationDateRangeForSamples<T: Collection>(
_ samples: T,
from start: Date? = nil,
to end: Date? = nil,
duration: TimeInterval,
delay: TimeInterval = 0,
delta: TimeInterval
) -> (start: Date, end: Date)? where T.Element: TimelineValue {
guard samples.count > 0 else {
return nil
}
if let start = start, let end = end {
return (start: start.dateFlooredToTimeInterval(delta), end: end.dateCeiledToTimeInterval(delta))
} else {
var minDate = samples.first!.startDate
var maxDate = minDate
for sample in samples {
if sample.startDate < minDate {
minDate = sample.startDate
}
if sample.endDate > maxDate {
maxDate = sample.endDate
}
}
return (
start: (start ?? minDate).dateFlooredToTimeInterval(delta),
end: (end ?? maxDate.addingTimeInterval(duration + delay)).dateCeiledToTimeInterval(delta)
)
}
}
/**
Calculates a timeline of predicted glucose values from a variety of effects timelines.
Each effect timeline:
- Is given equal weight, with the exception of the momentum effect timeline
- Can be of arbitrary size and start date
- Should be in ascending order
- Should have aligning dates with any overlapping timelines to ensure a smooth result
- parameter startingGlucose: The starting glucose value
- parameter momentum: The momentum effect timeline determined from prior glucose values
- parameter effects: The glucose effect timelines to apply to the prediction.
- returns: A timeline of glucose values
*/
public static func predictGlucose(startingAt startingGlucose: GlucoseValue, momentum: [GlucoseEffect] = [], effects: [GlucoseEffect]...) -> [PredictedGlucoseValue] {
return predictGlucose(startingAt: startingGlucose, momentum: momentum, effects: effects)
}
/**
Calculates a timeline of predicted glucose values from a variety of effects timelines.
Each effect timeline:
- Is given equal weight, with the exception of the momentum effect timeline
- Can be of arbitrary size and start date
- Should be in ascending order
- Should have aligning dates with any overlapping timelines to ensure a smooth result
- parameter startingGlucose: The starting glucose value
- parameter momentum: The momentum effect timeline determined from prior glucose values
- parameter effects: The glucose effect timelines to apply to the prediction.
- returns: A timeline of glucose values
*/
public static func predictGlucose(startingAt startingGlucose: GlucoseValue, momentum: [GlucoseEffect] = [], effects: [[GlucoseEffect]]) -> [PredictedGlucoseValue] {
var effectValuesAtDate: [Date: Double] = [:]
let unit = HKUnit.milligramsPerDeciliter
for timeline in effects {
var previousEffectValue: Double = timeline.first?.quantity.doubleValue(for: unit) ?? 0
for effect in timeline {
let value = effect.quantity.doubleValue(for: unit)
effectValuesAtDate[effect.startDate] = (effectValuesAtDate[effect.startDate] ?? 0) + value - previousEffectValue
previousEffectValue = value
}
}
// Blend the momentum effect linearly into the summed effect list
if momentum.count > 1 {
var previousEffectValue: Double = momentum[0].quantity.doubleValue(for: unit)
// The blend begins delta minutes after after the last glucose (1.0) and ends at the last momentum point (0.0)
// We're assuming the first one occurs on or before the starting glucose.
let blendCount = momentum.count - 2
let timeDelta = momentum[1].startDate.timeIntervalSince(momentum[0].startDate)
// The difference between the first momentum value and the starting glucose value
let momentumOffset = startingGlucose.startDate.timeIntervalSince(momentum[0].startDate)
let blendSlope = 1.0 / Double(blendCount)
let blendOffset = momentumOffset / timeDelta * blendSlope
for (index, effect) in momentum.enumerated() {
let value = effect.quantity.doubleValue(for: unit)
let effectValueChange = value - previousEffectValue
let split = min(1.0, max(0.0, Double(momentum.count - index) / Double(blendCount) - blendSlope + blendOffset))
let effectBlend = (1.0 - split) * (effectValuesAtDate[effect.startDate] ?? 0)
let momentumBlend = split * effectValueChange
effectValuesAtDate[effect.startDate] = effectBlend + momentumBlend
previousEffectValue = value
}
}
let prediction = effectValuesAtDate.sorted { $0.0 < $1.0 }.reduce([PredictedGlucoseValue(startDate: startingGlucose.startDate, quantity: startingGlucose.quantity)]) { (prediction, effect) -> [PredictedGlucoseValue] in
if effect.0 > startingGlucose.startDate, let lastValue = prediction.last {
let nextValue = PredictedGlucoseValue(
startDate: effect.0,
quantity: HKQuantity(unit: unit, doubleValue: effect.1 + lastValue.quantity.doubleValue(for: unit))
)
return prediction + [nextValue]
} else {
return prediction
}
}
return prediction
}
}
extension GlucoseValue {
/**
Calculates a timeline of glucose effects by applying a linear decay to a rate of change.
- parameter rate: The glucose velocity
- parameter duration: The duration the effect should continue before ending
- parameter delta: The time differential for the returned values
- returns: An array of glucose effects
*/
public func decayEffect(atRate rate: HKQuantity, for duration: TimeInterval, withDelta delta: TimeInterval = 5 * 60) -> [GlucoseEffect] {
guard let (startDate, endDate) = LoopMath.simulationDateRangeForSamples([self], duration: duration, delta: delta) else {
return []
}
let glucoseUnit = HKUnit.milligramsPerDeciliter
let velocityUnit = GlucoseEffectVelocity.perSecondUnit
// The starting rate, which we will decay to 0 over the specified duration
let intercept = rate.doubleValue(for: velocityUnit) // mg/dL/s
let decayStartDate = startDate.addingTimeInterval(delta)
let slope = -intercept / (duration - delta) // mg/dL/s/s
var values = [GlucoseEffect(startDate: startDate, quantity: quantity)]
var date = decayStartDate
var lastValue = quantity.doubleValue(for: glucoseUnit)
repeat {
let value = lastValue + (intercept + slope * date.timeIntervalSince(decayStartDate)) * delta
values.append(GlucoseEffect(startDate: date, quantity: HKQuantity(unit: glucoseUnit, doubleValue: value)))
lastValue = value
date = date.addingTimeInterval(delta)
} while date < endDate
return values
}
}
extension BidirectionalCollection where Element == GlucoseEffect {
/// Sums adjacent glucose effects into buckets of the specified duration.
///
/// Requires the receiver to be sorted chronologically by endDate
///
/// - Parameter duration: The duration of each resulting summed element
/// - Returns: An array of summed effects
public func combinedSums(of duration: TimeInterval) -> [GlucoseChange] {
var sums = [GlucoseChange]()
sums.reserveCapacity(self.count)
var lastValidIndex = sums.startIndex
for effect in reversed() {
sums.append(GlucoseChange(startDate: effect.startDate, endDate: effect.endDate, quantity: effect.quantity))
for sumsIndex in lastValidIndex..<(sums.endIndex - 1) {
guard sums[sumsIndex].endDate <= effect.endDate.addingTimeInterval(duration) else {
lastValidIndex += 1
continue
}
sums[sumsIndex].append(effect)
}
}
return sums.reversed()
}
/// Returns the net effect of the receiver as a GlucoseChange object
///
/// Requires the receiver to be sorted chronologically by endDate
///
/// - Returns: A single GlucoseChange representing the net effect
public func netEffect() -> GlucoseChange? {
guard let first = self.first, let last = self.last else {
return nil
}
let net = last.quantity.doubleValue(for: .milligramsPerDeciliter) - first.quantity.doubleValue(for: .milligramsPerDeciliter)
return GlucoseChange(startDate: first.startDate, endDate: last.endDate, quantity: HKQuantity(unit: .milligramsPerDeciliter, doubleValue: net))
}
}
extension Sequence where Element: AdditiveArithmetic {
func sum() -> Element {
return reduce(.zero, +)
}
}
extension BidirectionalCollection where Element == GlucoseEffectVelocity {
/// Subtracts an array of glucose effects with uniform intervals and no gaps from the collection of effect changes, which may not have uniform intervals.
///
/// - Parameters:
/// - otherEffects: The array of glucose effects to subtract
/// - effectInterval: The time interval between elements in the otherEffects array
/// - Returns: A resulting array of glucose effects
public func subtracting(_ otherEffects: [GlucoseEffect], withUniformInterval effectInterval: TimeInterval) -> [GlucoseEffect] {
// Trim both collections to match
let otherEffects = otherEffects.filterDateRange(self.first?.endDate, nil)
let effects = self.filterDateRange(otherEffects.first?.startDate, nil)
var subtracted: [GlucoseEffect] = []
var previousOtherEffectValue = otherEffects.first?.quantity.doubleValue(for: .milligramsPerDeciliter) ?? 0 // mg/dL
var effectIndex = effects.startIndex
for otherEffect in otherEffects.dropFirst() {
guard effectIndex < effects.endIndex else {
break
}
let otherEffectValue = otherEffect.quantity.doubleValue(for: .milligramsPerDeciliter)
let otherEffectChange = otherEffectValue - previousOtherEffectValue
previousOtherEffectValue = otherEffectValue
let effect = effects[effectIndex]
// Our effect array may have gaps, or have longer segments than 5 minutes.
guard effect.endDate <= otherEffect.endDate else {
continue // Move on to the next other effect
}
effectIndex += 1
let effectValue = effect.quantity.doubleValue(for: GlucoseEffectVelocity.perSecondUnit) // mg/dL/s
let effectValueMatchingOtherEffectInterval = effectValue * effectInterval // mg/dL
subtracted.append(GlucoseEffect(
startDate: effect.endDate,
quantity: HKQuantity(
unit: .milligramsPerDeciliter,
doubleValue: effectValueMatchingOtherEffectInterval - otherEffectChange
)
))
}
// If we have run out of otherEffect items, we assume the otherEffectChange remains zero
for effect in effects[effectIndex..<effects.endIndex] {
let effectValue = effect.quantity.doubleValue(for: GlucoseEffectVelocity.perSecondUnit) // mg/dL/s
let effectValueMatchingOtherEffectInterval = effectValue * effectInterval // mg/dL
subtracted.append(GlucoseEffect(
startDate: effect.endDate,
quantity: HKQuantity(
unit: .milligramsPerDeciliter,
doubleValue: effectValueMatchingOtherEffectInterval
)
))
}
return subtracted
}
}
| mit | a47cb514d32c9343cc098da29c023882 | 40.276667 | 225 | 0.646693 | 5.131786 | false | false | false | false |
TotemTraining/PracticaliOSAppSecurity | V5/Keymaster/Keymaster/CategoriesCollectionViewController.swift | 1 | 4156 | //
// CategoriesCollectionViewController.swift
// Keymaster
//
// Created by Chris Forant on 4/22/15.
// Copyright (c) 2015 Totem. All rights reserved.
//
import UIKit
import LocalAuthentication
let reuseIdentifier = "Cell"
let highlightColor = UIColor(red:0.99, green:0.67, blue:0.16, alpha:1)
class CategoriesCollectionViewController: UICollectionViewController {
let categories = ["Household" , "Finance", "Computer", "Mobile", "Email", "Shopping", "User Accounts", "Secrets", "Music", "ID", "Biometrics", "Media"]
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if let identifier = segue.identifier {
switch identifier {
case "SEGUE_ENTRIES":
let vc = segue.destinationViewController as! EntriesViewController
if let selectedIndex = (collectionView?.indexPathsForSelectedItems().last as? NSIndexPath)?.row {
vc.category = categories[selectedIndex]
}
default: return
}
}
}
}
// MARK: - Collection View Datasource
extension CategoriesCollectionViewController {
override func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
return 1
}
override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return count(categories)
}
override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! CategoryCell
// Configure the cell
cell.categoryImageView.image = UIImage(named: categories[indexPath.row])
cell.categoryImageView.highlightedImage = UIImage(named: categories[indexPath.row])?.imageWithRenderingMode(UIImageRenderingMode.AlwaysTemplate)
return cell
}
override func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
let context = LAContext()
if context.canEvaluatePolicy(LAPolicy.DeviceOwnerAuthenticationWithBiometrics, error: nil) {
context.evaluatePolicy(LAPolicy.DeviceOwnerAuthenticationWithBiometrics, localizedReason: "We need your fingerprint to show you that", reply: { (success, error) -> Void in
if success {
NSOperationQueue.mainQueue().addOperationWithBlock({ () -> Void in
self.performSegueWithIdentifier("SEGUE_ENTRIES", sender: self)
})
}else{
return
}
})
}
}
override func collectionView(collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionReusableView {
switch kind {
case UICollectionElementKindSectionHeader: return collectionView.dequeueReusableSupplementaryViewOfKind(kind, withReuseIdentifier: "SectionHeader", forIndexPath: indexPath) as! SectionHeaderView
case UICollectionElementKindSectionFooter: return collectionView.dequeueReusableSupplementaryViewOfKind(kind, withReuseIdentifier: "SectionFooter", forIndexPath: indexPath) as! SectionFooterView
default: return UICollectionReusableView()
}
}
override func collectionView(collectionView: UICollectionView, didHighlightItemAtIndexPath indexPath: NSIndexPath) {
let cell = collectionView.cellForItemAtIndexPath(indexPath)
cell?.contentView.backgroundColor = highlightColor
}
override func collectionView(collectionView: UICollectionView, didUnhighlightItemAtIndexPath indexPath: NSIndexPath) {
let cell = collectionView.cellForItemAtIndexPath(indexPath)
cell?.contentView.backgroundColor = UIColor.clearColor()
}
}
| mit | b2db768eb662712f36ebb3a45dd8933d | 43.688172 | 202 | 0.701155 | 6.202985 | false | false | false | false |
david1mdavis/IOS-nRF-Toolbox | nRF Toolbox/PROXIMITY/NORProximityViewController.swift | 1 | 18559 | //
// NORPRoximityViewController.swift
// nRF Toolbox
//
// Created by Mostafa Berg on 10/05/16.
// Copyright © 2016 Nordic Semiconductor. All rights reserved.
//
import UIKit
import CoreBluetooth
import AVFoundation
class NORProximityViewController: NORBaseViewController, CBCentralManagerDelegate, CBPeripheralDelegate, NORScannerDelegate, CBPeripheralManagerDelegate {
//MARK: - Class Properties
var bluetoothManager : CBCentralManager?
var proximityImmediateAlertServiceUUID : CBUUID
var proximityLinkLossServiceUUID : CBUUID
var proximityAlertLevelCharacteristicUUID : CBUUID
var batteryServiceUUID : CBUUID
var batteryLevelCharacteristicUUID : CBUUID
var isImmidiateAlertOn : Bool?
var isBackButtonPressed : Bool?
var proximityPeripheral : CBPeripheral?
var peripheralManager : CBPeripheralManager?
var immidiateAlertCharacteristic : CBCharacteristic?
var audioPlayer : AVAudioPlayer?
//MARK: - View Outlets
@IBOutlet weak var deviceName: UILabel!
@IBOutlet weak var battery: UIButton!
@IBOutlet weak var lockImage: UIImageView!
@IBOutlet weak var verticalLabel: UILabel!
@IBOutlet weak var findmeButton: UIButton!
@IBOutlet weak var connectionButton: UIButton!
//MARK: - View Actions
@IBAction func connectionButtonTapped(_ sender: AnyObject) {
if proximityPeripheral != nil {
bluetoothManager?.cancelPeripheralConnection(proximityPeripheral!)
}
}
@IBAction func findmeButtonTapped(_ sender: AnyObject) {
if self.immidiateAlertCharacteristic != nil {
if isImmidiateAlertOn == true {
self.immidiateAlertOff()
} else {
self.immidiateAlertOn()
}
}
}
@IBAction func aboutButtonTapped(_ sender: AnyObject) {
self.showAbout(message: NORAppUtilities.getHelpTextForService(service: .proximity))
}
//MARK: - UIVIew Delegate
required init?(coder aDecoder: NSCoder) {
// Custom initialization
proximityImmediateAlertServiceUUID = CBUUID(string: NORServiceIdentifiers.proximityImmediateAlertServiceUUIDString)
proximityLinkLossServiceUUID = CBUUID(string: NORServiceIdentifiers.proximityLinkLossServiceUUIDString)
proximityAlertLevelCharacteristicUUID = CBUUID(string: NORServiceIdentifiers.proximityAlertLevelCharacteristicUUIDString)
batteryServiceUUID = CBUUID(string: NORServiceIdentifiers.batteryServiceUUIDString)
batteryLevelCharacteristicUUID = CBUUID(string: NORServiceIdentifiers.batteryLevelCharacteristicUUIDString)
super.init(coder: aDecoder)
}
override func viewDidLoad() {
super.viewDidLoad()
// Rotate the vertical label
self.verticalLabel.transform = CGAffineTransform(translationX: -(verticalLabel.frame.width/2) + (verticalLabel.frame.height / 2), y: 0.0).rotated(by: CGFloat(-M_PI_2))
self.immidiateAlertCharacteristic = nil
isImmidiateAlertOn = false
isBackButtonPressed = false;
self.initGattServer()
self.initSound()
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
if proximityPeripheral != nil && isBackButtonPressed == true {
bluetoothManager?.cancelPeripheralConnection(proximityPeripheral!)
}
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
isBackButtonPressed = true
}
//MARK: - Class Implementation
func initSound() {
do{
try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
try AVAudioSession.sharedInstance().setActive(true)
} catch _ {
print("Could not init AudioSession!")
return
}
let url = URL(fileURLWithPath: Bundle.main.path(forResource: "high", ofType: "mp3")!)
do {
audioPlayer = try AVAudioPlayer(contentsOf: url)
} catch _ {
print("Could not intialize AudioPlayer")
return
}
audioPlayer?.prepareToPlay()
}
func enableFindmeButton() {
findmeButton.isEnabled = true
findmeButton.backgroundColor = UIColor.black
findmeButton.setTitleColor(UIColor.white, for: UIControlState())
}
func disableFindmeButton() {
findmeButton.isEnabled = false
findmeButton.backgroundColor = UIColor.lightGray
findmeButton.setTitleColor(UIColor.lightText, for: UIControlState())
}
func initGattServer() {
peripheralManager = CBPeripheralManager(delegate: self, queue: nil)
}
func addServices() {
let service = CBMutableService(type: CBUUID(string:"1802"), primary: true)
let characteristic = self.createCharacteristic()
service.characteristics = [characteristic]
self.peripheralManager?.add(service)
}
func createCharacteristic() -> CBMutableCharacteristic {
let properties : CBCharacteristicProperties = CBCharacteristicProperties.writeWithoutResponse
let permissions : CBAttributePermissions = CBAttributePermissions.writeable
let characteristicType : CBUUID = CBUUID(string:"2A06")
let characteristic : CBMutableCharacteristic = CBMutableCharacteristic(type: characteristicType, properties: properties, value: nil, permissions: permissions)
return characteristic
}
func immidiateAlertOn() {
if self.immidiateAlertCharacteristic != nil {
var val : UInt8 = 2
let data = Data(bytes: &val, count: 1)
proximityPeripheral?.writeValue(data, for: immidiateAlertCharacteristic!, type: CBCharacteristicWriteType.withoutResponse)
isImmidiateAlertOn = true
findmeButton.setTitle("SilentMe", for: UIControlState())
}
}
func immidiateAlertOff() {
if self.immidiateAlertCharacteristic != nil {
var val : UInt8 = 0
let data = Data(bytes: &val, count: 1)
proximityPeripheral?.writeValue(data, for: immidiateAlertCharacteristic!, type: CBCharacteristicWriteType.withoutResponse)
isImmidiateAlertOn = false
findmeButton.setTitle("FindMe", for: UIControlState())
}
}
func stopSound() {
audioPlayer?.stop()
}
func playLoopingSound() {
audioPlayer?.numberOfLoops = -1
audioPlayer?.play()
}
func playSoundOnce() {
audioPlayer?.play()
}
func clearUI() {
deviceName.text = "DEFAULT PROXIMITY"
battery.setTitle("n/a", for:UIControlState.disabled)
battery.tag = 0
lockImage.isHighlighted = false
isImmidiateAlertOn = false
self.immidiateAlertCharacteristic = nil
}
func applicationDidEnterBackgroundCallback() {
let name = proximityPeripheral?.name ?? "peripheral"
NORAppUtilities.showBackgroundNotification(message: "You are still connected to \(name).")
}
func applicationDidBecomeActiveCallback() {
UIApplication.shared.cancelAllLocalNotifications()
}
//MARK: - Segue Methods
override func shouldPerformSegue(withIdentifier identifier: String, sender: Any?) -> Bool {
// The 'scan' seque will be performed only if connectedPeripheral == nil (if we are not connected already).
return identifier != "scan" || proximityPeripheral == nil
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "scan" {
// Set this contoller as scanner delegate
let nc = segue.destination as! UINavigationController
let controller = nc.childViewControllerForStatusBarHidden as! NORScannerViewController
controller.filterUUID = proximityLinkLossServiceUUID
controller.delegate = self
}
}
//MARK: - NORScannerDelegate
func centralManagerDidSelectPeripheral(withManager aManager: CBCentralManager, andPeripheral aPeripheral: CBPeripheral) {
// We may not use more than one Central Manager instance. Let's just take the one returned from Scanner View Controller
bluetoothManager = aManager
bluetoothManager!.delegate = self
// The sensor has been selected, connect to it
proximityPeripheral = aPeripheral
proximityPeripheral!.delegate = self
bluetoothManager?.connect(proximityPeripheral!, options: [CBConnectPeripheralOptionNotifyOnNotificationKey : NSNumber(value: true as Bool)])
}
//MARK: - CBCentralManagerDelegate
func centralManagerDidUpdateState(_ central: CBCentralManager) {
if central.state == .poweredOff {
print("Bluetooth powered off")
} else {
print("Bluetooth powered on")
}
}
func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) {
// Scanner uses other queue to send events. We must edit UI in the main queue
DispatchQueue.main.async(execute: {
self.deviceName.text = peripheral.name
self.connectionButton.setTitle("DISCONNECT", for: UIControlState())
self.lockImage.isHighlighted = true
self.enableFindmeButton()
})
//Following if condition display user permission alert for background notification
if UIApplication.instancesRespond(to: #selector(UIApplication.registerUserNotificationSettings(_:))){
UIApplication.shared.registerUserNotificationSettings(UIUserNotificationSettings(types: [.alert, .sound], categories: nil))
}
NotificationCenter.default.addObserver(self, selector: #selector(self.applicationDidEnterBackgroundCallback), name: NSNotification.Name.UIApplicationDidEnterBackground, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(self.applicationDidBecomeActiveCallback), name: NSNotification.Name.UIApplicationDidBecomeActive, object: nil)
if NORAppUtilities.isApplicationInactive() {
NORAppUtilities.showBackgroundNotification(message: "\(self.proximityPeripheral?.name) is within range!")
}
peripheral.discoverServices([proximityLinkLossServiceUUID, proximityImmediateAlertServiceUUID, batteryServiceUUID])
}
func centralManager(_ central: CBCentralManager, didFailToConnect peripheral: CBPeripheral, error: Error?) {
// Scanner uses other queue to send events. We must edit UI in the main queue
DispatchQueue.main.async(execute: {
NORAppUtilities.showAlert(title: "Error", andMessage: "Connecting to the peripheral failed. Try again")
self.connectionButton.setTitle("CONNECT", for: UIControlState())
self.proximityPeripheral = nil
self.disableFindmeButton()
self.clearUI()
})
}
func centralManager(_ central: CBCentralManager, didDisconnectPeripheral peripheral: CBPeripheral, error: Error?) {
print("Peripheral disconnected or out of range!")
DispatchQueue.main.async(execute: {
let name = peripheral.name ?? "Peripheral"
if error != nil {
self.lockImage.isHighlighted = false
self.disableFindmeButton()
self.bluetoothManager?.connect(peripheral, options: [CBConnectPeripheralOptionNotifyOnNotificationKey : NSNumber(value: true as Bool)])
let message = "\(name) is out of range!"
if NORAppUtilities.isApplicationInactive() {
NORAppUtilities.showBackgroundNotification(message: message)
} else {
NORAppUtilities.showAlert(title: "PROXIMITY", andMessage: message)
}
self.playSoundOnce()
} else {
self.connectionButton.setTitle("CONNECT", for: UIControlState())
if NORAppUtilities.isApplicationInactive() {
NORAppUtilities.showBackgroundNotification(message: "\(name) is disconnected.")
}
self.proximityPeripheral = nil
self.clearUI()
NotificationCenter.default.removeObserver(self, name:NSNotification.Name.UIApplicationDidBecomeActive, object: nil)
NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIApplicationDidEnterBackground, object: nil)
}
})
}
//MARK: - CBPeripheralDelegate
func peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: Error?) {
guard error == nil else {
print("An error occured while discovering services: \(error!.localizedDescription)")
bluetoothManager!.cancelPeripheralConnection(peripheral)
return;
}
for aService : CBService in (peripheral.services)! {
if aService.uuid == proximityLinkLossServiceUUID {
print("Link loss service is found")
peripheral.discoverCharacteristics([proximityAlertLevelCharacteristicUUID], for: aService)
} else if aService.uuid == proximityImmediateAlertServiceUUID {
print("Immediate alert service is found")
peripheral.discoverCharacteristics([proximityAlertLevelCharacteristicUUID], for: aService)
}else if aService.uuid == batteryServiceUUID {
print("Battery service is found")
peripheral.discoverCharacteristics([batteryLevelCharacteristicUUID], for: aService)
}
}
}
func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, error: Error?) {
guard error == nil else {
print("Error occurred while discovering characteristic: \(error!.localizedDescription)")
bluetoothManager!.cancelPeripheralConnection(peripheral)
return
}
if service.uuid == proximityLinkLossServiceUUID {
for aCharacteristic : CBCharacteristic in service.characteristics! {
if aCharacteristic.uuid == proximityAlertLevelCharacteristicUUID {
var val = UInt8(1)
let data = Data(bytes: &val, count: 1)
peripheral.writeValue(data, for: aCharacteristic, type: CBCharacteristicWriteType.withResponse)
}
}
} else if service.uuid == proximityImmediateAlertServiceUUID {
for aCharacteristic : CBCharacteristic in service.characteristics! {
if aCharacteristic.uuid == proximityAlertLevelCharacteristicUUID {
immidiateAlertCharacteristic = aCharacteristic
}
}
} else if service.uuid == batteryServiceUUID {
for aCharacteristic : CBCharacteristic in service.characteristics! {
if aCharacteristic.uuid == batteryLevelCharacteristicUUID {
peripheral.readValue(for: aCharacteristic)
}
}
}
}
func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?) {
guard error == nil else {
print("Error occurred while updating characteristic value: \(error!.localizedDescription)")
return
}
print(characteristic.uuid)
DispatchQueue.main.async(execute: {
if characteristic.uuid == self.batteryLevelCharacteristicUUID {
let value = characteristic.value!
let array = UnsafeMutablePointer<UInt8>(mutating: (value as NSData).bytes.bindMemory(to: UInt8.self, capacity: value.count))
let batteryLevel = UInt8(array[0])
let text = "\(batteryLevel)%"
self.battery.setTitle(text, for: UIControlState.disabled)
if self.battery.tag == 0 {
// If battery level notifications are available, enable them
if (characteristic.properties.rawValue & CBCharacteristicProperties.notify.rawValue) > 0 {
//Mark that we have enabled notifications
self.battery.tag = 1
//Enable notification on data characteristic
self.proximityPeripheral?.setNotifyValue(true, for: characteristic)
}
}
}
})
}
//MARK: - CBPeripheralManagerDelegate
func peripheralManagerDidUpdateState(_ peripheral: CBPeripheralManager) {
switch (peripheral.state) {
case .poweredOff:
print("PeripheralManagerState is Off")
break;
case .poweredOn:
print("PeripheralManagerState is on");
self.addServices()
break;
default:
break;
}
}
func peripheralManager(_ peripheral: CBPeripheralManager, didAdd service: CBService, error: Error?) {
guard error == nil else {
print("Error while adding peripheral service: \(error!.localizedDescription)")
return
}
print("PeripheralManager added sercvice successfully")
}
func peripheralManager(_ peripheral: CBPeripheralManager, didReceiveWrite requests: [CBATTRequest]) {
let attributeRequest = requests[0]
if attributeRequest.characteristic.uuid == CBUUID(string: "2A06") {
let data = attributeRequest.value!
let array = UnsafeMutablePointer<UInt8>(mutating: (data as NSData).bytes.bindMemory(to: UInt8.self, capacity: data.count))
let alertLevel = array[0]
switch alertLevel {
case 0:
print("No Alert")
stopSound()
break
case 1:
print("Low Alert")
playLoopingSound()
break
case 2:
print("High Alert")
playSoundOnce()
break
default:
break
}
}
}
}
| bsd-3-clause | 9faddb0c1c0f87cad19abfaf7ccf1513 | 42.87234 | 189 | 0.639455 | 5.806633 | false | false | false | false |
lanjing99/iOSByTutorials | iOS 8 by tutorials/Chapter 15 - Beginning CloudKit/BabiFud-Final/BabiFud/UserInfo.swift | 1 | 3228 | /*
* Copyright (c) 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 Foundation
import CloudKit
class UserInfo {
let container : CKContainer
var userRecordID : CKRecordID!
var contacts = [AnyObject]()
init (container : CKContainer) {
self.container = container;
}
func loggedInToICloud(completion : (accountStatus : CKAccountStatus, error : NSError?) -> ()) {
container.accountStatusWithCompletionHandler() { (status : CKAccountStatus, error : NSError!) in
completion(accountStatus: status, error: error)
}
}
func userID(completion: (userRecordID: CKRecordID!, error: NSError!)->()) {
if userRecordID != nil {
completion(userRecordID: userRecordID, error: nil)
} else {
self.container.fetchUserRecordIDWithCompletionHandler() {
recordID, error in
if recordID != nil {
self.userRecordID = recordID
}
completion(userRecordID: recordID, error: error)
}
}
}
func userInfo(completion: (userInfo: CKDiscoveredUserInfo!, error: NSError!)->()) {
requestDiscoverability() { discoverable in
self.userID() { recordID, error in
if error != nil {
completion(userInfo: nil, error: error)
} else {
self.userInfo(recordID, completion: completion)
}
}
}
}
func userInfo(recordID: CKRecordID!,
completion:(userInfo: CKDiscoveredUserInfo!, error: NSError!)->()) {
container.discoverUserInfoWithUserRecordID(recordID,
completionHandler:completion)
}
func requestDiscoverability(completion: (discoverable: Bool) -> ()) {
container.statusForApplicationPermission(
.PermissionUserDiscoverability) {
status, error in
if error != nil || status == CKApplicationPermissionStatus.Denied {
completion(discoverable: false)
} else {
self.container.requestApplicationPermission(.PermissionUserDiscoverability) { status, error in
completion(discoverable: status == .Granted)
}
}
}
}
func findContacts(completion: (userInfos:[AnyObject]!, error: NSError!)->()) {
completion(userInfos: [CKRecordID](), error: nil)
}
}
| mit | 10566f6f7152dd3f8cbcb0904109650b | 34.086957 | 102 | 0.695477 | 4.75405 | false | false | false | false |
ben-ng/swift | benchmark/single-source/LinkedList.swift | 1 | 1308 | //===--- LinkedList.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
//
//===----------------------------------------------------------------------===//
// This test checks performance of linked lists. It is based on LinkedList from
// utils/benchmark, with modifications for performance measuring.
import TestsUtils
final class Node {
var next: Node?
var data: Int
init(n: Node?, d: Int) {
next = n
data = d
}
}
@inline(never)
public func run_LinkedList(_ N: Int) {
let size = 100
var head = Node(n:nil, d:0)
for i in 0..<size {
head = Node(n:head, d:i)
}
var sum = 0
let ref_result = size*(size-1)/2
var ptr = head
for _ in 1...5000*N {
ptr = head
sum = 0
while let nxt = ptr.next {
sum += ptr.data
ptr = nxt
}
if sum != ref_result {
break
}
}
CheckResults(sum == ref_result,
"Incorrect results in LinkedList: \(sum) != \(ref_result)")
}
| apache-2.0 | 88f9d22d7cc95f6ec031134ee8b130be | 24.647059 | 80 | 0.566514 | 3.904478 | false | false | false | false |
elaser/swift-json-mapper | Mapper/Operators/Operator.swift | 1 | 766 | //
// Operator.swift
// Mapper
//
// Created by Anderthan Hsieh on 10/2/16.
// Copyright © 2016 anderthan. All rights reserved.
//
import Foundation
public func =><T>(lhs: JSON, rhs: String) throws -> T where T: Convertible {
if let val = lhs.getKeyPath(rhs) {
do {
return try T.convert(val) as! T
}
catch {
throw MappingError.InvalidFormat
}
}
else {
throw MappingError.NilValue
}
}
public func =>?<T>(lhs: JSON, rhs: String) -> T? where T: Convertible {
return try? lhs => rhs
}
infix operator => : ConversionPrecedence
infix operator =>? : ConversionPrecedence
precedencegroup ConversionPrecedence {
associativity: left
higherThan: AssignmentPrecedence
}
| mit | 7f05c1b0169969cb74ac2b6d7070d3a5 | 19.675676 | 76 | 0.622222 | 3.923077 | false | false | false | false |
josve05a/wikipedia-ios | Wikipedia/Code/DiffListUneditedCell.swift | 2 | 1319 |
import UIKit
class DiffListUneditedCell: UICollectionViewCell {
static let reuseIdentifier = "DiffListUneditedCell"
@IBOutlet var innerLeadingConstraint: NSLayoutConstraint!
@IBOutlet var innerTrailingConstraint: NSLayoutConstraint!
@IBOutlet var innerTopConstraint: NSLayoutConstraint!
@IBOutlet var innerBottomConstraint: NSLayoutConstraint!
@IBOutlet var textLabel: UILabel!
@IBOutlet var divView: UIView!
@IBOutlet var textBackgroundView: UIView!
func update(_ viewModel: DiffListUneditedViewModel) {
innerLeadingConstraint.constant = viewModel.innerPadding.leading
innerTrailingConstraint.constant = viewModel.innerPadding.trailing
innerTopConstraint.constant = viewModel.innerPadding.top
innerBottomConstraint.constant = viewModel.innerPadding.bottom
textLabel.font = viewModel.font
textLabel.text = viewModel.text
apply(theme: viewModel.theme)
}
}
extension DiffListUneditedCell: Themeable {
func apply(theme: Theme) {
textLabel.textColor = theme.colors.secondaryText
backgroundColor = theme.colors.paperBackground
textBackgroundView.backgroundColor = theme.colors.paperBackground
divView.backgroundColor = theme.colors.border
}
}
| mit | cce396c3d0dc971b9aa97d39ecf2b6ed | 34.648649 | 74 | 0.733889 | 5.518828 | false | false | false | false |
AloneMonkey/RxSwiftStudy | RxSwiftTableViewSection/RxSwiftTableViewSection/ViewController.swift | 1 | 2315 | //
// ViewController.swift
// RxSwiftTableViewSection
//
// Created by monkey on 2017/3/28.
// Copyright © 2017年 Coder. All rights reserved.
//
import UIKit
import RxSwift
import RxCocoa
import RxDataSources
class ViewController: UIViewController {
@IBOutlet weak var tableview: UITableView!
let dataSource = RxTableViewSectionedReloadDataSource<SectionModel<String, Double>>()
let disposeBag = DisposeBag()
override func viewDidLoad() {
super.viewDidLoad()
let dataSource = self.dataSource
let items = Observable.just([
SectionModel(model: "First", items:[
1.0,
2.0,
3.0
]),
SectionModel(model: "Second", items:[
1.0,
2.0,
3.0
]),
SectionModel(model: "Third", items:[
1.0,
2.0,
3.0
])
])
dataSource.configureCell = {
(_, tv, indexPath, element) in
let cell = tv.dequeueReusableCell(withIdentifier: "Cell")!
cell.textLabel?.text = "\(element) @ row \(indexPath.row)"
return cell
}
dataSource.titleForHeaderInSection = { dataSource, sectionIndex in
return dataSource[sectionIndex].model
}
items
.bindTo(tableview.rx.items(dataSource: dataSource))
.disposed(by: disposeBag)
tableview.rx
.itemSelected
.map { indexPath in
return (indexPath, dataSource[indexPath])
}
.subscribe(onNext: { indexPath, model in
print("Tapped `\(model)` @ \(indexPath)")
})
.disposed(by: disposeBag)
tableview.rx
.setDelegate(self)
.disposed(by: disposeBag)
}
}
extension ViewController : UITableViewDelegate{
func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCellEditingStyle {
return .none
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 40
}
}
| mit | d59a2b6a0dca15bb1d171f7ee50a4dfd | 26.2 | 120 | 0.532872 | 5.5179 | false | false | false | false |
meteochu/DecisionKitchen | iOS/DecisionKitchen/User.swift | 1 | 1473 | //
// User.swift
// DecisionKitchen
//
// Created by Andy Liang on 2017-07-29.
// Copyright © 2017 Andy Liang. All rights reserved.
//
import Foundation
struct User: Codable {
var name: String
var firstName: String
var lastName: String
var id: UserID
var email: String
var img: URL
enum CodingKeys: String, CodingKey {
case name, id, email, img
case firstName = "first_name"
case lastName = "last_name"
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
name = try container.decode(String.self, forKey: .name)
firstName = try container.decode(String.self, forKey: .firstName)
lastName = try container.decode(String.self, forKey: .lastName)
id = try container.decode(String.self, forKey: .id)
email = try container.decode(String.self, forKey: .email)
img = try container.decode(URL.self, forKey: .img)
}
func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(name, forKey: .name)
try container.encode(firstName, forKey: .firstName)
try container.encode(lastName, forKey: .lastName)
try container.encode(id, forKey: .id)
try container.encode(email, forKey: .email)
try container.encode(img, forKey: .img)
}
}
| apache-2.0 | ca2bed546d3f4e32b0382855c02440b4 | 27.307692 | 73 | 0.628397 | 4.100279 | false | false | false | false |
cplaverty/KeitaiWaniKani | WaniKaniKit/Model/StudyMaterials.swift | 1 | 770 | //
// StudyMaterials.swift
// WaniKaniKit
//
// Copyright © 2017 Chris Laverty. All rights reserved.
//
public struct StudyMaterials: ResourceCollectionItemData, Equatable {
public let createdAt: Date
public let subjectID: Int
public let subjectType: SubjectType
public let meaningNote: String?
public let readingNote: String?
public let meaningSynonyms: [String]
public let isHidden: Bool
private enum CodingKeys: String, CodingKey {
case createdAt = "created_at"
case subjectID = "subject_id"
case subjectType = "subject_type"
case meaningNote = "meaning_note"
case readingNote = "reading_note"
case meaningSynonyms = "meaning_synonyms"
case isHidden = "hidden"
}
}
| mit | a685f5e0c390dcf9e47db5dc952a145b | 28.576923 | 69 | 0.676203 | 4.550296 | false | false | false | false |
Bartlebys/Bartleby | Bartleby.xOS/extensions/User+Auth.swift | 1 | 1809 | //
// User+Auth.swift
// BartlebyKit
//
// Created by Benoit Pereira da silva on 01/04/2016.
//
//
import Foundation
extension User {
/// Returns the commplete singIn URL
open func signInURL(for document:BartlebyDocument)->URL?{
let password=self.cryptoPassword
if let encoded=password.data(using: Default.STRING_ENCODING)?.base64EncodedString(){
let signin=document.baseURL.absoluteString.replacingOccurrences(of: "/api/v1", with: "")+"/signIn?spaceUID=\(document.spaceUID)&userUID=\(self.UID)&password=\(encoded)&observationUID=\(document.UID)"
return URL(string: signin)
}
return nil
}
/// Returns an encrypted hashed version of the password
open var cryptoPassword:String{
do{
let encrypted=try Bartleby.cryptoDelegate.encryptString(self.password ?? Default.NO_PASSWORD,useKey:Bartleby.configuration.KEY)
return encrypted
}catch{
return "CRYPTO_ERROR"
}
}
open func login(sucessHandler success:@escaping()->(),
failureHandler failure:@escaping(_ context: HTTPContext)->()) {
LoginUser.execute(self, sucessHandler:success, failureHandler:failure)
}
open func logout(sucessHandler success:@escaping()->(),
failureHandler failure:@escaping(_ context: HTTPContext)->()) {
LogoutUser.execute(self, sucessHandler: success, failureHandler: failure)
}
/// Returns the full phone number
open var fullPhoneNumber:String{
var prefix=""
if let match = self.phoneCountryCode.range(of:"(?<=\\()[^()]{1,10}(?=\\))", options: .regularExpression) {
prefix = String(self.phoneCountryCode[match])
}
return prefix+self.phoneNumber
}
}
| apache-2.0 | 15bae5fb1380e28b0a45a1a7cec845dd | 30.736842 | 211 | 0.63958 | 4.511222 | false | false | false | false |
auth0/Lock.iOS-OSX | LockTests/Presenters/EnterpriseActiveAuthPresenterSpec.swift | 2 | 10081 | // EnterprisePasswordPresenterSpec.swift
//
// Copyright (c) 2016 Auth0 (http://auth0.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Quick
import Nimble
import Auth0
@testable import Lock
class EnterpriseActiveAuthPresenterSpec: QuickSpec {
override func spec() {
let authentication = Auth0.authentication(clientId: clientId, domain: domain)
var interactor: EnterpriseActiveAuthInteractor!
var presenter: EnterpriseActiveAuthPresenter!
var messagePresenter: MockMessagePresenter!
var view: EnterpriseActiveAuthView!
var options: LockOptions!
var user: User!
var connection: EnterpriseConnection!
beforeEach {
options = LockOptions()
user = User()
messagePresenter = MockMessagePresenter()
connection = EnterpriseConnection(name: "TestAD", domains: ["test.com"])
interactor = EnterpriseActiveAuthInteractor(connection: connection, authentication: authentication, user: user, options: options, dispatcher: ObserverStore())
presenter = EnterpriseActiveAuthPresenter(interactor: interactor, options: options, domain: "test.com")
presenter.messagePresenter = messagePresenter
view = presenter.view as? EnterpriseActiveAuthView
}
describe("init") {
it("should have a presenter object") {
expect(presenter).toNot(beNil())
}
it("should set button title") {
expect(view.primaryButton?.title) == "LOG IN"
}
}
describe("user state") {
it("should return initial valid email") {
interactor.validEmail = true
interactor.email = email
presenter = EnterpriseActiveAuthPresenter(interactor: interactor, options: options, domain: "test.com")
let view = (presenter.view as! EnterpriseActiveAuthView).form as! CredentialView
expect(view.identityField.text).to(equal(email))
}
it("should return initial username") {
interactor.validUsername = true
interactor.username = username
presenter = EnterpriseActiveAuthPresenter(interactor: interactor, options: options, domain: "test.com")
let view = (presenter.view as! EnterpriseActiveAuthView).form as! CredentialView
expect(view.identityField.text).to(equal(username))
}
it("should expect default identifier input type to be UserName") {
let view = (presenter.view as! EnterpriseActiveAuthView).form as! CredentialView
expect(view.identityField.type).toEventually(equal(InputField.InputType.username))
}
context("use email as identifier option") {
beforeEach {
options = LockOptions()
options.activeDirectoryEmailAsUsername = true
interactor = EnterpriseActiveAuthInteractor(connection: connection, authentication: authentication, user: user, options: options, dispatcher: ObserverStore())
presenter = EnterpriseActiveAuthPresenter(interactor: interactor, options: options, domain: "test.com")
presenter.messagePresenter = messagePresenter
}
it("should expect default identifier type to be email") {
let view = (presenter.view as! EnterpriseActiveAuthView).form as! CredentialView
expect(view.identityField.type).toEventually(equal(InputField.InputType.email))
}
}
}
describe("user input") {
it("should update username if value is valid") {
let input = mockInput(.username, value: username)
view.form?.onValueChange(input)
expect(presenter.interactor.username).to(equal(username))
expect(presenter.interactor.validUsername).to(beTrue())
}
it("should hide the field error if value is valid") {
let input = mockInput(.username, value: username)
view.form?.onValueChange(input)
expect(input.valid).to(equal(true))
}
it("should show field error for empty username") {
let input = mockInput(.username, value: "")
view.form?.onValueChange(input)
expect(input.valid).to(equal(false))
}
it("should update password if value is valid") {
let input = mockInput(.password, value: password)
view.form?.onValueChange(input)
expect(presenter.interactor.password).to(equal(password))
expect(presenter.interactor.validPassword).to(beTrue())
}
it("should show field error for empty password") {
let input = mockInput(.password, value: "")
view.form?.onValueChange(input)
expect(input.valid).to(equal(false))
}
it("should not process unsupported input type") {
let input = mockInput(.oneTimePassword, value: password)
view.form?.onValueChange(input)
expect(input.valid).to(beNil())
}
context("use email as identifier option") {
beforeEach {
options = LockOptions()
options.activeDirectoryEmailAsUsername = true
interactor = EnterpriseActiveAuthInteractor(connection: connection, authentication: authentication, user: user, options: options, dispatcher: ObserverStore())
presenter = EnterpriseActiveAuthPresenter(interactor: interactor, options: options, domain: "test.com")
presenter.messagePresenter = messagePresenter
view = presenter.view as? EnterpriseActiveAuthView
}
it("should update email if value is valid") {
let input = mockInput(.email, value: email)
view.form?.onValueChange(input)
expect(presenter.interactor.email).to(equal(email))
expect(presenter.interactor.validEmail).to(beTrue())
}
it("should hide the field error if value is valid") {
let input = mockInput(.email, value: email)
view.form?.onValueChange(input)
expect(input.valid).to(equal(true))
}
it("should show field error for invalid email") {
let input = mockInput(.email, value: "invalid")
view.form?.onValueChange(input)
expect(input.valid).to(equal(false))
}
}
}
describe("login action") {
beforeEach {
options = LockOptions()
options.activeDirectoryEmailAsUsername = true
interactor = EnterpriseActiveAuthInteractor(connection: connection, authentication: authentication, user: user, options: options, dispatcher: ObserverStore())
try! interactor.update(.username, value: username)
try! interactor.update(.password(enforcePolicy: false), value: password)
presenter = EnterpriseActiveAuthPresenter(interactor: interactor, options: options, domain: "test.com")
presenter.messagePresenter = messagePresenter
view = presenter.view as? EnterpriseActiveAuthView
}
it("should not trigger action with nil button") {
let input = mockInput(.username, value: username)
input.returnKey = .done
view.primaryButton = nil
view.form?.onReturn(input)
expect(messagePresenter.message).toEventually(beNil())
expect(messagePresenter.error).toEventually(beNil())
}
it("should trigger login on button press and fail with with CouldNotLogin") {
view.primaryButton?.onPress(view.primaryButton!)
expect(messagePresenter.error).toEventually(beError(error: CredentialAuthError.couldNotLogin))
}
it("should trigger submission of form") {
let input = mockInput(.password, value: password)
input.returnKey = .done
view.form?.onReturn(input)
expect(messagePresenter.error).toEventually(beError(error: CredentialAuthError.couldNotLogin))
}
}
}
}
extension InputField.InputType: Equatable {}
public func ==(lhs: InputField.InputType, rhs: InputField.InputType) -> Bool {
switch((lhs, rhs)) {
case (.username, .username), (.email, .email), (.oneTimePassword, .oneTimePassword), (.phone, .phone):
return true
default:
return false
}
}
| mit | a1c32345eeb2f8185ba6839d68739915 | 41.716102 | 178 | 0.610753 | 5.408262 | false | false | false | false |
NUKisZ/TestKitchen_1606 | TestKitchen/TestKitchen/classes/cookbook/recommend/view/CBSubjectCell.swift | 1 | 2404 | //
// CBSubjectCell.swift
// TestKitchen
//
// Created by NUK on 16/8/23.
// Copyright © 2016年 NUK. All rights reserved.
//
import UIKit
class CBSubjectCell: UITableViewCell {
@IBOutlet weak var subjectImageView: UIImageView!
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var descLabel: UILabel!
//字数组
var dataArray :Array<CBRecommendWidgetDataModel>?{
didSet{
showData()
}
}
func showData(){
if dataArray?.count>0{
let imageModel = dataArray![0]
if imageModel.type == "image"{
let url = NSURL(string: imageModel.content!)
subjectImageView.kf_setImageWithURL(url, placeholderImage: dImage, optionsInfo: nil, progressBlock: nil, completionHandler: nil)
}
}
if dataArray?.count>1{
let titleModel = dataArray![1]
if titleModel.type == "text"{
titleLabel.text = titleModel.content
}
}
if dataArray?.count > 2{
let descModel = dataArray![2]
if descModel.type == "text"{
descLabel.text = descModel.content
}
}
}
class func createSubjectCellFor(tableView:UITableView,atIndexPath indexPath:NSIndexPath,withListModel listModel:CBRecommendWidgetListModel)->CBSubjectCell{
let cellId = "subjectCellId"
var cell = tableView.dequeueReusableCellWithIdentifier(cellId) as? CBSubjectCell
if cell == nil {
cell = NSBundle.mainBundle().loadNibNamed("CBSubjectCell", owner: nil, options: nil).last as? CBSubjectCell
}
if listModel.widget_data?.count >= indexPath.row * 3 + 3{
let array = NSArray(array: listModel.widget_data!)
let subArray = array.subarrayWithRange(NSMakeRange(indexPath.row*3, 3)) as! Array<CBRecommendWidgetDataModel>
cell?.dataArray = subArray
}
return cell!
}
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
}
}
| mit | 2424d64452d5d9430d3d5239d37a0a10 | 26.528736 | 159 | 0.581211 | 5 | false | false | false | false |
strike65/SwiftyStats | SwiftyStats/CommonSource/SpecialFunctions/Bessel/Polyeval.swift | 1 | 2799 | /*
Copyright (c) 2018 strike65
GNU GPL 3+
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, version 3 of the License.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import Foundation
/* polevl.c
* p1evl.c
*
* Evaluate polynomial
*
*
*
* SYNOPSIS:
*
* int N;
* double x, y, coef[N+1], polevl[];
*
* y = polevl( x, coef, N );
*
*
*
* DESCRIPTION:
*
* Evaluates polynomial of degree N:
*
* 2 N
* y = C + C x + C x +...+ C x
* 0 1 2 N
*
* Coefficients are stored in reverse order:
*
* coef[0] = C , ..., coef[N] = C .
* N 0
*
* The function p1evl() assumes that coef[N] = 1.0 and is
* omitted from the array. Its calling arguments are
* otherwise the same as polevl().
*
*
* SPEED:
*
* In the interest of speed, there are no checks for out
* of bounds arithmetic. This routine is used by most of
* the functions in the library. Depending on available
* equipment features, the user may wish to rewrite the
* program in microcode or assembly language.
*
*/
/*
Cephes Math Library Release 2.1: December, 1988
Copyright 1984, 1987, 1988 by Stephen L. Moshier
Direct inquiries to 30 Frost Street, Cambridge, MA 02140
*/
extension SSSpecialFunctions.Helper {
internal static func polyeval<FPT: SSFloatingPoint>( x: FPT, coef: [FPT], n: Int ) -> FPT {
var ans: FPT
var i: Int
var k: Int = 0
ans = coef[k]
k += 1
i = n
repeat {
ans = ans * x + coef[k]
k += 1
i -= 1
} while( i > 0 )
return ans
}
/* p1evl() */
/* N
* Evaluate polynomial when coefficient of x is 1.0.
* Otherwise same as polevl.
*/
internal static func poly1eval<FPT: SSFloatingPoint>( x: FPT, coef: [FPT], n: Int! ) -> FPT {
var ans: FPT
var i: Int
var k: Int = 0
ans = x + coef[k]
k += 1
i = n - 1
repeat {
ans = ans * x + coef[k]
k += 1
i -= 1
} while ( i > 0 )
return ans
}
}
| gpl-3.0 | d08dff83d95d08968535463710e93564 | 23.12931 | 97 | 0.531618 | 3.702381 | false | false | false | false |
kaphacius/react-native-chat | RNChat/iOS/ChatView.swift | 1 | 8289 | //
// ChatView.swift
// TestProject
//
// Created by Yurii Zadoianchuk on 02/05/15.
// Copyright (c) 2015 Facebook. All rights reserved.
//
import UIKit
class ChatView: RCTView, UITextViewDelegate {
var chatCollectionView: UICollectionView!
var inputToolbar: UIToolbar!
var inputTextView: UITextView!
var sendButton: UIButton!
var inputToolBarBottomConstraint: NSLayoutConstraint!
var chatDataSource: ChatDataSource!
let kToolbarHeight: CGFloat = 44.0
override init(frame: CGRect) {
super.init(frame: frame)
var layout = UICollectionViewFlowLayout()
// layout.sectionInset = UIEdgeInsets(top: 10.0, left: 10.0, bottom: 10.0, right: 10.0)
chatCollectionView = UICollectionView(frame: CGRectZero, collectionViewLayout: layout)
chatCollectionView.setTranslatesAutoresizingMaskIntoConstraints(false)
self.addSubview(chatCollectionView)
inputToolbar = UIToolbar(frame: CGRectZero)
inputToolbar.setTranslatesAutoresizingMaskIntoConstraints(false)
self.addSubview(inputToolbar)
inputTextView = UITextView(frame: CGRectZero)
inputTextView.setTranslatesAutoresizingMaskIntoConstraints(false)
inputTextView.delegate = self
self.inputToolbar.addSubview(inputTextView)
sendButton = UIButton(frame: CGRectZero)
sendButton.setTranslatesAutoresizingMaskIntoConstraints(false)
sendButton.setTitle("Send", forState: UIControlState.Normal)
sendButton.backgroundColor = UIColor.blueColor()
sendButton.sizeToFit()
self.inputToolbar.addSubview(sendButton)
var inputToolbarHeight = NSLayoutConstraint(item: inputToolbar, attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1.0, constant: kToolbarHeight)
var inputToolbarLeading = NSLayoutConstraint(item: inputToolbar, attribute: NSLayoutAttribute.Leading, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.Left, multiplier: 1.0, constant: 0.0)
var inputToolbarTrailing = NSLayoutConstraint(item: inputToolbar, attribute: NSLayoutAttribute.Trailing, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.Right, multiplier: 1.0, constant: 0.0)
inputToolBarBottomConstraint = NSLayoutConstraint(item: inputToolbar, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.Bottom, multiplier: 1.0, constant: 0.0)
self.addConstraints([inputToolbarLeading, inputToolbarTrailing, inputToolBarBottomConstraint])
inputToolbar.addConstraint(inputToolbarHeight)
var collectionViewTop = NSLayoutConstraint(item: chatCollectionView, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.Top, multiplier: 1.0, constant: 0.0);
var collectionViewBottom = NSLayoutConstraint(item: chatCollectionView, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: inputToolbar, attribute: NSLayoutAttribute.Top, multiplier: 1.0, constant: 0.0)
var collectionViewLeading = NSLayoutConstraint(item: chatCollectionView, attribute: NSLayoutAttribute.Leading, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.Left, multiplier: 1.0, constant: 0.0)
var collectionViewTrailing = NSLayoutConstraint(item: chatCollectionView, attribute: NSLayoutAttribute.Trailing, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.RightMargin, multiplier: 1.0, constant: 0.0)
self.addConstraints([collectionViewTop, collectionViewBottom, collectionViewLeading, collectionViewTrailing])
var sendButtonTop = NSLayoutConstraint(item: sendButton, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: inputToolbar, attribute: NSLayoutAttribute.Top, multiplier: 1.0, constant: 0.0)
var sendButtonBottom = NSLayoutConstraint(item: sendButton, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: inputToolbar, attribute: NSLayoutAttribute.Bottom, multiplier: 1.0, constant: 0.0)
var sendButtonTrailing = NSLayoutConstraint(item: sendButton, attribute: NSLayoutAttribute.Trailing, relatedBy: NSLayoutRelation.Equal, toItem: inputToolbar, attribute: NSLayoutAttribute.Right, multiplier: 1.0, constant: 0.0)
var sendButtonWidth = NSLayoutConstraint(item: sendButton, attribute: NSLayoutAttribute.Width, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1.0, constant: sendButton.frame.width)
inputToolbar.addConstraints([sendButtonTop, sendButtonBottom, sendButtonTrailing])
sendButton.addConstraint(sendButtonWidth)
var inputTextViewTop = NSLayoutConstraint(item: inputTextView, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: inputToolbar, attribute: NSLayoutAttribute.Top, multiplier: 1.0, constant: 0.0)
var inputTextViewBottom = NSLayoutConstraint(item: inputTextView, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: inputToolbar, attribute: NSLayoutAttribute.Bottom, multiplier: 1.0, constant: 0.0)
var inputTextViewLeading = NSLayoutConstraint(item: inputTextView, attribute: NSLayoutAttribute.Leading, relatedBy: NSLayoutRelation.Equal, toItem: inputToolbar, attribute: NSLayoutAttribute.Left, multiplier: 1.0, constant: 0.0)
var inputTextViewTrailing = NSLayoutConstraint(item: inputTextView, attribute: NSLayoutAttribute.Trailing, relatedBy: NSLayoutRelation.Equal, toItem: sendButton, attribute: NSLayoutAttribute.Left, multiplier: 1.0, constant: 0.0)
inputToolbar.addConstraints([inputTextViewTop, inputTextViewBottom, inputTextViewLeading, inputTextViewTrailing])
NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillChangeFrame:", name: UIKeyboardWillChangeFrameNotification, object: nil)
sendButton.addTarget(self, action: "sendButtonTapped", forControlEvents: UIControlEvents.TouchUpInside)
self.chatDataSource = ChatDataSource(сollectionView: self.chatCollectionView)
self.chatCollectionView.backgroundColor = UIColor.cyanColor()
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func keyboardWillChangeFrame(notification: NSNotification) {
if let ui = notification.userInfo,
let frameBeginValue = (ui[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.CGRectValue(),
let frameEndValue = (ui[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.CGRectValue(),
let duration = (ui[UIKeyboardAnimationDurationUserInfoKey] as? NSNumber)?.doubleValue,
let curveInt = (ui[UIKeyboardAnimationCurveUserInfoKey] as? NSNumber)?.intValue,
let curve = UIViewAnimationCurve(rawValue: Int(curveInt)) {
self .animateInputToolbarWithYPosDiff(frameBeginValue.origin.y - frameEndValue.origin.y, duration: duration, animationCurve: curve)
}
}
func sendButtonTapped() {
if true == inputTextView.isFirstResponder() {
inputTextView.resignFirstResponder()
var message = ChatMessage(isAuthor: true, date: NSDate(), message: inputTextView.text)
chatDataSource.addMessage(message)
}
}
func textView(textView: UITextView, shouldChangeTextInRange range: NSRange, replacementText text: String) -> Bool {
if text == "\n" {
textView.resignFirstResponder()
return false
}
return true
}
func animateInputToolbarWithYPosDiff(yPosDiff: CGFloat, duration: Double, animationCurve: UIViewAnimationCurve) {
var option = UInt(animationCurve.rawValue << 16)
UIView.animateWithDuration(duration, delay: 0.0, options: UIViewAnimationOptions(option), animations: { () -> Void in
self.inputToolBarBottomConstraint.constant -= yPosDiff
self.layoutIfNeeded()
}, completion: nil)
}
}
| mit | 6bb6f7d33ef3eeafccfa6dd69ee2cc57 | 71.069565 | 246 | 0.750483 | 5.445466 | false | false | false | false |
WCByrne/CBToolkit | CBToolkit/CBToolkit/CBCollectionViewLayout.swift | 1 | 25777 | //
// CHTCollectionViewWaterfallLayout.swift
// PinterestSwift
//
// Created by Nicholas Tau on 6/30/14.
// Copyright (c) 2014 Nicholas Tau. All rights reserved.
//
import Foundation
import UIKit
extension CGPoint {
func add(point: CGPoint) -> CGPoint {
return CGPoint(x: self.x + point.x, y: self.y + point.y)
}
}
/**
* The delegate for CBCollectionViewLayout
*/
@objc public protocol CBCollectionViewDelegateLayout: UICollectionViewDelegate {
/**
The height for the item at the given indexPath (Priority 2)
- parameter collectionView: The collection view the item is in
- parameter collectionViewLayout: The CollectionViewLayout
- parameter indexPath: The indexPath for the item
- returns: The height for the item
*/
@objc optional func collectionView (_ collectionView: UICollectionView,layout collectionViewLayout: UICollectionViewLayout,
heightForItemAtIndexPath indexPath: IndexPath) -> CGFloat
/**
The aspect ration for the item at the given indexPath (Priority 1). Width and height must be greater than 0.
- parameter collectionView: The collection view the item is in
- parameter collectionViewLayout: The CollectionViewLayout
- parameter indexPath: The indexPath for the item
- returns: The aspect ration for the item
*/
@objc optional func collectionView (_ collectionView: UICollectionView,layout collectionViewLayout: UICollectionViewLayout,
aspectRatioForItemAtIndexPath indexPath: IndexPath) -> CGSize
@objc optional func collectionView (_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout,
heightForHeaderInSection section: NSInteger) -> CGFloat
@objc optional func collectionView (_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout,
heightForFooterInSection section: NSInteger) -> CGFloat
@objc optional func collectionView (_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout,
numberOfColumnsInSection section: Int) -> Int
@objc optional func collectionView (_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout,
insetForSectionAtIndex section: NSInteger) -> UIEdgeInsets
// Between to items in the same column
@objc optional func collectionView (_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout,
minimumInteritemSpacingForSectionAtIndex section: NSInteger) -> CGFloat
@objc optional func collectionview(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout,
minimumColumnSpacingForSectionAtIndex: NSInteger) -> CGFloat
/*!
Tells the delegate that a cell is about to be moved. Optionally cancelling or redirecting the move to a new indexPath. If the current indexPath is returned the cell will not be moved. If any other indexpath is returned the cell will be moved there. The datasource should be updated during this call.
:param: collectionView The collection view
:param: collectionViewLayout The CollectionViewLayout
:param: sourceIndexPath The original position of the cell when dragging began
:param: currentIndexPath The current position of the cell
:param: proposedIndexPath The proposed new position of the cell
:returns: The indexPath that the cell should be moved to.
*/
@objc optional func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout,
shouldMoveItemAtIndexPath originalIndexPath: IndexPath,
currentIndexPath : IndexPath,
toProposedIndexPath proposedIndexPath: IndexPath) -> IndexPath
@objc optional func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout,
didFinishMovingCellFrom originalIndexPath: IndexPath, finalIndexPath: IndexPath)
}
@objc public protocol CBCollectionViewDataSource: UICollectionViewDataSource {
@objc optional func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout,
canMoveItemAtIndexPath indexPath: IndexPath) -> Bool
@objc optional func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout,
moveItemAtIndexPath sourceIndexPath: IndexPath, toIndexPath : IndexPath)
}
public enum CBCollectionViewLayoutItemRenderDirection : NSInteger {
case ShortestFirst
case LeftToRight
case RightToLeft
}
public struct CBCollectionViewLayoutElementKind {
public static let SectionHeader: String = "CBCollectionElementKindSectionHeader"
public static let SectionFooter: String = "CBCollectionElementKindSectionFooter"
}
/// A feature packed collection view layout with pinterest like layouts, aspect ratio sizing, and drag and drop.
public class CBCollectionViewLayout : UICollectionViewLayout, UIGestureRecognizerDelegate {
//MARK: - Default layout values
/// The default column count
public var columnCount : NSInteger = 2 {
didSet{
invalidateLayout()
}}
/// The spacing between each column
public var minimumColumnSpacing : CGFloat = 8 {
didSet{
invalidateLayout()
}}
/// The vertical spacing between items in the same column
public var minimumInteritemSpacing : CGFloat = 8 {
didSet{
invalidateLayout()
}}
/// The height of section header views
public var headerHeight : CGFloat = 0.0 {
didSet{
invalidateLayout()
}}
/// The height of section footer views
public var footerHeight : CGFloat = 0.0 {
didSet{
invalidateLayout()
}}
/// The default height to apply to all items
public var defaultItemHeight : CGFloat = 50 {
didSet{
invalidateLayout()
}}
/// Default insets for all sections
public var sectionInset : UIEdgeInsets = UIEdgeInsets(top: 8, left: 8, bottom: 8, right: 8) {
didSet{
invalidateLayout()
}}
// MARK: - Render Options
/// A hint as to how to render items when deciding which column to place them in
public var itemRenderDirection : CBCollectionViewLayoutItemRenderDirection = .LeftToRight {
didSet{
invalidateLayout()
}}
private var _itemWidth : CGFloat = 0
/// the calculated width of items based on the total width and number of columns (read only)
public var itemWidth : CGFloat {
get {
return _itemWidth
}
}
private var numSections : Int { get { return self.collectionView!.numberOfSections }}
private func columns(in section: Int) -> Int {
return self.delegate?.collectionView?(self.collectionView!, layout: self, numberOfColumnsInSection: section) ?? self.columnCount
}
private var longPressGesture : UILongPressGestureRecognizer?
private var panGesture : UIPanGestureRecognizer?
private var dragView : UIView?
private var initialPosition : CGPoint! = CGPoint.zero
private var selectedIndexPath : IndexPath?
private var targetIndexPath: IndexPath?
/// Enable drag and drop
public var dragEnabled : Bool = false {
didSet {
if longPressGesture == nil {
longPressGesture = UILongPressGestureRecognizer(target: self, action: #selector(CBCollectionViewLayout.handleLongPress(gesture:)))
longPressGesture?.delegate = self
panGesture = UIPanGestureRecognizer(target: self, action: #selector(CBCollectionViewLayout.handlePanGesture(gesture:)))
panGesture?.maximumNumberOfTouches = 1
panGesture?.delegate = self
if let gestures = self.collectionView!.gestureRecognizers {
for gesture in gestures {
if let g = gesture as? UILongPressGestureRecognizer {
g.require(toFail: longPressGesture!)
}
}
}
collectionView!.addGestureRecognizer(longPressGesture!)
collectionView!.addGestureRecognizer(panGesture!)
}
self.panGesture?.isEnabled = dragEnabled
self.longPressGesture?.isEnabled = dragEnabled
if !dragEnabled {
dragView?.removeFromSuperview()
dragView = nil
selectedIndexPath = nil
}
}
}
// private property and method above.
private weak var delegate : CBCollectionViewDelegateLayout?{ get{ return self.collectionView!.delegate as? CBCollectionViewDelegateLayout }}
private weak var dataSource : CBCollectionViewDataSource? { get { return self.collectionView!.dataSource as? CBCollectionViewDataSource }}
private var columnHeights : [[CGFloat]]! = []
private var sectionItemAttributes : [[UICollectionViewLayoutAttributes]] = []
private var allItemAttributes : [UICollectionViewLayoutAttributes] = []
private var headersAttributes : [Int:UICollectionViewLayoutAttributes] = [:]
private var footersAttributes : [Int:UICollectionViewLayoutAttributes] = [:]
private var unionRects = [CGRect]()
private let unionSize = 20
override public init() {
super.init()
}
/**
Initialize the layout with a collectionView
- parameter collectionView: The collectionView to apply the layout to
- returns: The intialized layout
*/
convenience public init(collectionView: UICollectionView!) {
self.init()
collectionView.collectionViewLayout = self
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
public func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
if gestureRecognizer.isEqual(panGesture) { return selectedIndexPath != nil }
return true
}
public func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
if gestureRecognizer.isEqual(longPressGesture) {
return otherGestureRecognizer.isEqual(panGesture)
}
if gestureRecognizer.isEqual(panGesture) {
return otherGestureRecognizer.isEqual(longPressGesture)
}
return false
}
@objc func handleLongPress(gesture: UILongPressGestureRecognizer) {
if gesture.state == .began {
let indexPath = self.collectionView?.indexPathForItem(at: gesture.location(in: self.collectionView!))
if indexPath == nil { return }
let canMove = self.dataSource?.collectionView?(self.collectionView!, layout: self, canMoveItemAtIndexPath: indexPath!) ?? true
if canMove == false { return }
self.selectedIndexPath = indexPath
let cell = self.collectionView!.cellForItem(at: indexPath!)!
dragView = cell.snapshotView(afterScreenUpdates: false)
self.collectionView!.addSubview(dragView!)
initialPosition = cell.center
dragView!.frame = cell.frame
UIView.animate(withDuration: 0.5, animations: { () -> Void in
self.dragView!.transform = CGAffineTransform(scaleX: 1.05, y: 1.05)
cell.alpha = 0.3
})
}
// If long press ends and pan was never started, return the view to it's pace
else if panGesture!.state != .possible && (gesture.state == .ended || gesture.state == .cancelled){
finishDrag(velocity: nil)
}
}
@objc func handlePanGesture(gesture: UIPanGestureRecognizer) {
// just for
if selectedIndexPath == nil { return }
if gesture.state == .changed || gesture.state == .began {
let offset = gesture.translation(in: self.collectionView!)
let newCenter = initialPosition.add(point: offset)
dragView?.center = newCenter
let newIP = self.collectionView!.indexPathForItem(at: newCenter)
if newIP == nil { return }
let currentIP = targetIndexPath ?? selectedIndexPath!
if newIP == currentIP { return }
let adjustedIP = self.delegate?.collectionView?(self.collectionView!, layout: self,
shouldMoveItemAtIndexPath: self.selectedIndexPath!,
currentIndexPath : currentIP,
toProposedIndexPath: newIP!) ?? newIP!
if adjustedIP == currentIP { return }
self.targetIndexPath = adjustedIP
self.dataSource?.collectionView?(self.collectionView!, layout: self, moveItemAtIndexPath: currentIP, toIndexPath: adjustedIP)
}
else if gesture.state == .ended {
finishDrag(velocity: gesture.velocity(in: self.collectionView!))
}
}
func finishDrag(velocity: CGPoint?) {
if dragView == nil { return }
let finalIndexPath = targetIndexPath ?? selectedIndexPath!
let attr = self.layoutAttributesForItem(at: finalIndexPath as IndexPath)
let oldView = dragView!
dragView = nil
if finalIndexPath != selectedIndexPath {
self.delegate?.collectionView?(self.collectionView!, layout: self, didFinishMovingCellFrom: selectedIndexPath!, finalIndexPath: finalIndexPath)
}
self.selectedIndexPath = nil
self.targetIndexPath = nil
// let v = velocity ?? CGPoint.zero
let cell = self.collectionView?.cellForItem(at: finalIndexPath as IndexPath)
UIView.animate(withDuration: 0.35, delay: 0, usingSpringWithDamping: 0.95, initialSpringVelocity: 0, options: UIViewAnimationOptions.beginFromCurrentState, animations: { () -> Void in
oldView.frame = attr!.frame
cell?.alpha = 1
}, completion: { (fin) -> Void in
// cell?.hidden = false
oldView.removeFromSuperview()
})
}
func itemWidthInSectionAtIndex (section : NSInteger) -> CGFloat {
let colCount = self.delegate?.collectionView?(self.collectionView!, layout: self, numberOfColumnsInSection: section) ?? self.columnCount
var insets : UIEdgeInsets!
if let sectionInsets = self.delegate?.collectionView?(self.collectionView!, layout: self, insetForSectionAtIndex: section){
insets = sectionInsets
}else{
insets = self.sectionInset
}
let width:CGFloat = self.collectionView!.bounds.size.width - insets.left - insets.right
let spaceColumCount:CGFloat = CGFloat(colCount-1)
return floor((width - (spaceColumCount*self.minimumColumnSpacing)) / CGFloat(colCount))
}
override public func prepare(){
super.prepare()
let numberOfSections = self.collectionView!.numberOfSections
if numberOfSections == 0 {
return
}
self.headersAttributes.removeAll()
self.footersAttributes.removeAll(keepingCapacity: false)
self.unionRects.removeAll()
self.columnHeights.removeAll(keepingCapacity: false)
self.allItemAttributes.removeAll()
self.sectionItemAttributes.removeAll()
// Create default column heights for each section
for sec in 0...self.numSections-1 {
let colCount = self.columns(in: sec)
columnHeights.append([CGFloat](repeating: 0, count: colCount))
}
var top : CGFloat = 0.0
// var attributes = UICollectionViewLayoutAttributes()
for section in 0..<numberOfSections {
/*
* 1. Get section-specific metrics (minimumInteritemSpacing, sectionInset)
*/
let colCount = self.delegate?.collectionView?(self.collectionView!, layout: self, numberOfColumnsInSection: section) ?? self.columnCount
let sectionInsets : UIEdgeInsets = self.delegate?.collectionView?(self.collectionView!, layout: self, insetForSectionAtIndex: section) ?? self.sectionInset
let itemSpacing : CGFloat = self.delegate?.collectionView?(self.collectionView!, layout: self, minimumInteritemSpacingForSectionAtIndex: section) ?? self.minimumInteritemSpacing
let colSpacing = self.delegate?.collectionview?(self.collectionView!, layout: self, minimumColumnSpacingForSectionAtIndex: section) ?? self.minimumColumnSpacing
let contentWidth = self.collectionView!.bounds.size.width - sectionInsets.left - sectionInsets.right
let spaceColumCount = CGFloat(colCount-1)
let itemWidth = floor((contentWidth - (spaceColumCount*colSpacing)) / CGFloat(colCount))
_itemWidth = itemWidth
/*
* 2. Section header
*/
let heightHeader : CGFloat = self.delegate?.collectionView?(self.collectionView!, layout: self, heightForHeaderInSection: section) ?? self.headerHeight
if heightHeader > 0 {
let attributes = UICollectionViewLayoutAttributes(forSupplementaryViewOfKind: CBCollectionViewLayoutElementKind.SectionHeader, with: IndexPath(item: 0, section: section))
attributes.frame = CGRect(x: 0, y: top, width: self.collectionView!.bounds.size.width, height: heightHeader)
self.headersAttributes[section] = attributes
self.allItemAttributes.append(attributes)
top = attributes.frame.maxY
}
top += sectionInsets.top
for idx in 0..<colCount {
self.columnHeights[section][idx] = top;
}
/*
* 3. Section items
*/
let itemCount = self.collectionView!.numberOfItems(inSection: section)
var itemAttributes : [UICollectionViewLayoutAttributes] = []
// Item will be put into shortest column.
for idx in 0..<itemCount {
let indexPath = IndexPath(item: idx, section: section)
let columnIndex = self.nextColumn(forItem: indexPath)
let xOffset = sectionInsets.left + (itemWidth + colSpacing) * CGFloat(columnIndex)
let yOffset = self.columnHeights[section][columnIndex]
var itemHeight : CGFloat = 0
let aSize = self.delegate?.collectionView?(self.collectionView!, layout: self, aspectRatioForItemAtIndexPath: indexPath)
if aSize != nil && aSize!.width != 0 && aSize!.height != 0 {
let h = aSize!.height * (itemWidth/aSize!.width)
itemHeight = floor(h)
}
else {
itemHeight = self.delegate?.collectionView?(self.collectionView!, layout: self, heightForItemAtIndexPath: indexPath) ?? self.defaultItemHeight
}
let attributes = UICollectionViewLayoutAttributes(forCellWith: indexPath)
attributes.alpha = indexPath == targetIndexPath ? 0.3 : 1
attributes.frame = CGRect(x: xOffset, y: CGFloat(yOffset), width: itemWidth, height: itemHeight)
itemAttributes.append(attributes)
self.allItemAttributes.append(attributes)
self.columnHeights[section][columnIndex] = attributes.frame.maxY + itemSpacing;
}
self.sectionItemAttributes.append(itemAttributes)
/*
* 4. Section footer
*/
let columnIndex = self.longestColumn(in: section)
top = self.columnHeights[section][columnIndex] - itemSpacing + sectionInsets.bottom
let footerHeight = self.delegate?.collectionView?(self.collectionView!, layout: self, heightForFooterInSection: section) ?? self.footerHeight
if footerHeight > 0 {
let attributes = UICollectionViewLayoutAttributes (forSupplementaryViewOfKind: CBCollectionViewLayoutElementKind.SectionFooter, with: IndexPath(item: 0, section: section))
attributes.frame = CGRect(x: 0, y: top, width: self.collectionView!.bounds.size.width, height:footerHeight)
self.footersAttributes[section] = attributes
self.allItemAttributes.append(attributes)
top = attributes.frame.maxY
}
for idx in 0..<colCount {
self.columnHeights[section][idx] = top
}
}
var idx = 0;
let itemCounts = self.allItemAttributes.count
while(idx < itemCounts){
let rect1 = self.allItemAttributes[idx].frame as CGRect
idx = min(idx + unionSize, itemCounts) - 1
let rect2 = self.allItemAttributes[idx].frame as CGRect
self.unionRects.append(rect1.union(rect2))
idx += 1
}
}
override public var collectionViewContentSize : CGSize{
let numberOfSections = self.collectionView!.numberOfSections
if numberOfSections == 0{
return CGSize.zero
}
var contentSize = self.collectionView!.bounds.size as CGSize
let height = self.columnHeights.last?.first ?? 0
contentSize.height = CGFloat(height)
return contentSize
}
public override func layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? {
if indexPath.section >= self.sectionItemAttributes.count{
return nil
}
if indexPath.item >= self.sectionItemAttributes[indexPath.section].count{
return nil;
}
let list = self.sectionItemAttributes[indexPath.section]
return list[indexPath.item]
}
public override func layoutAttributesForSupplementaryView(ofKind elementKind: String, at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? {
var attribute = UICollectionViewLayoutAttributes()
if elementKind == CBCollectionViewLayoutElementKind.SectionHeader {
attribute = self.headersAttributes[indexPath.section]!
} else if elementKind == CBCollectionViewLayoutElementKind.SectionFooter {
attribute = self.footersAttributes[indexPath.section]!
}
return attribute
}
override public func layoutAttributesForElements (in rect : CGRect) -> [UICollectionViewLayoutAttributes] {
var attrs = [UICollectionViewLayoutAttributes]()
for attr in allItemAttributes {
if attr.frame.intersects(rect) {
attrs.append(attr)
}
}
return attrs
/*
// This logic is flawed, the temporary fix above is not the more efficient solution
var begin = 0, end = self.unionRects.count
for i in 0..<end {
if rect.intersects(unionRects[i]){
begin = i * unionSize;
break
}
}
for i in stride(from: self.unionRects.count - 1, through: 0, by: -1) {
if rect.intersects(unionRects[i]){
end = min((i+1)*unionSize,self.allItemAttributes.count)
break
}
}
for i in begin..<end {
let attr = self.allItemAttributes[i]
if rect.intersects(attr.frame) {
attrs.append(attr)
}
}
return attrs
*/
}
override public func shouldInvalidateLayout (forBoundsChange newBounds : CGRect) -> Bool {
let oldBounds = self.collectionView!.bounds
if newBounds.width != oldBounds.width{
return true
}
return false
}
/*!
Find the shortest column in a particular section
:param: section The section to find the shortest column for.
:returns: The index of the shortest column in the given section
*/
func shortestColumn(in section: Int) -> NSInteger {
let min = self.columnHeights[section].min()!
return self.columnHeights[section].index(of: min)!
}
/*!
Find the longest column in a particular section
:param: section The section to find the longest column for.
:returns: The index of the longest column in the given section
*/
func longestColumn(in section: Int) -> NSInteger {
let max = self.columnHeights[section].max()!
return self.columnHeights[section].index(of: max)!
}
/*!
Find the index of the column the for the next item at the given index path
:param: The indexPath of the section to look ahead of
:returns: The index of the next column
*/
func nextColumn(forItem atIndexPath : IndexPath) -> Int {
let colCount = self.delegate?.collectionView?(self.collectionView!, layout: self, numberOfColumnsInSection: atIndexPath.section) ?? self.columnCount
var index = 0
switch (self.itemRenderDirection){
case .ShortestFirst :
index = self.shortestColumn(in: atIndexPath.section)
case .LeftToRight :
index = (atIndexPath.item%colCount)
case .RightToLeft:
index = (colCount - 1) - (atIndexPath.item % colCount);
}
return index
}
}
| mit | dab62e626fd043cc2816a76fd316f6dd | 42.468803 | 303 | 0.648446 | 5.681508 | false | false | false | false |
Bouke/HAP | Sources/HAP/Server/ChannelHandlers.swift | 1 | 12543 | import Crypto
import Dispatch
import Foundation
import Logging
import NIO
import NIOHTTP1
import VaporHTTP
fileprivate let logger = Logger(label: "hap.nio")
enum CryptographyEvent {
case sharedKey(Data)
}
class CryptographerHandler: ChannelDuplexHandler {
typealias InboundIn = ByteBuffer
typealias InboundOut = ByteBuffer
typealias OutboundIn = ByteBuffer
typealias OutboundOut = ByteBuffer
var cryptographer: Cryptographer
var cumulationBuffer: ByteBuffer?
init(_ cryptographer: Cryptographer) {
self.cryptographer = cryptographer
}
func channelRead(context: ChannelHandlerContext, data: NIOAny) {
var buffer = unwrapInboundIn(data)
if cumulationBuffer == nil {
cumulationBuffer = buffer
} else {
cumulationBuffer!.writeBuffer(&buffer)
}
repeat {
let startIndex = cumulationBuffer!.readerIndex
guard let length = cumulationBuffer!.readInteger(endianness: Endianness.little, as: Int16.self) else {
return // not enough bytes available
}
cumulationBuffer!.moveReaderIndex(to: startIndex)
guard 2 + length + 16 <= cumulationBuffer!.readableBytes else {
return // not enough bytes available
}
readOneFrame(context: context, length: Int(length))
} while cumulationBuffer != nil
}
func readOneFrame(context: ChannelHandlerContext, length: Int) {
let lengthBytes = cumulationBuffer!.readSlice(length: 2)!
let cyphertext = cumulationBuffer!.readSlice(length: length)!
let tag = cumulationBuffer!.readSlice(length: 16)!
var message: Data
do {
message = try cryptographer.decrypt(lengthBytes: lengthBytes.readableBytesView,
ciphertext: cyphertext.readableBytesView,
tag: tag.readableBytesView)
} catch {
// swiftlint:disable:next line_length
logger.warning("Could not decrypt message from \(context.remoteAddress?.description ?? "???"): \(error), closing connection.")
cumulationBuffer!.clear()
context.close(promise: nil)
return
}
context.fireChannelRead(wrapInboundOut(ByteBuffer(data: message)))
if cumulationBuffer!.readableBytes == 0 {
cumulationBuffer = nil
}
}
func write(context: ChannelHandlerContext, data: NIOAny, promise: EventLoopPromise<Void>?) {
var buffer = unwrapOutboundIn(data)
while buffer.readableBytes > 0 {
writeOneFrame(context: context, buffer: &buffer, promise: promise)
}
}
func writeOneFrame(context: ChannelHandlerContext, buffer: inout ByteBuffer, promise: EventLoopPromise<Void>?) {
let length = min(1024, buffer.readableBytes)
let frame = buffer.readSlice(length: length)!
var cipher: Data
do {
cipher = try cryptographer.encrypt(plaintext: frame)
} catch {
// swiftlint:disable:next line_length
logger.warning("Could not decrypt message from \(context.remoteAddress?.description ?? "???"): \(error), closing connection.")
buffer.clear()
context.close(promise: nil)
return
}
if buffer.readableBytes > 0 {
context.write(wrapOutboundOut(ByteBuffer(data: cipher)), promise: nil)
} else {
context.write(wrapOutboundOut(ByteBuffer(data: cipher)), promise: promise)
}
}
}
class EventHandler: ChannelOutboundHandler {
typealias OutboundIn = ByteBuffer
typealias OutboundOut = ByteBuffer
var pendingNotifications: [Characteristic] = []
var pendingPromises: [EventLoopPromise<Void>] = []
var nextAllowableNotificationTime = Date()
func triggerUserOutboundEvent(context: ChannelHandlerContext, event: Any, promise: EventLoopPromise<Void>?) {
if case let CharacteristicEvent.changed(characteristic) = event {
pendingNotifications.append(characteristic)
if let promise = promise {
pendingPromises.append(promise)
}
// We don't send notifications immediately to allow a small window
// to receive additional events, otherwise those events would have
// to wait for the next opportunity.
_ = context.eventLoop.scheduleTask(in: TimeAmount.milliseconds(5)) {
self.writePendingNotifications(context: context)
}
} else {
context.triggerUserOutboundEvent(event, promise: promise)
}
}
func writePendingNotifications(context: ChannelHandlerContext) {
/* HAP Specification 5.8 (excerpts)
Network-based notifications must be coalesced
by the accessory using a delay of no less than 1 second.
Excessive or inappropriate notifications may result
in the user being notified of a misbehaving
accessory and/or termination of the pairing relationship.
*/
if pendingNotifications.isEmpty {
return
}
if nextAllowableNotificationTime > Date() {
let waitms = nextAllowableNotificationTime.timeIntervalSinceNow * 1000
_ = context.eventLoop.scheduleTask(in: TimeAmount.milliseconds(Int64(waitms))) {
self.writePendingNotifications(context: context)
}
return
}
// swiftlint:disable:next line_length
logger.debug("Writing \(self.pendingNotifications.count) notification to \(context.remoteAddress?.description ?? "N/A")")
guard let event = try? Event(valueChangedOfCharacteristics: pendingNotifications) else {
// swiftlint:disable:next line_length
logger.warning("Could not serialize events for \(context.remoteAddress?.description ?? "N/A"), closing connection.")
return
}
let serialized = event.serialized()
var buffer = context.channel.allocator.buffer(capacity: serialized.count)
buffer.writeBytes(serialized)
context.writeAndFlush(wrapOutboundOut(buffer), promise: nil)
for promise in pendingPromises {
promise.succeed(())
}
pendingNotifications = []
nextAllowableNotificationTime = Date(timeIntervalSinceNow: 1)
}
}
enum PairingEvent {
case verified(Pairing)
}
enum CharacteristicEvent {
case changed(Characteristic)
}
class ControllerHandler: ChannelDuplexHandler {
typealias InboundIn = HTTPServerRequestPart
typealias OutboundIn = HTTPServerResponsePart
// All access to channels is guarded by channelsSyncQueue.
private let channelsSyncQueue = DispatchQueue(label: "channelsQueue")
private var channels: [ObjectIdentifier: Channel] = [:]
private var pairings: [ObjectIdentifier: Pairing] = [:]
// TODO: tighter integration into Device.
internal var removeSubscriptions: ((Channel) -> Void)?
func channelActive(context: ChannelHandlerContext) {
let channel = context.channel
var channelsCount = 0
channelsSyncQueue.sync {
self.channels[ObjectIdentifier(channel)] = channel
channelsCount = self.channels.count
}
logger.info(
"""
Controller \(channel.remoteAddress?.description ?? "N/A") connected, \
\(channelsCount) controllers total
""")
context.fireChannelActive()
}
func channelInactive(context: ChannelHandlerContext) {
let channel = context.channel
var channelsCount = 0
channelsSyncQueue.sync {
self.channels.removeValue(forKey: ObjectIdentifier(channel))
self.pairings.removeValue(forKey: ObjectIdentifier(channel))
channelsCount = self.channels.count
}
self.removeSubscriptions?(channel)
logger.info(
"""
Controller \(channel.remoteAddress?.description ?? "N/A") disconnected, \
\(channelsCount) controllers total
""")
context.fireChannelInactive()
}
func triggerUserOutboundEvent(context: ChannelHandlerContext, event: Any, promise: EventLoopPromise<Void>?) {
if case let PairingEvent.verified(pairing) = event {
let channel = context.channel
registerPairing(pairing, forChannel: channel)
} else {
context.triggerUserOutboundEvent(event, promise: promise)
}
}
func isChannelVerified(channel: Channel) -> Bool {
channelsSyncQueue.sync {
pairings.keys.contains(ObjectIdentifier(channel))
}
}
func notifyChannel(identifier: ObjectIdentifier, ofCharacteristicChange characteristic: Characteristic) {
channelsSyncQueue.sync {
guard let channel = self.channels[identifier] else {
// todo... probably need to clean up?
logger.error("event for non-existing channel")
return
}
channel.triggerUserOutboundEvent(CharacteristicEvent.changed(characteristic), promise: nil)
}
}
func getPairingForChannel(_ channel: Channel) -> Pairing? {
channelsSyncQueue.sync {
self.pairings[ObjectIdentifier(channel)]
}
}
func registerPairing(_ pairing: Pairing, forChannel channel: Channel) {
channelsSyncQueue.sync {
self.pairings[ObjectIdentifier(channel)] = pairing
}
}
func disconnectPairing(_ pairing: Pairing) {
var channelsToClose = [Channel]()
channelsSyncQueue.sync {
let channelIdentifiers = pairings.filter { $0.value.identifier == pairing.identifier }.keys
channelsToClose = channelIdentifiers.compactMap({ channels[$0] })
}
for channel in channelsToClose {
// This will trigger `channelInactive(context:)`.
channel.close(promise: nil)
}
}
}
class CryptographerInstallerHandler: ChannelOutboundHandler, RemovableChannelHandler {
typealias OutboundIn = HTTPResponse
typealias OutboundOut = HTTPResponse
var newCryptographer: Cryptographer?
func write(context: ChannelHandlerContext, data: NIOAny, promise: EventLoopPromise<Void>?) {
guard let cryptographer = newCryptographer else {
return context.write(data, promise: promise)
}
context.write(data).whenSuccess {
promise?.succeed(())
context.pipeline.addHandler(CryptographerHandler(cryptographer), position: .first)
context.pipeline.removeHandler(self)
}
}
func triggerUserOutboundEvent(context: ChannelHandlerContext, event: Any, promise: EventLoopPromise<Void>?) {
if case let CryptographyEvent.sharedKey(sharedKey) = event {
newCryptographer = Cryptographer(sharedSecret: SymmetricKey(data: sharedKey))
promise?.succeed(())
} else {
context.triggerUserOutboundEvent(event, promise: promise)
}
}
}
typealias Responder = (RequestContext, HTTPRequest) -> EventLoopFuture<HTTPResponse>
class ApplicationHandler: ChannelInboundHandler {
typealias InboundIn = HTTPRequest
typealias OutboundOut = HTTPResponse
let responder: Responder
init(responder: @escaping Responder) {
self.responder = responder
}
func channelRead(context: ChannelHandlerContext, data: NIOAny) {
let request = unwrapInboundIn(data)
let response = responder(context, request)
response.whenSuccess { response in
context.write(self.wrapOutboundOut(response), promise: nil)
}
}
}
protocol RequestContext {
var channel: Channel { get }
func triggerUserOutboundEvent(_ event: Any, promise: EventLoopPromise<Void>?)
var session: SessionHandler { get }
}
extension ChannelHandlerContext: RequestContext {
var session: SessionHandler {
// swiftlint:disable:next force_try
try! pipeline.syncOperations.handler(type: SessionHandler.self)
}
}
class SessionHandler: ChannelDuplexHandler {
typealias InboundIn = HTTPServerRequestPart
typealias OutboundIn = HTTPServerResponsePart
var storage = [String: AnyObject]()
init() { }
subscript(index: String) -> AnyObject? {
get { storage[index] }
set { storage[index] = newValue }
}
}
| mit | 70d0cc03fee44b1c04db64a305d8718a | 34.735043 | 138 | 0.649845 | 5.134261 | false | false | false | false |
Asura19/My30DaysOfSwift | WikiFace/Carthage/Checkouts/SwiftyJSON/Tests/SwiftyJSONTests/PerformanceTests.swift | 9 | 3886 | // PerformanceTests.swift
//
// Copyright (c) 2014 - 2017 Pinglin Tang
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import XCTest
import SwiftyJSON
class PerformanceTests: XCTestCase {
var testData: Data!
override func setUp() {
super.setUp()
if let file = Bundle(for:PerformanceTests.self).path(forResource: "Tests", ofType: "json") {
self.testData = try? Data(contentsOf: URL(fileURLWithPath: file))
} else {
XCTFail("Can't find the test JSON file")
}
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testInitPerformance() {
self.measure() {
for _ in 1...100 {
let json = JSON(data:self.testData)
XCTAssertTrue(json != JSON.null)
}
}
}
func testObjectMethodPerformance() {
let json = JSON(data:self.testData)
self.measure() {
for _ in 1...100 {
let object:Any? = json.object
XCTAssertTrue(object != nil)
}
}
}
func testArrayMethodPerformance() {
let json = JSON(data:self.testData)
self.measure() {
for _ in 1...100 {
autoreleasepool{
if let array = json.array {
XCTAssertTrue(array.count > 0)
}
}
}
}
}
func testDictionaryMethodPerformance() {
let json = JSON(data:testData)[0]
self.measure() {
for _ in 1...100 {
autoreleasepool{
if let dictionary = json.dictionary {
XCTAssertTrue(dictionary.count > 0)
}
}
}
}
}
func testRawStringMethodPerformance() {
let json = JSON(data:testData)
self.measure() {
for _ in 1...100 {
autoreleasepool{
let string = json.rawString()
XCTAssertTrue(string != nil)
}
}
}
}
func testLargeDictionaryMethodPerformance() {
var data: [String: JSON] = [:]
(0...100000).forEach { n in
data["\(n)"] = JSON([
"name": "item\(n)",
"id": n
])
}
let json = JSON(data)
self.measure() {
autoreleasepool{
if let dictionary = json.dictionary {
XCTAssertTrue(dictionary.count > 0)
} else {
XCTFail("dictionary should not be nil")
}
}
}
}
}
| mit | 12010c7ffd34f837360339e2f1a1ff0a | 30.852459 | 111 | 0.543747 | 4.88805 | false | true | false | false |
DY-Lee/MicroBlog | Sina/Sina/Classes/View/Main/未命名文件夹/WBVistorView.swift | 1 | 13186 | //
// WBVistorView.swift
// Sina
//
// Created by Macintosh HD on 16/8/20.
// Copyright © 2016年 lidingyuan. All rights reserved.
//
import UIKit
class WBVistorView: UIView {
//设置访客视图信息
var infoDict : [String : String]?{
didSet{
guard let imageName = infoDict?["imageName"],
message = infoDict?["message"] else {
return
}
//首页直接返回
tipLabel.text = message
if imageName == "" {
return
}
//其他视图不需要小房子/背景阴影
houseIconView.image = UIImage(named: imageName)
maskIconView.hidden = true
iconView.hidden = true
tipLabel.textAlignment = .Center
}
}
//小转轮
private lazy var iconView:UIImageView = UIImageView(image: UIImage(named: "visitordiscover_feed_image_smallicon"))
private lazy var maskIconView:UIImageView = UIImageView(image: UIImage(named: "visitordiscover_feed_mask_smallicon"))
//小房子
private lazy var houseIconView:UIImageView = UIImageView(image: UIImage(named: "visitordiscover_feed_image_house"))
//提示标签
private lazy var tipLabel:UILabel = UILabel.cz_labelWithText("",
fontSize: 14,
color: UIColor.darkGrayColor())
//注册按钮
private lazy var registerButton:UIButton = UIButton.cz_textButton("注册",
fontSize: 14,
normalColor: UIColor.orangeColor(),
highlightedColor: UIColor.blackColor(),
backgroundImageName: "common_button_white_disable")
//登陆按钮
private lazy var loginButton:UIButton = UIButton.cz_textButton("登录",
fontSize: 14,
normalColor: UIColor.darkGrayColor(),
highlightedColor: UIColor.blackColor(),
backgroundImageName: "common_button_white_disable")
override init(frame: CGRect) {
super.init(frame:frame)
setUpUI()
iconViewRotate()
//dddddddd
}
//这个方法打完上面的会提示
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
//ddffffffff
extension WBVistorView{
//给iconView添加旋转动画
func iconViewRotate(){
let anim = CABasicAnimation(keyPath: "transform.rotation")
anim.toValue = M_PI * 2
anim.repeatCount = MAXFLOAT
anim.duration = 15
anim.removedOnCompletion = false //完成后不删除
iconView.layer.addAnimation(anim, forKey: nil)
}
func setUpUI() {
backgroundColor = UIColor.cz_colorWithHex(0xEDEDED)
addSubview(iconView)
addSubview(maskIconView)
addSubview(houseIconView)
addSubview(tipLabel)
addSubview(registerButton)
addSubview(loginButton)
//纯代码自动布局(苹果原生的两个方法:构造函数,VFL可视化格式语言)
//1、取消autoresizing(xib时autolayout)
for sview in subviews {
sview.translatesAutoresizingMaskIntoConstraints = false
}
//2、自动布局
//(1) iconView.CenterX =self.CenterX * 1.0 + 0
addConstraint(NSLayoutConstraint(item: iconView,
attribute: .CenterX,
relatedBy: .Equal,
toItem: self,
attribute: .CenterX,
multiplier: 1.0,
constant: 0))
addConstraint(NSLayoutConstraint(item: iconView,
attribute: .CenterY,
relatedBy: .Equal,
toItem: self,
attribute: .CenterY,
multiplier: 1.0,
constant: -60))
//(2)houseView
addConstraint(NSLayoutConstraint(item: houseIconView,
attribute: .CenterX,
relatedBy: .Equal,
toItem: iconView,
attribute: .CenterX,
multiplier: 1.0,
constant: 0))
addConstraint(NSLayoutConstraint(item: houseIconView,
attribute: .CenterY,
relatedBy: .Equal,
toItem: iconView,
attribute: .CenterY,
multiplier: 1.0,
constant: 0))
//(3)提示标签
addConstraint(NSLayoutConstraint(item: tipLabel,
attribute: .CenterX,
relatedBy: .Equal,
toItem: iconView,
attribute: .CenterX,
multiplier: 1.0,
constant: 0))
addConstraint(NSLayoutConstraint(item: tipLabel,
attribute: .Top,
relatedBy: .Equal,
toItem: iconView,
attribute: .Bottom,
multiplier: 1.0,
constant: 20))
addConstraint(NSLayoutConstraint(item: tipLabel,
attribute: .Width,
relatedBy: .Equal,
toItem: nil,
attribute: .NotAnAttribute,
multiplier:0 ,
constant: 230)) ;
//(4)注册按钮
addConstraint(NSLayoutConstraint(item: registerButton,
attribute: .Top,
relatedBy: .Equal,
toItem: tipLabel,
attribute: .Bottom,
multiplier: 1,
constant: 20))
addConstraint(NSLayoutConstraint(item: registerButton,
attribute: .Left,
relatedBy: .Equal,
toItem: tipLabel,
attribute: .Left,
multiplier: 1,
constant: 0))
addConstraint(NSLayoutConstraint(item: registerButton,
attribute: .Width,
relatedBy: .Equal,
toItem: nil,
attribute: .NotAnAttribute,
multiplier: 1,
constant: 100))
//(4)登录按钮
addConstraint(NSLayoutConstraint(item: loginButton,
attribute: .Top,
relatedBy: .Equal,
toItem: tipLabel,
attribute: .Bottom,
multiplier: 1,
constant: 20))
addConstraint(NSLayoutConstraint(item: loginButton,
attribute: .Right,
relatedBy: .Equal,
toItem: tipLabel,
attribute: .Right,
multiplier: 1,
constant: 0))
addConstraint(NSLayoutConstraint(item: loginButton,
attribute: .Width,
relatedBy: .Equal,
toItem: nil,
attribute: .NotAnAttribute,
multiplier: 1,
constant: 100))
//背景:VFL
//views:定义 VFL控件名称和实际名称的映射关系
//metrics:定义VFL中()指定的常数映射关系
let viewDict = ["maskIconView":maskIconView,
"registerButton":registerButton]
addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[maskIconView]-0-|",
options: [],
metrics: nil,
views: viewDict))
addConstraints(NSLayoutConstraint.constraintsWithVisualFormat(
"V:|-0-[maskIconView]-(-35)-[registerButton]",
options: [],
metrics: nil,
views: viewDict))
//用metrics效果同上
// let metirc = ["spacing":-35]
// addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[maskIconView]-(spacing)-[registerButton]", options: [], metrics: metirc, views: viewDict))
}
}
| mit | ba4eed67a7d5e1e51fad9abb7f0fb76e | 59.070093 | 170 | 0.310774 | 9.175589 | false | false | false | false |
Shopify/mobile-buy-sdk-ios | Buy/Generated/Storefront/Page.swift | 1 | 12028 | //
// Page.swift
// Buy
//
// Created by Shopify.
// Copyright (c) 2017 Shopify 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.
//
import Foundation
extension Storefront {
/// Shopify merchants can create pages to hold static HTML content. Each Page
/// object represents a custom page on the online store.
open class PageQuery: GraphQL.AbstractQuery, GraphQLQuery {
public typealias Response = Page
/// The description of the page, complete with HTML formatting.
@discardableResult
open func body(alias: String? = nil) -> PageQuery {
addField(field: "body", aliasSuffix: alias)
return self
}
/// Summary of the page body.
@discardableResult
open func bodySummary(alias: String? = nil) -> PageQuery {
addField(field: "bodySummary", aliasSuffix: alias)
return self
}
/// The timestamp of the page creation.
@discardableResult
open func createdAt(alias: String? = nil) -> PageQuery {
addField(field: "createdAt", aliasSuffix: alias)
return self
}
/// A human-friendly unique string for the page automatically generated from
/// its title.
@discardableResult
open func handle(alias: String? = nil) -> PageQuery {
addField(field: "handle", aliasSuffix: alias)
return self
}
/// A globally-unique identifier.
@discardableResult
open func id(alias: String? = nil) -> PageQuery {
addField(field: "id", aliasSuffix: alias)
return self
}
/// Returns a metafield found by namespace and key.
///
/// - parameters:
/// - namespace: A container for a set of metafields.
/// - key: The identifier for the metafield.
///
@discardableResult
open func metafield(alias: String? = nil, namespace: String, key: String, _ subfields: (MetafieldQuery) -> Void) -> PageQuery {
var args: [String] = []
args.append("namespace:\(GraphQL.quoteString(input: namespace))")
args.append("key:\(GraphQL.quoteString(input: key))")
let argsString = "(\(args.joined(separator: ",")))"
let subquery = MetafieldQuery()
subfields(subquery)
addField(field: "metafield", aliasSuffix: alias, args: argsString, subfields: subquery)
return self
}
/// The metafields associated with the resource matching the supplied list of
/// namespaces and keys.
///
/// - parameters:
/// - identifiers: The list of metafields to retrieve by namespace and key.
///
@discardableResult
open func metafields(alias: String? = nil, identifiers: [HasMetafieldsIdentifier], _ subfields: (MetafieldQuery) -> Void) -> PageQuery {
var args: [String] = []
args.append("identifiers:[\(identifiers.map{ "\($0.serialize())" }.joined(separator: ","))]")
let argsString = "(\(args.joined(separator: ",")))"
let subquery = MetafieldQuery()
subfields(subquery)
addField(field: "metafields", aliasSuffix: alias, args: argsString, subfields: subquery)
return self
}
/// The URL used for viewing the resource on the shop's Online Store. Returns
/// `null` if the resource is currently not published to the Online Store sales
/// channel.
@discardableResult
open func onlineStoreUrl(alias: String? = nil) -> PageQuery {
addField(field: "onlineStoreUrl", aliasSuffix: alias)
return self
}
/// The page's SEO information.
@discardableResult
open func seo(alias: String? = nil, _ subfields: (SEOQuery) -> Void) -> PageQuery {
let subquery = SEOQuery()
subfields(subquery)
addField(field: "seo", aliasSuffix: alias, subfields: subquery)
return self
}
/// The title of the page.
@discardableResult
open func title(alias: String? = nil) -> PageQuery {
addField(field: "title", aliasSuffix: alias)
return self
}
/// The timestamp of the latest page update.
@discardableResult
open func updatedAt(alias: String? = nil) -> PageQuery {
addField(field: "updatedAt", aliasSuffix: alias)
return self
}
}
/// Shopify merchants can create pages to hold static HTML content. Each Page
/// object represents a custom page on the online store.
open class Page: GraphQL.AbstractResponse, GraphQLObject, HasMetafields, MetafieldParentResource, MetafieldReference, Node, OnlineStorePublishable {
public typealias Query = PageQuery
internal override func deserializeValue(fieldName: String, value: Any) throws -> Any? {
let fieldValue = value
switch fieldName {
case "body":
guard let value = value as? String else {
throw SchemaViolationError(type: Page.self, field: fieldName, value: fieldValue)
}
return value
case "bodySummary":
guard let value = value as? String else {
throw SchemaViolationError(type: Page.self, field: fieldName, value: fieldValue)
}
return value
case "createdAt":
guard let value = value as? String else {
throw SchemaViolationError(type: Page.self, field: fieldName, value: fieldValue)
}
return GraphQL.iso8601DateParser.date(from: value)!
case "handle":
guard let value = value as? String else {
throw SchemaViolationError(type: Page.self, field: fieldName, value: fieldValue)
}
return value
case "id":
guard let value = value as? String else {
throw SchemaViolationError(type: Page.self, field: fieldName, value: fieldValue)
}
return GraphQL.ID(rawValue: value)
case "metafield":
if value is NSNull { return nil }
guard let value = value as? [String: Any] else {
throw SchemaViolationError(type: Page.self, field: fieldName, value: fieldValue)
}
return try Metafield(fields: value)
case "metafields":
guard let value = value as? [Any] else {
throw SchemaViolationError(type: Page.self, field: fieldName, value: fieldValue)
}
return try value.map { if $0 is NSNull { return nil }
guard let value = $0 as? [String: Any] else {
throw SchemaViolationError(type: Page.self, field: fieldName, value: fieldValue)
}
return try Metafield(fields: value) } as [Any?]
case "onlineStoreUrl":
if value is NSNull { return nil }
guard let value = value as? String else {
throw SchemaViolationError(type: Page.self, field: fieldName, value: fieldValue)
}
return URL(string: value)!
case "seo":
if value is NSNull { return nil }
guard let value = value as? [String: Any] else {
throw SchemaViolationError(type: Page.self, field: fieldName, value: fieldValue)
}
return try SEO(fields: value)
case "title":
guard let value = value as? String else {
throw SchemaViolationError(type: Page.self, field: fieldName, value: fieldValue)
}
return value
case "updatedAt":
guard let value = value as? String else {
throw SchemaViolationError(type: Page.self, field: fieldName, value: fieldValue)
}
return GraphQL.iso8601DateParser.date(from: value)!
default:
throw SchemaViolationError(type: Page.self, field: fieldName, value: fieldValue)
}
}
/// The description of the page, complete with HTML formatting.
open var body: String {
return internalGetBody()
}
func internalGetBody(alias: String? = nil) -> String {
return field(field: "body", aliasSuffix: alias) as! String
}
/// Summary of the page body.
open var bodySummary: String {
return internalGetBodySummary()
}
func internalGetBodySummary(alias: String? = nil) -> String {
return field(field: "bodySummary", aliasSuffix: alias) as! String
}
/// The timestamp of the page creation.
open var createdAt: Date {
return internalGetCreatedAt()
}
func internalGetCreatedAt(alias: String? = nil) -> Date {
return field(field: "createdAt", aliasSuffix: alias) as! Date
}
/// A human-friendly unique string for the page automatically generated from
/// its title.
open var handle: String {
return internalGetHandle()
}
func internalGetHandle(alias: String? = nil) -> String {
return field(field: "handle", aliasSuffix: alias) as! String
}
/// A globally-unique identifier.
open var id: GraphQL.ID {
return internalGetId()
}
func internalGetId(alias: String? = nil) -> GraphQL.ID {
return field(field: "id", aliasSuffix: alias) as! GraphQL.ID
}
/// Returns a metafield found by namespace and key.
open var metafield: Storefront.Metafield? {
return internalGetMetafield()
}
open func aliasedMetafield(alias: String) -> Storefront.Metafield? {
return internalGetMetafield(alias: alias)
}
func internalGetMetafield(alias: String? = nil) -> Storefront.Metafield? {
return field(field: "metafield", aliasSuffix: alias) as! Storefront.Metafield?
}
/// The metafields associated with the resource matching the supplied list of
/// namespaces and keys.
open var metafields: [Storefront.Metafield?] {
return internalGetMetafields()
}
open func aliasedMetafields(alias: String) -> [Storefront.Metafield?] {
return internalGetMetafields(alias: alias)
}
func internalGetMetafields(alias: String? = nil) -> [Storefront.Metafield?] {
return field(field: "metafields", aliasSuffix: alias) as! [Storefront.Metafield?]
}
/// The URL used for viewing the resource on the shop's Online Store. Returns
/// `null` if the resource is currently not published to the Online Store sales
/// channel.
open var onlineStoreUrl: URL? {
return internalGetOnlineStoreUrl()
}
func internalGetOnlineStoreUrl(alias: String? = nil) -> URL? {
return field(field: "onlineStoreUrl", aliasSuffix: alias) as! URL?
}
/// The page's SEO information.
open var seo: Storefront.SEO? {
return internalGetSeo()
}
func internalGetSeo(alias: String? = nil) -> Storefront.SEO? {
return field(field: "seo", aliasSuffix: alias) as! Storefront.SEO?
}
/// The title of the page.
open var title: String {
return internalGetTitle()
}
func internalGetTitle(alias: String? = nil) -> String {
return field(field: "title", aliasSuffix: alias) as! String
}
/// The timestamp of the latest page update.
open var updatedAt: Date {
return internalGetUpdatedAt()
}
func internalGetUpdatedAt(alias: String? = nil) -> Date {
return field(field: "updatedAt", aliasSuffix: alias) as! Date
}
internal override func childResponseObjectMap() -> [GraphQL.AbstractResponse] {
var response: [GraphQL.AbstractResponse] = []
objectMap.keys.forEach {
switch($0) {
case "metafield":
if let value = internalGetMetafield() {
response.append(value)
response.append(contentsOf: value.childResponseObjectMap())
}
case "metafields":
internalGetMetafields().forEach {
if let value = $0 {
response.append(value)
response.append(contentsOf: value.childResponseObjectMap())
}
}
case "seo":
if let value = internalGetSeo() {
response.append(value)
response.append(contentsOf: value.childResponseObjectMap())
}
default:
break
}
}
return response
}
}
}
| mit | 27e7f187f94af3dc1040e7ccbc45129a | 30.904509 | 149 | 0.690223 | 3.84896 | false | false | false | false |
kellanburket/Passenger | Pod/Classes/Authentication/OAuth1.swift | 1 | 10057 | //
// OAuth1Service.swift
// Pods
//
// Created by Kellan Cummings on 6/10/15.
//
//
import Foundation
/**
Manages the construction of an `OAuth1` HTTP header.
*/
public class OAuth1: AuthorizationService {
public var token: String?
public var secret: String?
public var delegate: OAuth1Delegate?
public var requestTokenUrl: NSURL {
return _requestTokenUrl
}
public var accessTokenUrl: NSURL {
return _accessTokenUrl
}
public var authorizeUrl: NSURL {
return _authorizeUrl
}
public var requestTokenCallback: String {
return _requestTokenCallback
}
private var consumerSecret: String
private var _requestTokenCallback: String
private var _accessTokenUrl: NSURL
private var _requestTokenUrl: NSURL
private var _authorizeUrl: NSURL
private var signingKey: String {
var secret = self.secret?.percentEncode() ?? ""
return "\(consumerSecret.percentEncode())&\(secret)"
}
private var requestHeaders: [String: String] {
var params = [
"oauth_consumer_key": consumerKey,
"oauth_signature_method": "HMAC-SHA1",
"oauth_timestamp": getCurrentTimestamp(),
"oauth_nonce": generateNonce(),
"oauth_version": "1.0"
]
if let token = token {
params["oauth_token"] = token
}
return params
}
override internal init(key: String, params: [String: AnyObject]) {
if let consumerSecret = params["consumer_secret"] as? String {
self.consumerSecret = consumerSecret
} else {
fatalError("Consumer Secret must be provided for OAuth1 Authentication")
}
if let requestTokenCallback = params["request_token_callback"] as? String {
self._requestTokenCallback = requestTokenCallback
} else {
fatalError("Request Token Callback must be provided for OAuth1 Authentication")
}
if let requestTokenUrl = params["request_token_url"] as? String {
self._requestTokenUrl = NSURL(string: requestTokenUrl)!
} else {
fatalError("Request Token URL must be provided for OAuth1 Authentication")
}
if let authorizeUrl = params["authorize_url"] as? String {
self._authorizeUrl = NSURL(string: authorizeUrl)!
} else {
fatalError("Authorization URL must be provided for OAuth1 Authentication")
}
if let accessTokenUrl = params["access_token_url"] as? String {
self._accessTokenUrl = NSURL(string: accessTokenUrl)!
} else {
fatalError("Access Token URL must be provided for OAuth1 Authentication")
}
if let token = params["token"] as? String {
self.token = token
}
if let secret = params["secret"] as? String {
self.secret = secret
}
super.init(key: key, params: params)
}
override internal func setSignature(url: NSURL, parameters: [String:AnyObject], method: String, onComplete: () -> ()) {
//println("Setting Signature")
headers = [String:String]()
for (key, param) in parameters {
if let pstring = param as? String {
if pstring != "" {
headers[key] = pstring
}
} else {
headers[key] = "\(param)"
}
}
headers += requestHeaders
var output = ""
var keys = [String](headers.keys)
keys.sort { $0 < $1 }
for key in keys {
if let header = headers[key] {
output += (key.percentEncode() + "=" + "\(header)".percentEncode() + "&")
} else {
//println("Cannot Set \(key) for \(headers)")
}
}
output = output.rtrim("&").percentEncode()
var absoluteURL = url.absoluteString!.percentEncode()
var signatureInput = "\(method)&\(absoluteURL)&\(output)"
if let signature = signatureInput.sign(HMACAlgorithm.SHA1, key: signingKey) {
self.headers["oauth_signature"] = signature
onComplete()
}
}
override internal func setHeader(url: NSURL, inout request: NSMutableURLRequest) {
var header: String = "OAuth "//realm=\"\(url.absoluteString!)\", "
var keys = [String](headers.keys)
keys.sort { return $0 < $1 }
for key in keys {
var akey = key.percentEncode()
var aval = "\(headers[key]!)".percentEncode()
header += "\(akey)=\"\(aval)\", "
}
header = header.rtrim(", ")
//println("Header: \(header)")
request.setValue(header, forHTTPHeaderField: "Authorization")
}
/**
Gets the request token URL.
:param: onComplete anonymous function called when the url has been fetched; returns the request token secret as its first parameter and the url as its second
*/
public func getRequestTokenUrl(onComplete: (String?, NSURL?) -> Void) {
let request = HttpRequest(URL: requestTokenUrl, method: HttpMethod.Post, params: [String: AnyObject]()) { data, response, url in
let query = HttpRequest.parseQueryString(data, encoding: self.encoding)
if let requestToken = query["oauth_token"] as? String, requestTokenSecret = query["oauth_token_secret"] as? String {
//println("Request Token: \(requestToken)")
//println("Request Token Secret: \(requestTokenSecret)")
self.secret = requestTokenSecret
self.token = requestToken
if let baseurl = self.authorizeUrl.absoluteString, url = NSURL(string: "\(baseurl)?oauth_token=\(requestToken)") {
onComplete(requestTokenSecret, url)
} else {
println("Could not parse URL string.")
onComplete(nil, nil)
}
} else {
println("Was unable to fetch Request Token.")
onComplete(nil, nil)
}
}
request.authenticate(
OAuth1RequestToken(key: consumerKey, params: [
"consumer_secret": consumerSecret,
"request_token_callback": requestTokenCallback,
"request_token_url": requestTokenUrl.absoluteString!,
"authorize_url": authorizeUrl.absoluteString!,
"access_token_url": accessTokenUrl.absoluteString!
])
)
Http.start(request)
}
/*
Fetches the OAuth1 access token
:param: token token returned in the `getRequestToken` response
:param: verifier verifier returned in the `getRequestToken` response
*/
public func fetchAccessToken(#token: String, verifier: String) {
let request = HttpRequest(URL: accessTokenUrl, method: HttpMethod.Get, params: [String: AnyObject]()) { data, response, url in
let query = HttpRequest.parseQueryString(data, encoding: self.encoding)
if let token = query["oauth_token"] as? String, secret = query["oauth_token_secret"] as? String {
self.token = token
self.secret = secret
if let delegate = self.delegate {
delegate.accessTokenHasBeenFetched(token,
accessTokenSecret: secret
)
}
} else {
println("Could not parse query string \(query).")
}
}
if let secret = self.secret {
request.authenticate(
OAuth1AccessToken(key: consumerKey, params: [
"consumer_secret": consumerSecret,
"request_token_callback": requestTokenCallback,
"request_token_url": requestTokenUrl.absoluteString!,
"authorize_url": authorizeUrl.absoluteString!,
"access_token_url": accessTokenUrl.absoluteString!,
"secret": secret,
"token": token,
"verifier": verifier
])
)
Http.post(request)
} else {
println("Could Not Authorize without secret.")
}
}
}
private class OAuth1RequestToken: OAuth1 {
override private var requestHeaders: [String: String] {
return [
"oauth_callback": requestTokenCallback,
"oauth_consumer_key": consumerKey,
"oauth_nonce": generateNonce(),
"oauth_signature_method": "HMAC-SHA1",
"oauth_timestamp": getCurrentTimestamp(),
"oauth_version": "1.0"
]
}
}
private class OAuth1AccessToken: OAuth1 {
var verifier: String
override private var requestHeaders: [String: String] {
if let token = token {
return [
"oauth_consumer_key": consumerKey,
"oauth_nonce": generateNonce(),
"oauth_timestamp": getCurrentTimestamp(),
"oauth_signature_method": "HMAC-SHA1",
"oauth_token": token,
"oauth_verifier": verifier,
"oauth_version": "1.0"
]
} else {
println("Unable to find required token.")
return [String: String]()
}
}
override init(key: String, params: [String: AnyObject]) {
if let verifier = params["verifier"] as? String {
self.verifier = verifier
} else {
fatalError("Must Provide a verifier to fetch an access token.")
}
super.init(key: key, params: params)
}
} | mit | b7b0990b46223694cc92d039622c1b64 | 32.97973 | 166 | 0.547281 | 5.146878 | false | false | false | false |
PedroTrujilloV/TIY-Assignments | 17--Anybody-Out-There?/AlbumSearch - Pedro/AlbumSearch/APIController.swift | 1 | 2008 | //
// APIController.swift
// AlbumSearch
//
// Created by Pedro Trujillo on 10/27/15.
// Copyright © 2015 Pedro Trujillo. All rights reserved.
//
import Foundation
class APIController
{
var delegate: APIControllerProtocol
init(delegate: APIControllerProtocol)
{
self.delegate = delegate
}
func searchItunesFor(searchTerm:String)
{
let itunesSearchTerm = searchTerm.stringByReplacingOccurrencesOfString(" ", withString: "+", options: NSStringCompareOptions.CaseInsensitiveSearch, range: nil)
if let escapedSearchTerm = itunesSearchTerm.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.alphanumericCharacterSet())
{
let urlPath = "https://itunes.apple.com/search?term=\(escapedSearchTerm)&media=music&entity=album"
let url = NSURL(string: urlPath)
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithURL(url!, completionHandler: {data, response, error -> Void in
print("Task completed")
if error != nil
{
print(error!.localizedDescription)
}
else
{
if let dictionary = self.parseJSON(data!)
{
if let results: NSArray = dictionary["results"] as? NSArray
{
self.delegate.didReceiveAPIResults(results)
}
}
}
})
task.resume()
}
}
func parseJSON(data:NSData) -> NSDictionary?
{
do
{
let dictionary: NSDictionary! = try NSJSONSerialization.JSONObjectWithData(data, options: []) as! NSDictionary
return dictionary
}
catch let error as NSError
{
print(error)
return nil
}
}
}
| cc0-1.0 | 68578d41a6187aec17161cdead7f7379 | 28.955224 | 167 | 0.54559 | 5.88563 | false | false | false | false |
erhoffex/SwiftAnyPic | SwiftAnyPic/PAPPhotoCell.swift | 6 | 1586 | import UIKit
import ParseUI
class PAPPhotoCell: PFTableViewCell {
var photoButton: UIButton?
// MARK:- NSObject
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
// Initialization code
self.opaque = false
self.selectionStyle = UITableViewCellSelectionStyle.None
self.accessoryType = UITableViewCellAccessoryType.None
self.clipsToBounds = false
self.backgroundColor = UIColor.clearColor()
self.imageView!.frame = CGRectMake(0.0, 0.0, self.bounds.size.width, self.bounds.size.width)
self.imageView!.backgroundColor = UIColor.blackColor()
self.imageView!.contentMode = UIViewContentMode.ScaleAspectFit
self.photoButton = UIButton(type: UIButtonType.Custom)
self.photoButton!.frame = CGRectMake(0.0, 0.0, self.bounds.size.width, self.bounds.size.width)
self.photoButton!.backgroundColor = UIColor.clearColor()
self.contentView.addSubview(self.photoButton!)
self.contentView.bringSubviewToFront(self.imageView!)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK:- UIView
override func layoutSubviews() {
super.layoutSubviews()
self.imageView!.frame = CGRectMake(0.0, 0.0, self.bounds.size.width, self.bounds.size.width)
self.photoButton!.frame = CGRectMake(0.0, 0.0, self.bounds.size.width, self.bounds.size.width)
}
}
| cc0-1.0 | 1dbea60228aaf85c2dd69f5bf7b62c44 | 35.883721 | 102 | 0.679697 | 4.610465 | false | false | false | false |
apple/swift-nio | IntegrationTests/allocation-counter-tests-framework/template/HookedFunctionsDoNotHook/Package.swift | 2 | 999 | // swift-tools-version:5.0
// The swift-tools-version declares the minimum version of Swift required to build this package.
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftNIO open source project
//
// Copyright (c) 2017-2020 Apple Inc. and the SwiftNIO project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
import PackageDescription
let package = Package(
name: "HookedFunctions",
products: [
.library(name: "HookedFunctions", type: .dynamic, targets: ["HookedFunctions"]),
],
dependencies: [
.package(url: "../AtomicCounter/", .branch("main")),
],
targets: [
.target(name: "HookedFunctions", dependencies: ["AtomicCounter"]),
]
)
| apache-2.0 | dcdb046b254731e9a172cc0641f8ded1 | 32.3 | 96 | 0.574575 | 4.668224 | false | false | false | false |
pantuspavel/PPEventRegistryAPI | PPEventRegistryAPI/Classes/API/Operations/PPRecentArticlesOperation.swift | 1 | 1910 | //
// PPGetRecentActivity.swift
// PPEventRegistryAPI
//
// Created by Pavel Pantus on 6/22/16.
// Copyright © 2016 Pavel Pantus. All rights reserved.
//
import Foundation
/// Operation to request most recent articles.
final class PPRecentArticlesOperation: PPAsyncOperation {
/**
Operation initializer.
- Parameters:
- count: Articles count that should be requested.
- completionHandler: Completion handler that is executed upon operation completion.
- result: Result of the operation (see PPResult).
*/
init(count: Int = 5, completionHandler: @escaping (_ result: PPResult<[PPArticle], PPError>) -> ()) {
let parameters: [String: Any] = ["action": "getRecentActivity",
"addEvents": false,
"addActivity": false,
"addArticles": true,
"recentActivityArticlesMaxArticleCount": 1 ... 100 ~= count ? count : 5,
"recentActivityArticlesMaxMinsBack": 10 * 60,
"recentActivityArticlesMandatorySourceLocation": false,
"recentActivityArticlesLastActivityId": 0]
super.init(controller: .Overview, method: .Get, parameters: parameters as [String : Any])
self.completionHandler = { result in
switch result {
case let .Success(response):
let events: [PPArticle] = self.modelMapper.mapDataToModelObjects(response)
DispatchQueue.main.async {
completionHandler(.Success(events))
}
case let .Failure(error):
DispatchQueue.main.async {
completionHandler(.Failure(error))
}
}
}
}
}
| mit | e1a30ffa95f533ffce07c1172a35b50d | 39.617021 | 113 | 0.54374 | 5.407932 | false | false | false | false |
mspegagne/ToDoReminder-iOS | ToDoReminder/ToDoReminder/ToDo.swift | 1 | 1139 | //
// ToDo.swift
// ToDoReminder
//
// Created by Mathieu Spegagne on 05/04/2015.
// Copyright (c) 2015 Mathieu Spegagne. All rights reserved.
//
import Foundation
import CoreData
import UIKit
@objc(ToDo)
class ToDo: NSManagedObject {
@NSManaged var title: String
@NSManaged var text: String
@NSManaged var history: NSNumber
func alert()->UIAlertController {
let alertController = UIAlertController(title: self.title, message: self.text, preferredStyle: UIAlertControllerStyle.Alert)
alertController.addAction(UIAlertAction(title: "Dismiss", style: UIAlertActionStyle.Default,handler: nil))
return alertController
}
class func save(moc: NSManagedObjectContext, newTitle: String, newText: String) -> ToDo {
let entityDescripition = NSEntityDescription.entityForName("ToDo", inManagedObjectContext: moc)
let task = ToDo(entity: entityDescripition!, insertIntoManagedObjectContext: moc)
task.title = newTitle
task.text = newText
task.history = false
moc.save(nil)
return task
}
}
| mit | e776662d79f8da64a27f4910b92a0fb0 | 27.475 | 132 | 0.679543 | 4.745833 | false | false | false | false |
y0ke/actor-platform | actor-sdk/sdk-core-ios/ActorSDK/Sources/SwiftExtensions/Views.swift | 2 | 13531 | //
// Copyright (c) 2014-2016 Actor LLC. <https://actor.im>
//
import Foundation
import AVFoundation
// Closure based tap on views
private var targetReference = "target"
public extension UITapGestureRecognizer {
public convenience init(closure: ()->()){
let target = ClosureTarget(closure: closure)
self.init(target: target, action: #selector(ClosureTarget.invoke))
setAssociatedObject(self, value: target, associativeKey: &targetReference)
}
}
public extension UIView {
public var viewDidTap: (()->())? {
set (value) {
if value != nil {
self.addGestureRecognizer(UITapGestureRecognizer(closure: value!))
self.userInteractionEnabled = true
}
}
get {
return nil
}
}
}
private class ClosureTarget {
private let closure: ()->()
init(closure: ()->()) {
self.closure = closure
}
@objc func invoke() {
closure()
}
}
// View Hide/Show and size extensions
public extension UIView {
public func hideView() {
self.hidden = true
// UIView.animateWithDuration(0.2, animations: { () -> Void in
// self.alpha = 0
// })
}
public func showView() {
self.hidden = false
// UIView.animateWithDuration(0.2, animations: { () -> Void in
// self.alpha = 1
// })
}
public func showViewAnimated() {
UIView.animateWithDuration(0.2, animations: { () -> Void in
self.alpha = 1
})
}
public func hideViewAnimated() {
UIView.animateWithDuration(0.2, animations: { () -> Void in
self.alpha = 0
})
}
// public var height: CGFloat { get { return bounds.height } }
// public var width: CGFloat { get { return bounds.width } }
//
// public var left: CGFloat { get { return frame.minX } }
// public var right: CGFloat { get { return frame.maxX } }
// public var top: CGFloat { get { return frame.minY } }
// public var bottom: CGFloat { get { return frame.maxY } }
public func centerIn(rect: CGRect) {
self.frame = CGRectMake(rect.origin.x + (rect.width - self.bounds.width) / 2, rect.origin.y + (rect.height - self.bounds.height) / 2,
self.bounds.width, self.bounds.height)
}
public func under(rect: CGRect, offset: CGFloat) {
self.frame = CGRectMake(rect.origin.x + (rect.width - self.bounds.width) / 2, rect.origin.y + rect.height + offset,
self.bounds.width, self.bounds.height)
}
public func topIn(rect: CGRect) {
self.frame = CGRectMake(rect.origin.x + (rect.width - self.bounds.width) / 2, rect.origin.y,
self.bounds.width, self.bounds.height)
}
}
// Text measuring
public class UIViewMeasure {
public class func measureText(text: String, width: CGFloat, fontSize: CGFloat) -> CGSize {
return UIViewMeasure.measureText(text, width: width, font: UIFont.systemFontOfSize(fontSize))
}
public class func measureText(text: String, width: CGFloat, font: UIFont) -> CGSize {
// Building paragraph styles
let style = NSMutableParagraphStyle()
style.lineBreakMode = NSLineBreakMode.ByWordWrapping
// Measuring text with reduced width
let rect = text.boundingRectWithSize(CGSize(width: width - 2, height: CGFloat.max),
options: NSStringDrawingOptions.UsesLineFragmentOrigin,
attributes: [NSFontAttributeName: font, NSParagraphStyleAttributeName: style],
context: nil)
// Returning size with expanded width
return CGSizeMake(ceil(rect.width + 2), CGFloat(ceil(rect.height)))
}
public class func measureText(attributedText: NSAttributedString, width: CGFloat) -> CGSize {
// Measuring text with reduced width
let rect = attributedText.boundingRectWithSize(CGSize(width: width - 2, height: CGFloat.max), options: [.UsesLineFragmentOrigin, .UsesFontLeading], context: nil)
// Returning size with expanded width and height
return CGSizeMake(ceil(rect.width + 2), CGFloat(ceil(rect.height)))
}
}
// Loading cells without explict registration
private var registeredCells = "cells!"
public extension UITableView {
private func cellTypeForClass(cellClass: AnyClass) -> String {
let cellReuseId = "\(cellClass)"
var registered: ([String])! = getAssociatedObject(self, associativeKey: ®isteredCells)
var found = false
if registered != nil {
if registered.contains(cellReuseId) {
found = true
} else {
registered.append(cellReuseId)
setAssociatedObject(self, value: registered, associativeKey: ®isteredCells)
}
} else {
setAssociatedObject(self, value: [cellReuseId], associativeKey: ®isteredCells)
}
if !found {
registerClass(cellClass, forCellReuseIdentifier: cellReuseId)
}
return cellReuseId
}
public func dequeueCell(cellClass: AnyClass, indexPath: NSIndexPath) -> UITableViewCell {
let reuseId = cellTypeForClass(cellClass)
return self.dequeueReusableCellWithIdentifier(reuseId, forIndexPath: indexPath)
}
public func dequeueCell<T where T: UITableViewCell>(indexPath: NSIndexPath) -> T {
let reuseId = cellTypeForClass(T.self)
return self.dequeueReusableCellWithIdentifier(reuseId, forIndexPath: indexPath) as! T
}
public func visibleCellForIndexPath(path: NSIndexPath) -> UITableViewCell? {
if indexPathsForVisibleRows == nil {
return nil
}
for i in 0..<indexPathsForVisibleRows!.count {
let vPath = indexPathsForVisibleRows![i]
if vPath.row == path.row && vPath.section == path.section {
return visibleCells[i]
}
}
return nil
}
}
public extension UICollectionView {
// private func cellTypeForClass(cellClass: AnyClass) -> String {
// let cellReuseId = "\(cellClass)"
// var registered: ([String])! = getAssociatedObject(self, associativeKey: ®isteredCells)
// var found = false
// if registered != nil {
// if registered.contains(cellReuseId) {
// found = true
// } else {
// registered.append(cellReuseId)
// setAssociatedObject(self, value: registered, associativeKey: ®isteredCells)
// }
// } else {
// setAssociatedObject(self, value: [cellReuseId], associativeKey: ®isteredCells)
// }
//
// if !found {
// registerClass(cellClass, forCellWithReuseIdentifier: cellReuseId)
// }
//
// return cellReuseId
// }
//
// public func dequeueCell(cellClass: AnyClass, indexPath: NSIndexPath) -> UICollectionViewCell {
// let reuseId = cellTypeForClass(cellClass)
// return self.dequeueReusableCellWithReuseIdentifier(reuseId, forIndexPath: indexPath)
// }
//
// public func dequeueCell<T where T: UICollectionViewCell>(indexPath: NSIndexPath) -> T {
// let reuseId = cellTypeForClass(T.self)
// return self.dequeueReusableCellWithReuseIdentifier(reuseId, forIndexPath: indexPath) as! T
// }
}
// Status bar and navigation bar heights
public extension UIViewController {
public var navigationBarHeight: CGFloat {
get {
if (navigationController != nil) {
return navigationController!.navigationBar.frame.height
} else {
return CGFloat(44)
}
}
}
public var statusBarHeight: CGFloat {
get {
let statusBarSize = UIApplication.sharedApplication().statusBarFrame.size
return min(statusBarSize.width, statusBarSize.height)
}
}
}
// Status bar show/hide without moving views
private var selector = Selector("rs`str".encodeText(1) + "A`qVhmcnv".encodeText(1))
private var viewClass: AnyClass = NSClassFromString("VJTubuvtCbs".encodeText(-1))!
public extension UIApplication {
public func animateStatusBarAppearance(animation: StatusBarAppearanceAnimation, duration: NSTimeInterval) {
if self.respondsToSelector(selector) {
let window = self.performSelector(selector).takeUnretainedValue() as! UIWindow
var view: UIView! = nil
for subview in window.subviews {
if subview.dynamicType == viewClass {
view = subview
break
}
}
if view != nil {
let viewHeight = view.frame.size.height
var startPosition = view.layer.position
var position = view.layer.position
if animation == .SlideDown {
startPosition = CGPointMake(floor(view.frame.size.width / 2), floor(view.frame.size.height / 2) - viewHeight);
position = CGPointMake(floor(view.frame.size.width / 2), floor(view.frame.size.height / 2));
} else if animation == .SlideUp {
startPosition = CGPointMake(floor(view.frame.size.width / 2), floor(view.frame.size.height / 2));
position = CGPointMake(floor(view.frame.size.width / 2), floor(view.frame.size.height / 2) - viewHeight);
}
let animation = CABasicAnimation(keyPath: "position")
animation.duration = duration
animation.fromValue = NSValue(CGPoint: startPosition)
animation.toValue = NSValue(CGPoint: position)
animation.fillMode = kCAFillModeForwards
animation.removedOnCompletion = false
animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
view.layer.addAnimation(animation, forKey: "ac_position")
}
}
}
}
public enum StatusBarAppearanceAnimation {
case SlideDown
case SlideUp
}
// Encoding strings to avoid deobfuscation
extension String {
func encodeText(key: Int32) -> String {
var res = ""
for i in 0..<length {
res += String(
Character(
UnicodeScalar(
UInt32(
Int32(
(self[i] as String).unicodeScalars.first!.value) + key
))
)
)
}
return res
}
}
// Navigation Bar
extension UINavigationBar {
func setTransparentBackground() {
setBackgroundImage(UIImage(), forBarMetrics: UIBarMetrics.Default)
shadowImage = UIImage()
}
var hairlineHidden: Bool {
get {
return hairlineImageViewInNavigationBar(self)!.hidden
}
set(v) {
hairlineImageViewInNavigationBar(self)!.hidden = v
}
}
private func hairlineImageViewInNavigationBar(view: UIView) -> UIImageView? {
if view.isKindOfClass(UIImageView) && view.bounds.height <= 1.0 {
return (view as! UIImageView)
}
for subview: UIView in view.subviews {
if let imageView: UIImageView = hairlineImageViewInNavigationBar(subview) {
return imageView
}
}
return nil
}
}
extension AVAsset {
func videoOrientation() -> (orientation: UIInterfaceOrientation, device: AVCaptureDevicePosition) {
var orientation: UIInterfaceOrientation = .Unknown
var device: AVCaptureDevicePosition = .Unspecified
let tracks :[AVAssetTrack] = self.tracksWithMediaType(AVMediaTypeVideo)
if let videoTrack = tracks.first {
let t = videoTrack.preferredTransform
if (t.a == 0 && t.b == 1.0 && t.d == 0) {
orientation = .Portrait
if t.c == 1.0 {
device = .Front
} else if t.c == -1.0 {
device = .Back
}
}
else if (t.a == 0 && t.b == -1.0 && t.d == 0) {
orientation = .PortraitUpsideDown
if t.c == -1.0 {
device = .Front
} else if t.c == 1.0 {
device = .Back
}
}
else if (t.a == 1.0 && t.b == 0 && t.c == 0) {
orientation = .LandscapeRight
if t.d == -1.0 {
device = .Front
} else if t.d == 1.0 {
device = .Back
}
}
else if (t.a == -1.0 && t.b == 0 && t.c == 0) {
orientation = .LandscapeLeft
if t.d == 1.0 {
device = .Front
} else if t.d == -1.0 {
device = .Back
}
}
}
return (orientation, device)
}
} | agpl-3.0 | 3c1031108b27e67e3bc331e5391fd4ce | 32.49505 | 169 | 0.562264 | 4.965505 | false | false | false | false |
michaelvu812/MSDateFormatter | MSDateFormatter/MSDateFormatter/MSDateFormatter.swift | 2 | 21392 | //
// DateFormatter.swift
// DateFormatter
//
// Created by Michael Vu on 10/6/14.
// Copyright (c) 2014 Michael Vu. All rights reserved.
//
import CoreFoundation
import Foundation
let formatter: NSDateFormatter = NSDateFormatter()
let currentCalendar = NSCalendar.currentCalendar()
let bundle = NSBundle.mainBundle()
let significantUnits = NSCalendarUnit.YearCalendarUnit | NSCalendarUnit.MonthCalendarUnit | NSCalendarUnit.WeekCalendarUnit | NSCalendarUnit.DayCalendarUnit | NSCalendarUnit.HourCalendarUnit | NSCalendarUnit.MinuteCalendarUnit | NSCalendarUnit.SecondCalendarUnit
let localizationTable = "MSDateFormatter"
func calendarUnitFromString(string:String) -> NSCalendarUnit {
switch string {
case "year":
return .YearCalendarUnit
case "month":
return .MonthCalendarUnit
case "week":
return .WeekCalendarUnit
case "day":
return .DayCalendarUnit
case "hour":
return .HourCalendarUnit
case "minute":
return .MinuteCalendarUnit
case "second":
return .SecondCalendarUnit
default:
return nil
}
}
func getNormalizedCalendarUnit(unit:NSCalendarUnit) -> NSCalendarUnit {
switch unit {
case NSCalendarUnit.WeekOfMonthCalendarUnit, NSCalendarUnit.WeekOfYearCalendarUnit:
return .WeekCalendarUnit
case NSCalendarUnit.WeekdayCalendarUnit, NSCalendarUnit.WeekdayOrdinalCalendarUnit:
return .DayCalendarUnit
default:
return unit;
}
}
func compareCalendarUnitSignificance(unit:NSCalendarUnit, other:NSCalendarUnit) -> NSComparisonResult {
let nUnit = getNormalizedCalendarUnit(unit)
let nOther = getNormalizedCalendarUnit(other)
if (nUnit == .WeekCalendarUnit) ^ (nOther == .WeekCalendarUnit) {
if nUnit == .WeekCalendarUnit {
switch nUnit {
case NSCalendarUnit.YearCalendarUnit, NSCalendarUnit.MonthCalendarUnit:
return .OrderedAscending
default:
return .OrderedDescending
}
} else {
switch nOther {
case NSCalendarUnit.YearCalendarUnit, NSCalendarUnit.MonthCalendarUnit:
return .OrderedDescending
default:
return .OrderedAscending
}
}
} else {
if nUnit.value > nOther.value {
return .OrderedAscending
} else if (nUnit.value < nOther.value) {
return .OrderedDescending
} else {
return .OrderedSame
}
}
}
func localizedStringForNumber(number:NSInteger, unit:NSCalendarUnit, short:Bool = false) -> String {
let singular = (number == 1)
switch unit {
case NSCalendarUnit.YearCalendarUnit where singular:
return bundle.localizedStringForKey(short ? "yr" : "year", value: nil, table: localizationTable)
case NSCalendarUnit.YearCalendarUnit where !singular:
return bundle.localizedStringForKey(short ? "yrs" : "years", value: nil, table: localizationTable)
case NSCalendarUnit.MonthCalendarUnit where singular:
return bundle.localizedStringForKey(short ? "mo" : "month", value: nil, table: localizationTable)
case NSCalendarUnit.MonthCalendarUnit where !singular:
return bundle.localizedStringForKey(short ? "mos" : "months", value: nil, table: localizationTable)
case NSCalendarUnit.WeekCalendarUnit where singular:
return bundle.localizedStringForKey(short ? "wk" : "week", value: nil, table: localizationTable)
case NSCalendarUnit.WeekCalendarUnit where !singular:
return bundle.localizedStringForKey(short ? "wks" : "weeks", value: nil, table: localizationTable)
case NSCalendarUnit.DayCalendarUnit where singular:
return bundle.localizedStringForKey(short ? "day" : "day", value: nil, table: localizationTable)
case NSCalendarUnit.DayCalendarUnit where !singular:
return bundle.localizedStringForKey(short ? "days" : "days", value: nil, table: localizationTable)
case NSCalendarUnit.HourCalendarUnit where singular:
return bundle.localizedStringForKey(short ? "hr" : "hour", value: nil, table: localizationTable)
case NSCalendarUnit.HourCalendarUnit where !singular:
return bundle.localizedStringForKey(short ? "hrs" : "hours", value: nil, table: localizationTable)
case NSCalendarUnit.MinuteCalendarUnit where singular:
return bundle.localizedStringForKey(short ? "min" : "minute", value: nil, table: localizationTable)
case NSCalendarUnit.MinuteCalendarUnit where !singular:
return bundle.localizedStringForKey(short ? "mins" : "minutes", value: nil, table: localizationTable)
case NSCalendarUnit.SecondCalendarUnit where singular:
return bundle.localizedStringForKey(short ? "s" : "second", value: nil, table: localizationTable)
case NSCalendarUnit.SecondCalendarUnit where !singular:
return bundle.localizedStringForKey(short ? "s" : "seconds", value: nil, table: localizationTable)
default:
return ""
}
}
func localizedSimpleStringForComponents(components:NSDateComponents) -> String {
if (components.year == -1) {
return bundle.localizedStringForKey("last year", value: nil, table: localizationTable)
} else if (components.month == -1 && components.year == 0) {
return bundle.localizedStringForKey("last month", value: nil, table: localizationTable)
} else if (components.week() == -1 && components.year == 0 && components.month == 0) {
return bundle.localizedStringForKey("last week", value: nil, table: localizationTable)
} else if (components.day == -1 && components.year == 0 && components.month == 0 && components.week() == 0) {
return bundle.localizedStringForKey("yesterday", value: nil, table: localizationTable)
}
if (components.year == 1) {
return bundle.localizedStringForKey("next year", value: nil, table: localizationTable)
} else if (components.month == 1 && components.year == 0) {
return bundle.localizedStringForKey("next month", value: nil, table: localizationTable)
} else if (components.week() == 1 && components.year == 0 && components.month == 0) {
return bundle.localizedStringForKey("next week", value: nil, table: localizationTable)
} else if (components.day == 1 && components.year == 0 && components.month == 0 && components.week() == 0) {
return bundle.localizedStringForKey("tomorrow", value: nil, table: localizationTable)
}
return ""
}
extension NSDateComponents {
func ago() -> NSDate {
return currentCalendar.dateByAddingComponents(-self, toDate:NSDate.date(), options:nil)
}
func fromNow() -> NSDate {
return currentCalendar.dateByAddingComponents(self, toDate:NSDate.date(), options:nil)
}
func add(components: NSDateComponents) -> NSDateComponents {
let component = NSDateComponents()
component.second = ((self.second != NSUndefinedDateComponent ? self.second : 0) +
(components.second != NSUndefinedDateComponent ? components.second : 0))
component.minute = ((self.minute != NSUndefinedDateComponent ? self.minute : 0) +
(components.minute != NSUndefinedDateComponent ? components.minute : 0))
component.hour = ((self.hour != NSUndefinedDateComponent ? self.hour : 0) +
(components.hour != NSUndefinedDateComponent ? components.hour : 0))
component.day = ((self.day != NSUndefinedDateComponent ? self.day : 0) +
(components.day != NSUndefinedDateComponent ? components.day : 0))
component.weekOfYear = ((self.weekOfYear != NSUndefinedDateComponent ? self.weekOfYear : 0) +
(components.weekOfYear != NSUndefinedDateComponent ? components.weekOfYear : 0))
component.month = ((self.month != NSUndefinedDateComponent ? self.month : 0) +
(components.month != NSUndefinedDateComponent ? components.month : 0))
component.year = ((self.year != NSUndefinedDateComponent ? self.year : 0) +
(components.year != NSUndefinedDateComponent ? components.year : 0))
return component
}
func addDate(sdate: NSDate) -> NSDate {
return currentCalendar.dateByAddingComponents(self, toDate:sdate, options:nil)
}
func subtract(components: NSDateComponents) -> NSDateComponents {
let component = NSDateComponents()
component.second = ((self.second != NSUndefinedDateComponent ? self.second : 0) -
(components.second != NSUndefinedDateComponent ? components.second : 0))
component.minute = ((self.minute != NSUndefinedDateComponent ? self.minute : 0) -
(components.minute != NSUndefinedDateComponent ? components.minute : 0))
component.hour = ((self.hour != NSUndefinedDateComponent ? self.hour : 0) -
(components.hour != NSUndefinedDateComponent ? components.hour : 0))
component.day = ((self.day != NSUndefinedDateComponent ? self.day : 0) -
(components.day != NSUndefinedDateComponent ? components.day : 0))
component.weekOfYear = ((self.weekOfYear != NSUndefinedDateComponent ? self.weekOfYear : 0) -
(components.weekOfYear != NSUndefinedDateComponent ? components.weekOfYear : 0))
component.month = ((self.month != NSUndefinedDateComponent ? self.month : 0) -
(components.month != NSUndefinedDateComponent ? components.month : 0))
component.year = ((self.year != NSUndefinedDateComponent ? self.year : 0) -
(components.year != NSUndefinedDateComponent ? components.year : 0))
return component
}
func subtractDate(sdate: NSDate) -> NSDate {
return currentCalendar.dateByAddingComponents(-self, toDate:sdate, options:nil)
}
}
extension NSDate {
class func yesterday() -> NSDate {
let component = NSDateComponents()
component.day = -1;
return currentCalendar.dateByAddingComponents(component, toDate: self.date(), options: nil)
}
class func tomorrow() -> NSDate {
let component = NSDateComponents()
component.day = +1;
return currentCalendar.dateByAddingComponents(component, toDate: self.date(), options: nil)
}
func ago(components:NSDateComponents) -> NSDate {
return currentCalendar.dateByAddingComponents(-components, toDate: self, options: nil)
}
func timeAgo() -> String {
return self.timeDateAgo(NSDate.date(), toDate: self)
}
func timeAgoShort() -> String {
return self.timeDateAgo(NSDate.date(), toDate: self, short:true)
}
func timeAgoLong(level:Int=999) -> String {
return self.timeDateAgo(NSDate.date(), toDate: self, level:level)
}
func timeAgoSimple() -> String {
return self.timeDateAgo(NSDate.date(), toDate: self, simple:true)
}
func dateTimeAgo() -> String {
return self.timeDateAgo(NSDate.date(), toDate: self, approximate: true)
}
func dateTimeAgoShort() -> String {
return self.timeDateAgo(NSDate.date(), toDate: self, approximate: true, short:true)
}
func dateTimeAgoLong(level:Int=999) -> String {
return self.timeDateAgo(NSDate.date(), toDate: self, approximate: true, level:level)
}
func timeDateAgo(fromDate:NSDate, toDate:NSDate, simple:Bool = false, approximate:Bool = false, short:Bool = false, level:Int = 0) -> String {
let seconds = fromDate.timeIntervalSinceDate(toDate)
if fabs(seconds) < 1 {
return bundle.localizedStringForKey("just now", value: nil, table: localizationTable);
}
let components = currentCalendar.components(significantUnits, fromDate: fromDate, toDate: toDate, options: nil)
if simple {
let simpleString = localizedSimpleStringForComponents(components)
if simpleString.isEmpty == false {
return simpleString
}
}
var string = String()
var isApproximate:Bool = false
var numberOfUnits:Int = 0
let unitList: String[] = ["year", "month", "week", "day", "hour", "minute", "second"]
for unitName in unitList {
let unit = calendarUnitFromString(unitName)
if (significantUnits & unit) && compareCalendarUnitSignificance(.SecondCalendarUnit, unit) != .OrderedDescending {
let number:NSNumber = NSNumber(float: fabsf(components.valueForKey(unitName).floatValue))
if Bool(number.integerValue) {
let suffix = String(format: bundle.localizedStringForKey("Suffix Expression Format String", value: "%@ %@", table: localizationTable), arguments: [number, localizedStringForNumber(number.unsignedIntegerValue, unit, short:short)])
if string.isEmpty {
string = suffix
} else if numberOfUnits < level {
string += String(format: " %@", arguments: [suffix])
} else {
isApproximate = true
}
numberOfUnits += 1
}
}
}
if string.isEmpty == false {
if seconds > 0 {
string = String(format: bundle.localizedStringForKey("Date Format String", value: "%@ %@", table: localizationTable), arguments: [string, bundle.localizedStringForKey("ago", value: nil, table: localizationTable)])
} else {
string = String(format: bundle.localizedStringForKey("Date Format String", value: "%@ %@", table: localizationTable), arguments: [string, bundle.localizedStringForKey("from now", value: nil, table: localizationTable)])
}
if (isApproximate && approximate) {
string = String(format: bundle.localizedStringForKey("about %@", value: nil, table: localizationTable), arguments: [string])
}
}
return string
}
func toLocal() -> NSDate {
let localTimeZone = NSTimeZone.localTimeZone()
let date = NSDate()
var secondsFromGMT = NSTimeInterval(localTimeZone.secondsFromGMTForDate(self))
return self.dateByAddingTimeInterval(secondsFromGMT)
}
func toGlobal() -> NSDate {
let localTimeZone = NSTimeZone.localTimeZone()
let date = NSDate()
var secondsFromGMT = -NSTimeInterval(localTimeZone.secondsFromGMTForDate(self))
return self.dateByAddingTimeInterval(secondsFromGMT)
}
func beginningOfDay() -> NSDate {
let components = currentCalendar.components(.YearCalendarUnit | .MonthCalendarUnit | .DayCalendarUnit, fromDate: self)
return currentCalendar.dateFromComponents(components);
}
func endOfDay() -> NSDate {
let components = NSDateComponents()
components.day = 1
return currentCalendar.dateByAddingComponents(components, toDate: self.beginningOfDay(), options: nil).dateByAddingTimeInterval(-1)
}
func beginningOfWeek() -> NSDate {
let components = currentCalendar.components(.YearCalendarUnit | .MonthCalendarUnit | .WeekdayCalendarUnit | .DayCalendarUnit, fromDate: self)
var offset = components.weekday - NSInteger(currentCalendar.firstWeekday)
components.day = components.day - offset
return currentCalendar.dateFromComponents(components)
}
func endOfWeek() -> NSDate {
let components = NSDateComponents()
components.setWeek(1)
return currentCalendar.dateByAddingComponents(components, toDate: self.beginningOfWeek(), options: nil).dateByAddingTimeInterval(-1)
}
func beginningOfMonth() -> NSDate {
let components = currentCalendar.components(.YearCalendarUnit | .MonthCalendarUnit, fromDate: self)
return currentCalendar.dateFromComponents(components)
}
func endOfMonth() -> NSDate {
let components = NSDateComponents()
components.month = 1
return currentCalendar.dateByAddingComponents(components, toDate: self.beginningOfMonth(), options: nil).dateByAddingTimeInterval(-1)
}
func beginningOfYear() -> NSDate {
let components = currentCalendar.components(.YearCalendarUnit, fromDate: self)
return currentCalendar.dateFromComponents(components)
}
func endOfYear() -> NSDate {
let components = NSDateComponents()
components.year = 1
return currentCalendar.dateByAddingComponents(components, toDate: self.beginningOfYear(), options: nil).dateByAddingTimeInterval(-1)
}
func format(sformat:String) -> String {
formatter.dateFormat = sformat
return formatter.stringFromDate(self)
}
func format(sdate:NSDateFormatterStyle = .NoStyle, stime:NSDateFormatterStyle = .NoStyle) -> String {
formatter.dateFormat = nil;
formatter.timeStyle = stime;
formatter.dateStyle = sdate;
return formatter.stringFromDate(self)
}
func add(components: NSDateComponents) -> NSDate {
let cal = NSCalendar.currentCalendar()
return cal.dateByAddingComponents(components, toDate: self, options: nil)
}
func subtract(components: NSDateComponents) -> NSDate {
func negateIfNeeded(i: NSInteger) -> NSInteger {
if i == NSUndefinedDateComponent {
return i
}
return -i
}
components.year = negateIfNeeded(components.year)
components.month = negateIfNeeded(components.month)
components.weekOfYear = negateIfNeeded(components.weekOfYear)
components.day = negateIfNeeded(components.day)
components.hour = negateIfNeeded(components.hour)
components.minute = negateIfNeeded(components.minute)
components.second = negateIfNeeded(components.second)
components.nanosecond = negateIfNeeded(components.nanosecond)
return self.add(components)
}
}
extension Int {
var second: NSDateComponents {
var components = NSDateComponents()
components.second = self
return components
}
var seconds: NSDateComponents {
return self.second
}
var minute: NSDateComponents {
var components = NSDateComponents()
components.minute = self
return components
}
var minutes: NSDateComponents {
return self.minute
}
var hour: NSDateComponents {
var components = NSDateComponents()
components.hour = self
return components
}
var hours: NSDateComponents {
return self.hour
}
var day: NSDateComponents {
var components = NSDateComponents()
components.day = self
return components
}
var days: NSDateComponents {
return self.day
}
var week: NSDateComponents {
var components = NSDateComponents()
components.weekOfYear = self
return components
}
var weeks: NSDateComponents {
return self.week
}
var month: NSDateComponents {
var components = NSDateComponents()
components.month = self
return components
}
var months: NSDateComponents {
return self.month
}
var year: NSDateComponents {
var components = NSDateComponents()
components.year = self
return components
}
var years: NSDateComponents {
return self.year
}
}
@prefix func -(comps: NSDateComponents) -> NSDateComponents {
let result = NSDateComponents()
if(comps.second != NSUndefinedDateComponent) { result.second = -comps.second }
if(comps.minute != NSUndefinedDateComponent) { result.minute = -comps.minute }
if(comps.hour != NSUndefinedDateComponent) { result.hour = -comps.hour }
if(comps.day != NSUndefinedDateComponent) { result.day = -comps.day }
if(comps.weekOfYear != NSUndefinedDateComponent) { result.weekOfYear = -comps.weekOfYear }
if(comps.month != NSUndefinedDateComponent) { result.month = -comps.month }
if(comps.year != NSUndefinedDateComponent) { result.year = -comps.year }
return result
}
@infix func + (left: NSDate, right:NSDate) -> NSDate {
return left.dateByAddingTimeInterval(right.timeIntervalSinceNow)
}
@infix func + (left: NSDate, right:NSTimeInterval) -> NSDate {
return left.dateByAddingTimeInterval(right)
}
@infix func + (left: NSDate, right:NSDateComponents) -> NSDate {
return left.add(right);
}
@infix func + (left: NSDateComponents, right:NSDate) -> NSDate {
return left.addDate(right);
}
@infix func - (left: NSDate, right:NSDate) -> NSDate {
return left.dateByAddingTimeInterval(-right.timeIntervalSinceNow)
}
@infix func - (left: NSDate, right:NSTimeInterval) -> NSDate {
return left.dateByAddingTimeInterval(-right)
}
@infix func - (left: NSDate, right:NSDateComponents) -> NSDate {
return left.subtract(right);
}
@infix func - (left: NSDateComponents, right:NSDate) -> NSDate {
return left.subtractDate(right);
}
@infix func + (left: NSDateComponents, right: NSDateComponents) -> NSDateComponents {
return left.add(right)
}
@infix func - (left: NSDateComponents, right: NSDateComponents) -> NSDateComponents {
return left.subtract(right)
} | mit | 22b208ab1fe9fda4e6bea621753135ad | 44.517021 | 262 | 0.665389 | 4.910927 | false | false | false | false |
ZuoCaiSong/DouYuZB | DYZB/DYZB/Classes/Home/view/PageTitleView.swift | 1 | 3859 | //
// PageTitleView.swift
// DYZB
//
// Created by supin-tech on 2017/5/25.
// Copyright © 2017年 supin. All rights reserved.
//
import UIKit
// MARK: - 定义常量
private let KScrollLineH : CGFloat = 2
private let kNormalColor : (CGFloat, CGFloat, CGFloat) = (85, 85, 85)
private let kSelectColor : (CGFloat, CGFloat, CGFloat) = (255, 128, 0)
class PageTitleView: UIView {
fileprivate var titles: [String]
// MARK: - 懒加载属性
fileprivate lazy var titleLabels : [UILabel] = [UILabel]()
fileprivate lazy var scrollView: UIScrollView = {
let scrollView = UIScrollView()
scrollView.showsHorizontalScrollIndicator = false
scrollView.scrollsToTop = false
scrollView.bounces = false
return scrollView
}()
fileprivate lazy var scrollLine : UIView = { //滚动的线条
let scrollLine = UIView()
scrollLine.backgroundColor = UIColor.orange
return scrollLine
}()
// 自定义构造函数
init(frame: CGRect, titles: [String]) {
self.titles = titles
super.init(frame: frame)
// 设置UI
setupUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
// MARK:- 设置UI界面
fileprivate extension PageTitleView {
fileprivate func setupUI() {
//1. 添加UIScrollView
addSubview(scrollView)
scrollView.frame = bounds
//2.添加title到对应的label
setUptitleLabels()
// 3.设置底线和滚动的滑块
setupBottomLineAndScrollLine()
}
fileprivate func setUptitleLabels() {
// 0. 确定label的一些frame的值
let labelW : CGFloat = frame.width / CGFloat(titles.count)
let labelH : CGFloat = frame.height - KScrollLineH
let labelY : CGFloat = 0
for (index, title) in titles.enumerated(){
// 1.创建label
let label = UILabel()
// 2.设置Label的属性
label.text = title
label.tag = index
label.font = UIFont.systemFont(ofSize: 16.0)
label.textColor = UIColor(r: kNormalColor.0, g: kNormalColor.1, b: kNormalColor.2)
label.textAlignment = .center
// 3.设置label的frame
let labelX: CGFloat = labelW * CGFloat(index)
label.frame = CGRect(x: labelX, y: labelY, width: labelW, height: labelH)
// 4.添加、保存
scrollView.addSubview(label)
titleLabels.append(label)
// 5. 给label添加手势
label.isUserInteractionEnabled = true;
// let tapGes = UITapGestureRecognizer(target: self, action: #selector(self.titleLabelClick(_:)))
// label.addGestureRecognizer(tapGes)
}
}
fileprivate func setupBottomLineAndScrollLine() {
// 1. 添加底线
let bottomLine = UIView()
bottomLine.backgroundColor = UIColor.lightGray
let lineH : CGFloat = 0.5
bottomLine.frame = CGRect(x: 0, y: frame.height - lineH, width: frame.width, height: lineH)
addSubview(bottomLine)
// 2 添加scrollViewLine
guard let firstLabel = titleLabels.first else {
return
}
firstLabel.textColor = UIColor(r: kSelectColor.0, g: kSelectColor.1, b: kSelectColor.2)
scrollView.addSubview(scrollLine)
scrollLine.frame = CGRect(x: firstLabel.frame.origin.x, y: frame.height - KScrollLineH, width: firstLabel.frame.width, height: KScrollLineH)
}
}
| mit | a9a2bd7eb817e2781321eac8472e7113 | 25.992701 | 148 | 0.57112 | 4.898013 | false | false | false | false |
HasanEdain/NPCVersionShareSheet | NPCVersionShareSheet/NPCBundleHelper.swift | 1 | 3326 | //
// NPCBundleHelper.swift
// NPCVersionShareSheet
//
// Created by Hasan D Edain on 11/23/16.
// Copyright © 2016 NPC Unlimited. All rights reserved.
//
import Foundation
public class NPCBundleHelper {
/// Convenience Wrapper around Bundle allFrameworks
/// Returns ONLY bundles with Bundle Identifiers
public static func allBundles() -> [Bundle] {
let all = Bundle.allFrameworks
var allWithBundles = [Bundle]()
for bundle in all {
if bundle.bundleIdentifier != nil {
allWithBundles.append(bundle)
}
}
return allWithBundles
}
/// All bundles that do not contain com.apple
public static func allNonAppleBundles() -> [Bundle] {
let all = NPCBundleHelper.allBundles()
var nonApple = [Bundle]()
for bundle in all {
if let identifier = bundle.bundleIdentifier {
if identifier.contains("com.apple") != true {
nonApple.append(bundle)
}
}
}
return nonApple
}
// Filter
/// Filter a list of Bundles with a string (compares to the bundle identifier)
/// @return [Bundle]
public static func filterBundleList(bundleList: [Bundle], filterString: String) -> [Bundle] {
var filteredBundles = [Bundle]()
for bundle in bundleList {
if let bunldeIdentifier = bundle.bundleIdentifier {
let lcBundleId = bunldeIdentifier.lowercased()
let lcFilterString = filterString.lowercased()
if lcBundleId.contains(lcFilterString) {
filteredBundles.append(bundle)
}
}
}
return filteredBundles
}
// Text
/// A string rendering of each Bundle in the array
/// @return String
public static func bundleListString(bundleList: [Bundle]) -> String {
var bundlesString = ""
for bundle in bundleList {
let bundleString = NPCBundleHelper.bundleString(bundle: bundle)
bundlesString.append(bundleString)
}
return bundlesString
}
/// A string representation of a Bundle
public static func bundleString(bundle: Bundle) -> String {
var bundleIdentifierString: String
if let bndleIdentifierString = bundle.bundleIdentifier {
bundleIdentifierString = bndleIdentifierString
} else {
bundleIdentifierString = ""
}
var versionString: String
if let shortVersionString = (bundle.object(forInfoDictionaryKey: "CFBundleShortVersionString")) as? String {
versionString = shortVersionString
if let cfVersionString = (bundle.object(forInfoDictionaryKey: "CFBundleVersion")) as? String {
versionString = "\(shortVersionString) (\(cfVersionString))"
}
} else {
versionString = ""
}
var nameString: String
if let cfNameString = (bundle.object(forInfoDictionaryKey: "CFBundleName")) as? String {
nameString = cfNameString
} else {
nameString = ""
}
let bndlString = "\n\(nameString)\n\(versionString)\n\(bundleIdentifierString)\n-----------"
return bndlString
}
}
| mit | b7c647eee8a79821346d497e26ddc7a2 | 29.504587 | 116 | 0.599398 | 5.099693 | false | false | false | false |
ubi-naist/SenStick | ios/SenStickViewer/SenStickViewer/GyroDataModel.swift | 1 | 1152 | //
// GyroCellView.swift
// SenStickViewer
//
// Created by AkihiroUehara on 2016/05/25.
// Copyright © 2016年 AkihiroUehara. All rights reserved.
//
import UIKit
import SenStickSDK
import CoreMotion
class GyroDataModel : SensorDataModel<RotationRange, CMRotationRate>
{
override init() {
super.init()
self.sensorName = "gyro"
self.csvHeader = "Gyro.X,Gyro.Y,Gyro.Z"
self.csvEmptyData = ",,"
}
// MARK: - Private methods
override func updateRange(_ range: RotationRange) -> Void
{
switch(range) {
case .rotationRange250DPS:
self.maxValue = 5
self.minValue = -5
case .rotationRange500DPS:
self.maxValue = 10
self.minValue = -10
case .rotationRange1000DPS:
self.maxValue = 20
self.minValue = -20
case .rotationRange2000DPS:
self.maxValue = 40
self.minValue = -40
}
}
override func dataToArray(_ data: CMRotationRate) -> [Double]
{
return [data.x, data.y, data.z]
}
}
| mit | b3bb3586ad91e8a32f7dbd53b3cd962b | 22.44898 | 68 | 0.557006 | 3.934932 | false | false | false | false |
Suninus/XLForm | Examples/Swift/Examples/AccessoryViews/AccessoryViewFormViewController.swift | 9 | 11404 | //
// AccessoryViewFormViewController.m
// XLForm ( https://github.com/xmartlabs/XLForm )
//
// Copyright (c) 2015 Xmartlabs ( http://xmartlabs.com )
//
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#import "XLForm.h"
#import "AccessoryViewFormViewController.h"
//This macro defines if we use predicates to hide rows or do it manually the old way.
//Just comment out if you want it to run without predicates.
#define USE_PREDICATES_FOR_HIDING
@interface AccessoryViewFormViewController ()
@end
@implementation AccessoryViewFormViewController
{
#ifndef USE_PREDICATES_FOR_HIDING
XLFormRowDescriptor * _rowShowAccessoryView;
XLFormRowDescriptor * _rowStopDisableRow;
XLFormRowDescriptor * _rowStopInlineRow;
XLFormRowDescriptor * _rowSkipCanNotBecomeFirstResponderRow;
#endif
}
NSString * kAccessoryViewRowNavigationEnabled = @"kRowNavigationEnabled";
NSString * kAccessoryViewRowNavigationShowAccessoryView = @"kRowNavigationShowAccessoryView";
NSString * kAccessoryViewRowNavigationStopDisableRow = @"rowNavigationStopDisableRow";
NSString * kAccessoryViewRowNavigationSkipCanNotBecomeFirstResponderRow = @"rowNavigationSkipCanNotBecomeFirstResponderRow";
NSString * kAccessoryViewRowNavigationStopInlineRow = @"rowNavigationStopInlineRow";
NSString * kAccessoryViewName = @"name";
NSString * kAccessoryViewEmail = @"email";
NSString * kAccessoryViewTwitter = @"twitter";
NSString * kAccessoryViewUrl = @"url";
NSString * kAccessoryViewDate = @"date";
NSString * kAccessoryViewTextView = @"textView";
NSString * kAccessoryViewCheck = @"check";
NSString * kAccessoryViewNotes = @"notes";
-(id)init
{
self = [super init];
if (self) {
[self initializeForm];
}
return self;
}
-(void)initializeForm
{
XLFormDescriptor * formDescriptor = [XLFormDescriptor formDescriptorWithTitle:@"Accessory View"];
formDescriptor.rowNavigationOptions = XLFormRowNavigationOptionEnabled;
XLFormSectionDescriptor * section;
XLFormRowDescriptor * row;
XLFormRowDescriptor * switchRow;
// Configuration section
section = [XLFormSectionDescriptor formSectionWithTitle:@"Row Navigation Settings"];
section.footerTitle = @"Changing the Settings values you will navigate differently";
[formDescriptor addFormSection:section];
// RowNavigationEnabled
switchRow = [XLFormRowDescriptor formRowDescriptorWithTag:kAccessoryViewRowNavigationEnabled rowType:XLFormRowDescriptorTypeBooleanSwitch title:@"Row Navigation Enabled?"];
switchRow.value = @YES;
[section addFormRow:switchRow];
// RowNavigationShowAccessoryView
row = [XLFormRowDescriptor formRowDescriptorWithTag:kAccessoryViewRowNavigationShowAccessoryView rowType:XLFormRowDescriptorTypeBooleanCheck title:@"Show input accessory row?"];
row.value = @((formDescriptor.rowNavigationOptions & XLFormRowNavigationOptionEnabled) == XLFormRowNavigationOptionEnabled);
[section addFormRow:row];
#ifdef USE_PREDICATES_FOR_HIDING
row.hidden = [NSString stringWithFormat:@"$%@ == 0", switchRow];
#else
_rowShowAccessoryView = row;
#endif
// RowNavigationStopDisableRow
row = [XLFormRowDescriptor formRowDescriptorWithTag:kAccessoryViewRowNavigationStopDisableRow rowType:XLFormRowDescriptorTypeBooleanCheck title:@"Stop when reach disabled row?"];
row.value = @((formDescriptor.rowNavigationOptions & XLFormRowNavigationOptionStopDisableRow) == XLFormRowNavigationOptionStopDisableRow);
[section addFormRow:row];
#ifdef USE_PREDICATES_FOR_HIDING
row.hidden = [NSString stringWithFormat:@"$%@ == 0", switchRow];
#else
_rowStopDisableRow = row;
#endif
// RowNavigationStopInlineRow
row = [XLFormRowDescriptor formRowDescriptorWithTag:kAccessoryViewRowNavigationStopInlineRow rowType:XLFormRowDescriptorTypeBooleanCheck title:@"Stop when reach inline row?"];
row.value = @((formDescriptor.rowNavigationOptions & XLFormRowNavigationOptionStopInlineRow) == XLFormRowNavigationOptionStopInlineRow);
[section addFormRow:row];
#ifdef USE_PREDICATES_FOR_HIDING
row.hidden = [NSString stringWithFormat:@"$%@ == 0", switchRow];
#else
_rowStopInlineRow = row;
#endif
// RowNavigationSkipCanNotBecomeFirstResponderRow
row = [XLFormRowDescriptor formRowDescriptorWithTag:kAccessoryViewRowNavigationSkipCanNotBecomeFirstResponderRow rowType:XLFormRowDescriptorTypeBooleanCheck title:@"Skip Can Not Become First Responder Row?"];
row.value = @((formDescriptor.rowNavigationOptions & XLFormRowNavigationOptionSkipCanNotBecomeFirstResponderRow) == XLFormRowNavigationOptionSkipCanNotBecomeFirstResponderRow);
[section addFormRow:row];
#ifdef USE_PREDICATES_FOR_HIDING
row.hidden = [NSString stringWithFormat:@"$%@ == 0", switchRow];
#else
_rowSkipCanNotBecomeFirstResponderRow = row;
#endif
// Basic Information - Section
section = [XLFormSectionDescriptor formSectionWithTitle:@"TextField Types"];
section.footerTitle = @"This is a long text that will appear on section footer";
[formDescriptor addFormSection:section];
// Name
row = [XLFormRowDescriptor formRowDescriptorWithTag:kAccessoryViewName rowType:XLFormRowDescriptorTypeText title:@"Name"];
row.required = YES;
[section addFormRow:row];
// Email
row = [XLFormRowDescriptor formRowDescriptorWithTag:kAccessoryViewEmail rowType:XLFormRowDescriptorTypeEmail title:@"Email"];
// validate the email
[row addValidator:[XLFormValidator emailValidator]];
[section addFormRow:row];
// Twitter
row = [XLFormRowDescriptor formRowDescriptorWithTag:kAccessoryViewTwitter rowType:XLFormRowDescriptorTypeTwitter title:@"Twitter"];
row.disabled = @YES;
row.value = @"@no_editable";
[section addFormRow:row];
// Url
row = [XLFormRowDescriptor formRowDescriptorWithTag:kAccessoryViewUrl rowType:XLFormRowDescriptorTypeURL title:@"Url"];
[section addFormRow:row];
// Url
row = [XLFormRowDescriptor formRowDescriptorWithTag:kAccessoryViewDate rowType:XLFormRowDescriptorTypeDateInline title:@"Date Inline"];
row.value = [NSDate new];
[section addFormRow:row];
section = [XLFormSectionDescriptor formSection];
[formDescriptor addFormSection:section];
row = [XLFormRowDescriptor formRowDescriptorWithTag:kAccessoryViewTextView rowType:XLFormRowDescriptorTypeTextView];
[row.cellConfigAtConfigure setObject:@"TEXT VIEW EXAMPLE" forKey:@"textView.placeholder"];
[section addFormRow:row];
row = [XLFormRowDescriptor formRowDescriptorWithTag:kAccessoryViewCheck rowType:XLFormRowDescriptorTypeBooleanCheck title:@"Ckeck"];
[section addFormRow:row];
section = [XLFormSectionDescriptor formSectionWithTitle:@"TextView With Label Example"];
[formDescriptor addFormSection:section];
row = [XLFormRowDescriptor formRowDescriptorWithTag:kAccessoryViewNotes rowType:XLFormRowDescriptorTypeTextView title:@"Notes"];
[section addFormRow:row];
self.form = formDescriptor;
}
#pragma mark - XLFormDescriptorDelegate
-(void)formRowDescriptorValueHasChanged:(XLFormRowDescriptor *)rowDescriptor oldValue:(id)oldValue newValue:(id)newValue
{
[super formRowDescriptorValueHasChanged:rowDescriptor oldValue:oldValue newValue:newValue];
#ifndef USE_PREDICATES_FOR_HIDING
NSString * kRowNavigationEnabled = @"kRowNavigationEnabled";
if ([rowDescriptor.tag isEqualToString:kRowNavigationEnabled]){
if ([[rowDescriptor.value valueData] isEqual:@NO]){
self.form.rowNavigationOptions = XLFormRowNavigationOptionNone;
[self.form removeFormRowWithTag:kAccessoryViewRowNavigationShowAccessoryView];
[self.form removeFormRowWithTag:kAccessoryViewRowNavigationStopDisableRow];
[self.form removeFormRowWithTag:kAccessoryViewRowNavigationStopInlineRow];
[self.form removeFormRowWithTag:kAccessoryViewRowNavigationSkipCanNotBecomeFirstResponderRow];
}
else{
self.form.rowNavigationOptions = XLFormRowNavigationOptionEnabled;
_rowShowAccessoryView.value = @YES;
_rowStopDisableRow.value = @NO;
_rowStopInlineRow.value = @NO;
_rowSkipCanNotBecomeFirstResponderRow.value = @NO;
[self.form addFormRow:_rowShowAccessoryView afterRow:rowDescriptor];
[self.form addFormRow:_rowStopDisableRow afterRow:_rowShowAccessoryView];
[self.form addFormRow:_rowStopInlineRow afterRow:_rowStopDisableRow];
[self.form addFormRow:_rowSkipCanNotBecomeFirstResponderRow afterRow:_rowStopInlineRow];
}
}
else
#endif
if ([rowDescriptor.tag isEqualToString:kAccessoryViewRowNavigationStopDisableRow]){
if ([[rowDescriptor.value valueData] isEqual:@(YES)]){
self.form.rowNavigationOptions = self.form.rowNavigationOptions | XLFormRowNavigationOptionStopDisableRow;
}
else{
self.form.rowNavigationOptions = self.form.rowNavigationOptions & (~XLFormRowNavigationOptionStopDisableRow);
}
}
else if ([rowDescriptor.tag isEqualToString:kAccessoryViewRowNavigationStopInlineRow]){
if ([[rowDescriptor.value valueData] isEqual:@(YES)]){
self.form.rowNavigationOptions = self.form.rowNavigationOptions | XLFormRowNavigationOptionStopInlineRow;
}
else{
self.form.rowNavigationOptions = self.form.rowNavigationOptions & (~XLFormRowNavigationOptionStopInlineRow);
}
}
else if ([rowDescriptor.tag isEqualToString:kAccessoryViewRowNavigationSkipCanNotBecomeFirstResponderRow]){
if ([[rowDescriptor.value valueData] isEqual:@(YES)]){
self.form.rowNavigationOptions = self.form.rowNavigationOptions | XLFormRowNavigationOptionSkipCanNotBecomeFirstResponderRow;
}
else{
self.form.rowNavigationOptions = self.form.rowNavigationOptions & (~XLFormRowNavigationOptionSkipCanNotBecomeFirstResponderRow);
}
}
}
-(UIView *)inputAccessoryViewForRowDescriptor:(XLFormRowDescriptor *)rowDescriptor
{
if ([[[self.form formRowWithTag:kAccessoryViewRowNavigationShowAccessoryView].value valueData] isEqual:@NO]){
return nil;
}
return [super inputAccessoryViewForRowDescriptor:rowDescriptor];
}
@end
| mit | 1632c3a15a25adb3a5ec0e97375058f8 | 44.616 | 212 | 0.758067 | 5.061696 | false | false | false | false |
ethanneff/organize | Organize/SearchViewController.swift | 1 | 2193 | import UIKit
class SearchViewController: UIViewController {
override func loadView() {
super.loadView()
setupView()
}
func setupView() {
var constraints: [NSLayoutConstraint] = []
view.backgroundColor = Constant.Color.background
// scroll view
let scrollView = UIScrollView()
var scrollViewHeight: CGFloat = 0
scrollView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(scrollView)
// label
let label = UILabel()
label.text = "coming soon..."
label.textAlignment = .Center
label.translatesAutoresizingMaskIntoConstraints = false
scrollView.addSubview(label)
constraints.append(NSLayoutConstraint(item: label, attribute: .Leading, relatedBy: .Equal, toItem: view, attribute: .Leading, multiplier: 1, constant: 0))
constraints.append(NSLayoutConstraint(item: label, attribute: .Trailing, relatedBy: .Equal, toItem: view, attribute: .Trailing, multiplier: 1, constant: 0))
constraints.append(NSLayoutConstraint(item: label, attribute: .CenterY, relatedBy: .Equal, toItem: scrollView, attribute: .CenterY, multiplier: 1, constant: 0))
constraints.append(NSLayoutConstraint(item: label, attribute: .Height, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1, constant: Constant.Button.height))
scrollViewHeight += Constant.Button.height
// scroll view
constraints.append(NSLayoutConstraint(item: scrollView, attribute: .Top, relatedBy: .Equal, toItem: view, attribute: .Top, multiplier: 1, constant: 0))
constraints.append(NSLayoutConstraint(item: scrollView, attribute: .Bottom, relatedBy: .Equal, toItem: view, attribute: .Bottom, multiplier: 1, constant: 0))
constraints.append(NSLayoutConstraint(item: scrollView, attribute: .Leading, relatedBy: .Equal, toItem: view, attribute: .Leading, multiplier: 1, constant: 0))
constraints.append(NSLayoutConstraint(item: scrollView, attribute: .Trailing, relatedBy: .Equal, toItem: view, attribute: .Trailing, multiplier: 1, constant: 0))
scrollView.contentSize = CGSize(width: scrollView.frame.size.width, height: scrollViewHeight)
NSLayoutConstraint.activateConstraints(constraints)
}
}
| mit | e4e67315993ad1eacd6792a9bf4478ce | 51.214286 | 184 | 0.746922 | 4.665957 | false | false | false | false |
FelixMLians/AlgorithmDaily | AlgorithmDaily0804/ViewController.swift | 1 | 1907 | //
// ViewController.swift
// AlgorithmDaily0804
//
// Created by felix on 16/8/4.
// Copyright © 2016年 felix. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
// MARK: - Combinations
func myCombinations() -> () {
let com = Combinations();
let res = com.combine(5, k: 3);
print(res)
}
// MARK: - removeDuplicatesFromSortedList
func removeDuplicatesFromSortedList() -> () {
let arr = [1, 2, 2, 3, 3, 4]
let head: ListNode = ListNode.init(_val: 1)
var beforeTemp: ListNode = head
for i in arr {
print("before \(beforeTemp.val)")
beforeTemp.next = ListNode.init(_val: i)
beforeTemp = beforeTemp.next!
}
let resultListNode = deleteDuplicates(head);
var afterTemp: ListNode = resultListNode!
while afterTemp.next != nil {
print("after \(afterTemp.val)")
afterTemp = afterTemp.next!
}
}
func deleteDuplicates(head: ListNode?) -> ListNode? {
if head == nil || head?.next == nil {
return head;
}
var pre = head
var pres = head!.next
while pres != nil {
if pre!.val == pres!.val {
pres = pres!.next
pre!.next = pres
}
else {
pre = pres
pres = pres!.next
}
}
return head;
}
}
// definition
public class ListNode {
public var val: Int
public var next: ListNode?
public init(_val: Int) {
self.val = _val;
self.next = nil;
}
}
| mit | afd3bdd4650452e947593a44afd57fc5 | 22.8 | 80 | 0.5 | 4.448598 | false | false | false | false |
feighter09/Cloud9 | SoundCloud Pro/AppDelegate.swift | 1 | 8677 | //
// AppDelegate.swift
// SoundCloud Pro
//
// Created by Austin Feight on 6/30/15.
// Copyright (c) 2015 Lost in Flight. All rights reserved.
//
import UIKit
import Parse
import AVFoundation
let kSoundCloudClientID = "823363d3a8c33bfb0a1c608da13141b2"
let kSoundCloudClientSecret = "ad456d110c3c4a8f7ac9dacfb2f3c6c6"
let kSoundCloudAuthURL = "soundcloudpro://OAuth"
let kSoundCloudDidAuthenticate = "soundCloudDidAuthenticate"
let kParseApplicationId = "Xbb0RlJY5ph6YwusEiKmvBiaIbI85A88oYipzcTZ"
let kParseClientKey = "4pOtIpBxfHZHsc96smkLLXL6bwZuOtG9ZjQZOT3e"
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool
{
SCSoundCloud.setClientID(kSoundCloudClientID, secret: kSoundCloudClientSecret, redirectURL: NSURL(string: kSoundCloudAuthURL))
initParse()
initBackgroundAudio()
setGlobalColors()
showLoginViewControllerIfNecessary()
return true
}
private func initParse()
{
Parse.setApplicationId(kParseApplicationId, clientKey: kParseClientKey)
PFUser.registerSubclass()
ParsePlaylist.registerSubclass()
Follow.registerSubclass()
}
private func initBackgroundAudio()
{
let audioSession = AVAudioSession.sharedInstance()
do {
try audioSession.setCategory(AVAudioSessionCategoryPlayback)
try audioSession.setActive(true)
}
catch {
ErrorHandler.handleBackgroundAudioError()
}
}
private func setGlobalColors()
{
setNavigationBarColors()
setTableViewColors()
setTableViewCellColors()
setSearchColors()
setSegmentedControlColors()
}
private func showLoginViewControllerIfNecessary()
{
if SCSoundCloud.account() == nil || PFUser.currentUser() == nil {
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let loginViewController = storyboard.instantiateViewControllerWithIdentifier(kLoginViewControllerIdentifier)
window!.rootViewController = loginViewController
window?.makeKeyAndVisible()
}
}
private func setNavigationBarColors()
{
UINavigationBar.appearance().barTintColor = .lightBackgroundColor
UINavigationBar.appearance().tintColor = .primaryColor
UINavigationBar.appearance().titleTextAttributes = [NSForegroundColorAttributeName : UIColor.primaryColor]
}
private func setTableViewColors()
{
UITableView.appearance().separatorColor = .secondaryColor
UITableView.appearance().backgroundColor = .backgroundColor
}
private func setTableViewCellColors()
{
UITableViewCell.appearance().backgroundColor = .backgroundColor
let selectedBackgroundView = UIView()
selectedBackgroundView.backgroundColor = .lightBackgroundColor
UITableViewCell.appearance().selectedBackgroundView = selectedBackgroundView
if #available(iOS 9.0, *) {
UILabel.appearanceWhenContainedInInstancesOfClasses([UITableViewCell.self]).textColor = .primaryColor
}
}
private func setSearchColors()
{
UISearchBar.appearance().backgroundColor = .backgroundColor
UISearchBar.appearance().barTintColor = .secondaryColor
UISearchBar.appearance().tintColor = .primaryColor
if #available(iOS 9.0, *) {
UITextField.appearanceWhenContainedInInstancesOfClasses([UISearchBar.self]).textColor = .secondaryColor
}
UITextField.appearance().keyboardAppearance = .Dark
}
private func setSegmentedControlColors()
{
UISegmentedControl.appearance().tintColor = .secondaryColor
let textAttributes = [NSForegroundColorAttributeName : UIColor.primaryColor]
UISegmentedControl.appearance().setTitleTextAttributes(textAttributes, forState: .Normal)
}
}
// MARK: - URL Handling
extension AppDelegate {
func application(application: UIApplication, handleOpenURL url: NSURL) -> Bool
{
return handleOpenURL(url)
}
func application(app: UIApplication, openURL url: NSURL, options: [String : AnyObject]) -> Bool
{
return handleOpenURL(url)
}
private func handleOpenURL(url: NSURL) -> Bool
{
NSLog("opening url: \(url)")
if isAuthUrl(url) {
SCSoundCloud.handleRedirectURL(url)
NSNotificationCenter.defaultCenter().postNotificationName(kSoundCloudDidAuthenticate, object: nil)
return true
}
return false
}
private func isAuthUrl(url: NSURL) -> Bool
{
return url.absoluteString.hasPrefix(kSoundCloudAuthURL)
}
}
extension AppDelegate {
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
// self.saveContext()
}
// MARK: - Core Data stack
// lazy var applicationDocumentsDirectory: NSURL = {
// // The directory the application uses to store the Core Data store file.
// // This code uses a directory named "com.LostInFlight.SoundCloud_Pro"
// // in the application's documents Application Support directory.
// let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
// return urls[urls.count - 1] as NSURL
// }()
//
// lazy var managedObjectModel: NSManagedObjectModel = {
// // The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model.
// let modelURL = NSBundle.mainBundle().URLForResource("SoundCloud_Pro", withExtension: "momd")!
// return NSManagedObjectModel(contentsOfURL: modelURL)!
// }()
//
// lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = {
// // The persistent store coordinator for the application. This implementation creates and return a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail.
// // Create the coordinator and store
// var coordinator: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
// let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("SoundCloud_Pro.sqlite")
// var error: NSError? = nil
// var failureReason = "There was an error creating or loading the application's saved data."
//
// if coordinator!.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil) == nil {
// coordinator = nil
// // Report any error we got.
// var dict = [String: AnyObject]()
// dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data"
// dict[NSLocalizedFailureReasonErrorKey] = failureReason
// dict[NSUnderlyingErrorKey] = error
// error = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
// // Replace this with code to handle the error appropriately.
// // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
// NSLog("Unresolved error \(error), \(error!.userInfo)")
// abort()
// }
//
// return coordinator
// }()
//
// lazy var managedObjectContext: NSManagedObjectContext? = {
// // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail.
// let coordinator = self.persistentStoreCoordinator
// if coordinator == nil {
// return nil
// }
// var managedObjectContext = NSManagedObjectContext()
// managedObjectContext.persistentStoreCoordinator = coordinator
// return managedObjectContext
// }()
//
// // MARK: - Core Data Saving support
//
// func saveContext () {
// if let moc = self.managedObjectContext {
// var error: NSError? = nil
// if moc.hasChanges && !moc.save(&error) {
// // Replace this implementation with code to handle the error appropriately.
// // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
// NSLog("Unresolved error \(error), \(error!.userInfo)")
// abort()
// }
// }
// }
}
| lgpl-3.0 | 0e611fbd99c22f1b56cbc1daf6350e82 | 36.240343 | 288 | 0.729054 | 4.833983 | false | false | false | false |
jvesala/teknappi | teknappi/Pods/RxSwift/RxSwift/Observables/Implementations/Timer.swift | 27 | 2185 | //
// Timer.swift
// RxSwift
//
// Created by Krunoslav Zaher on 6/7/15.
// Copyright (c) 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
class TimerSink<S: SchedulerType, O: ObserverType where O.E == Int64> : Sink<O> {
typealias Parent = Timer<S>
let parent: Parent
init(parent: Parent, observer: O, cancel: Disposable) {
self.parent = parent
super.init(observer: observer, cancel: cancel)
}
func run() -> Disposable {
return self.parent.scheduler.schedulePeriodic(0 as Int64, startAfter: self.parent.dueTime, period: self.parent.period!) { state in
self.observer?.on(.Next(state))
return state &+ 1
}
}
}
class TimerOneOffSink<S: SchedulerType, O: ObserverType where O.E == Int64> : Sink<O> {
typealias Parent = Timer<S>
let parent: Parent
init(parent: Parent, observer: O, cancel: Disposable) {
self.parent = parent
super.init(observer: observer, cancel: cancel)
}
func run() -> Disposable {
return self.parent.scheduler.scheduleRelative((), dueTime: self.parent.dueTime) { (_) -> Disposable in
self.observer?.on(.Next(0))
self.observer?.on(.Completed)
return NopDisposable.instance
}
}
}
class Timer<S: SchedulerType>: Producer<Int64> {
typealias TimeInterval = S.TimeInterval
let scheduler: S
let dueTime: TimeInterval
let period: TimeInterval?
init(dueTime: TimeInterval, period: TimeInterval?, scheduler: S) {
self.scheduler = scheduler
self.dueTime = dueTime
self.period = period
}
override func run<O : ObserverType where O.E == Int64>(observer: O, cancel: Disposable, setSink: (Disposable) -> Void) -> Disposable {
if let _ = period {
let sink = TimerSink(parent: self, observer: observer, cancel: cancel)
setSink(sink)
return sink.run()
}
else {
let sink = TimerOneOffSink(parent: self, observer: observer, cancel: cancel)
setSink(sink)
return sink.run()
}
}
} | gpl-3.0 | f706ad701f43c932426fa879dedb3b5a | 28.540541 | 138 | 0.602288 | 4.226306 | false | false | false | false |
boqian2000/swift-algorithm-club | Graph/GraphTests/GraphTests.swift | 2 | 5038 | //
// GraphTests.swift
// GraphTests
//
// Created by Andrew McKnight on 5/8/16.
//
import XCTest
@testable import Graph
class GraphTests: XCTestCase {
func testAdjacencyMatrixGraphDescription() {
let graph = AdjacencyMatrixGraph<String>()
let a = graph.createVertex("a")
let b = graph.createVertex("b")
let c = graph.createVertex("c")
graph.addDirectedEdge(a, to: b, withWeight: 1.0)
graph.addDirectedEdge(b, to: c, withWeight: 2.0)
let expectedValue = " ø 1.0 ø \n ø ø 2.0 \n ø ø ø "
XCTAssertEqual(graph.description, expectedValue)
}
func testAdjacencyListGraphDescription() {
let graph = AdjacencyListGraph<String>()
let a = graph.createVertex("a")
let b = graph.createVertex("b")
let c = graph.createVertex("c")
graph.addDirectedEdge(a, to: b, withWeight: 1.0)
graph.addDirectedEdge(b, to: c, withWeight: 2.0)
graph.addDirectedEdge(a, to: c, withWeight: -5.5)
let expectedValue = "a -> [(b: 1.0), (c: -5.5)]\nb -> [(c: 2.0)]"
XCTAssertEqual(graph.description, expectedValue)
}
func testAddingPreexistingVertex() {
let adjacencyList = AdjacencyListGraph<String>()
let adjacencyMatrix = AdjacencyMatrixGraph<String>()
for graph in [adjacencyList, adjacencyMatrix] {
let a = graph.createVertex("a")
let b = graph.createVertex("a")
XCTAssertEqual(a, b, "Should have returned the same vertex when creating a new one with identical data")
XCTAssertEqual(graph.vertices.count, 1, "Graph should only contain one vertex after trying to create two vertices with identical data")
}
}
func testEdgesFromReturnsCorrectEdgeInSingleEdgeDirecedGraphWithType(graphType: AbstractGraph<Int>.Type) {
let graph = graphType.init()
let a = graph.createVertex(1)
let b = graph.createVertex(2)
graph.addDirectedEdge(a, to: b, withWeight: 1.0)
let edgesFromA = graph.edgesFrom(a)
let edgesFromB = graph.edgesFrom(b)
XCTAssertEqual(edgesFromA.count, 1)
XCTAssertEqual(edgesFromB.count, 0)
XCTAssertEqual(edgesFromA.first?.to, b)
}
func testEdgesFromReturnsCorrectEdgeInSingleEdgeUndirectedGraphWithType(graphType: AbstractGraph<Int>.Type) {
let graph = graphType.init()
let a = graph.createVertex(1)
let b = graph.createVertex(2)
graph.addUndirectedEdge((a, b), withWeight: 1.0)
let edgesFromA = graph.edgesFrom(a)
let edgesFromB = graph.edgesFrom(b)
XCTAssertEqual(edgesFromA.count, 1)
XCTAssertEqual(edgesFromB.count, 1)
XCTAssertEqual(edgesFromA.first?.to, b)
XCTAssertEqual(edgesFromB.first?.to, a)
}
func testEdgesFromReturnsNoEdgesInNoEdgeGraphWithType(graphType: AbstractGraph<Int>.Type) {
let graph = graphType.init()
let a = graph.createVertex(1)
let b = graph.createVertex(2)
XCTAssertEqual(graph.edgesFrom(a).count, 0)
XCTAssertEqual(graph.edgesFrom(b).count, 0)
}
func testEdgesFromReturnsCorrectEdgesInBiggerGraphInDirectedGraphWithType(graphType: AbstractGraph<Int>.Type) {
let graph = graphType.init()
let verticesCount = 100
var vertices: [Vertex<Int>] = []
for i in 0..<verticesCount {
vertices.append(graph.createVertex(i))
}
for i in 0..<verticesCount {
for j in i+1..<verticesCount {
graph.addDirectedEdge(vertices[i], to: vertices[j], withWeight: 1)
}
}
for i in 0..<verticesCount {
let outEdges = graph.edgesFrom(vertices[i])
let toVertices = outEdges.map {return $0.to}
XCTAssertEqual(outEdges.count, verticesCount - i - 1)
for j in i+1..<verticesCount {
XCTAssertTrue(toVertices.contains(vertices[j]))
}
}
}
func testEdgesFromReturnsCorrectEdgeInSingleEdgeDirecedMatrixGraph() {
testEdgesFromReturnsCorrectEdgeInSingleEdgeDirecedGraphWithType(AdjacencyMatrixGraph<Int>)
}
func testEdgesFromReturnsCorrectEdgeInSingleEdgeUndirectedMatrixGraph() {
testEdgesFromReturnsCorrectEdgeInSingleEdgeUndirectedGraphWithType(AdjacencyMatrixGraph<Int>)
}
func testEdgesFromReturnsNoInNoEdgeMatrixGraph() {
testEdgesFromReturnsNoEdgesInNoEdgeGraphWithType(AdjacencyMatrixGraph<Int>)
}
func testEdgesFromReturnsCorrectEdgesInBiggerGraphInDirectedMatrixGraph() {
testEdgesFromReturnsCorrectEdgesInBiggerGraphInDirectedGraphWithType(AdjacencyMatrixGraph<Int>)
}
func testEdgesFromReturnsCorrectEdgeInSingleEdgeDirecedListGraph() {
testEdgesFromReturnsCorrectEdgeInSingleEdgeDirecedGraphWithType(AdjacencyListGraph<Int>)
}
func testEdgesFromReturnsCorrectEdgeInSingleEdgeUndirectedListGraph() {
testEdgesFromReturnsCorrectEdgeInSingleEdgeUndirectedGraphWithType(AdjacencyListGraph<Int>)
}
func testEdgesFromReturnsNoInNoEdgeListGraph() {
testEdgesFromReturnsNoEdgesInNoEdgeGraphWithType(AdjacencyListGraph<Int>)
}
func testEdgesFromReturnsCorrectEdgesInBiggerGraphInDirectedListGraph() {
testEdgesFromReturnsCorrectEdgesInBiggerGraphInDirectedGraphWithType(AdjacencyListGraph<Int>)
}
}
| mit | 43ba6ed6e7441d25e225fb3b01fbb298 | 30.841772 | 141 | 0.733055 | 3.729429 | false | true | false | false |
rlaferla/CLTokenInputView-Swift | CLTokenInputView/CLToken.swift | 1 | 502 | //
// CLToken.swift
// CLTokenInputView
//
// Created by Robert La Ferla on 1/13/16 from original ObjC version by Rizwan Sattar.
// Copyright © 2016 Robert La Ferla. All rights reserved.
//
import Foundation
class CLToken {
var displayText: String!
var context:AnyObject?
}
extension CLToken: Equatable {}
func ==(lhs: CLToken, rhs: CLToken) -> Bool {
if lhs.displayText == rhs.displayText && lhs.context?.isEqual(rhs.context) == true {
return true
}
return false
} | mit | 66092830d0a53d1dd4454798ce4e4c5f | 20.826087 | 88 | 0.676647 | 3.553191 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.