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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
wolf81/Nimbl3Survey | Nimbl3Survey/SurveyInfoViewController.swift | 1 | 1386 | //
// SurveyInfoViewController.swift
// Nimbl3Survey
//
// Created by Wolfgang Schreurs on 24/03/2017.
// Copyright © 2017 Wolftrail. All rights reserved.
//
import UIKit
class SurveyInfoViewController: UIViewController {
let survey: Survey
var surveyInfoView: SurveyInfoView {
return self.view as! SurveyInfoView
}
// MARK: - Initialization & clean-up
init(survey: Survey) {
self.survey = survey
super.init(nibName: nil, bundle: nil)
}
required init?(coder aDecoder: NSCoder) {
fatalError()
}
// MARK: - View lifecycle
override func loadView() {
self.view = SurveyInfoView.instantiateFromInterfaceBuilder()
}
override func viewDidLoad() {
super.viewDidLoad()
self.surveyInfoView.updateWithSurvey(self.survey)
self.surveyInfoView.delegate = self
}
}
// MARK: - SurveyInfoViewDelegate
extension SurveyInfoViewController: SurveyInfoViewDelegate {
func surveyInfoViewSurveyAction(_ surveyInfoView: SurveyInfoView) {
guard let survey = surveyInfoView.survey else { return }
let viewController = SurveyViewController(survey: survey)
let navController = UINavigationController(rootViewController: viewController)
present(navController, animated: true, completion: nil)
}
}
| bsd-2-clause | 77f364ddf7041f8ffdb7ba159c4dc807 | 24.648148 | 86 | 0.667148 | 4.792388 | false | false | false | false |
akaralar/siesta | Tests/PerformanceTests.swift | 1 | 8629 | //
// PerformanceTests.swift
// Siesta
//
// Created by Paul on 2016/9/27.
// Copyright © 2016 Bust Out Solutions. All rights reserved.
//
import Foundation
import XCTest
import Siesta
class SiestaPerformanceTests: XCTestCase
{
var service: Service!
var networkStub: NetworkStub!
override func setUp()
{
networkStub = NetworkStub()
service = Service(baseURL: "http://test.ing", networking: networkStub)
}
override func tearDown()
{
NotificationCenter.default
.post(
name: NSNotification.Name("Siesta.MemoryWarningNotification"),
object: nil)
}
func testGetExistingResourcesByURL()
{
measure { self.exerciseResourceCache(uniqueResources: 20, iters: 20000) }
}
func testGetExistingResourcesByPath()
{
let uniqueResources = 20
let iters = 20000
measure
{
self.setUp() // Important to start empty each time
let paths = (0 ..< uniqueResources).map { "/items/\($0)" }
for n in 0 ..< iters
{ _ = self.service.resource(paths[n % uniqueResources]) }
}
}
func testGetResourceForNilURL()
{
measure
{
for _ in 0 ..< 20000
{ _ = self.service.resource(absoluteURL: nil) }
}
}
func testResourceCacheGrowth()
{
measure { self.exerciseResourceCache(uniqueResources: 10000, iters: 10000) }
}
func testResourceCacheChurn()
{
measure { self.exerciseResourceCache(uniqueResources: 10000, iters: 10000, countLimit: 100) }
}
func exerciseResourceCache(uniqueResources: Int, iters: Int, countLimit: Int = 100000)
{
setUp() // Important to start empty each time
service.cachedResourceCountLimit = countLimit
let urls = (0 ..< uniqueResources).map { URL(string: "/items/\($0)") }
for n in 0 ..< iters
{ _ = service.resource(absoluteURL: urls[n % uniqueResources]) }
}
func testObserverChurn5()
{
measure { self.churnItUp(observerCount: 5, reps: 2000) }
}
func testObserverChurn100()
{
measure { self.churnItUp(observerCount: 100, reps: 1000) }
}
private func churnItUp(observerCount: Int, reps: Int)
{
// Note no setUp() per measure() here. We expect stable performance here even
// with an existing resource. Lack of that will show as high stdev in test results.
let resource = service.resource("/observed")
let observers = (1...observerCount).map { _ in TestObserver() }
for n in 0 ..< reps
{
var x = 0
resource.addObserver(observers[n % observerCount])
resource.addObserver(owner: observers[(n * 7) % observerCount])
{ _ in x += 1 }
resource.removeObservers(ownedBy: observers[(n * 3) % observerCount])
}
}
func testObserverOwnerChurn5()
{
measure { self.churnOwnersUp(observerCount: 5, reps: 2000) }
}
func testObserverOwnerChurn100()
{
measure { self.churnOwnersUp(observerCount: 100, reps: 1000) }
}
private func churnOwnersUp(observerCount: Int, reps: Int)
{
let resource = service.resource("/observed")
var observers = (1...observerCount).map { _ in TestObserver() }
for n in 0 ..< reps
{
var x = 0
resource.addObserver(observers[n % observerCount])
resource.addObserver(owner: observers[(n * 7) % observerCount])
{ _ in x += 1 }
observers[(n * 3) % observerCount] = TestObserver()
}
}
func testRequestHooks()
{
measure
{
var callbacks = 0
self.timeRequests(resourceCount: 1, reps: 200)
{
let req = $0.load()
for _ in 0 ..< 499 // 500th fulfills expectation
{ req.onCompletion { _ in callbacks += 1 } }
return req
}
}
}
func testBareRequest()
{
measure
{ self.timeRequests(resourceCount: 300, reps: 10) { $0.request(.get) } }
}
func testLoadRequest()
{
measure
{ self.timeRequests(resourceCount: 300, reps: 10) { $0.load() } }
}
private func timeRequests(resourceCount: Int, reps: Int, makeRequest: (Resource) -> Request)
{
for n in stride(from: 0, to: resourceCount, by: 2)
{ networkStub.responses["/zlerp\(n)"] = ResponseStub(data: Data(count: 65536)) }
let resources = (0 ..< resourceCount).map
{ service.resource("/zlerp\($0)") }
let load = self.expectation(description: "load")
var responsesPending = reps * resources.count
for _ in 0 ..< reps
{
for resource in resources
{
makeRequest(resource).onCompletion
{
_ in
responsesPending -= 1
if responsesPending <= 0
{ load.fulfill() }
}
}
}
self.waitForExpectations(timeout: 1)
}
func testNotifyManyObservers()
{
networkStub.responses["/zlerp"] = ResponseStub(data: Data(count: 65536))
let resource = service.resource("/zlerp")
for _ in 0 ..< 5000
{ resource.addObserver(TestObserver(), owner: self) }
measure
{
let load = self.expectation(description: "load")
let reps = 10
var responsesPending = reps
for _ in 0 ..< reps
{
resource.load().onCompletion
{
_ in
responsesPending -= 1
if responsesPending <= 0
{ load.fulfill() }
}
}
self.waitForExpectations(timeout: 1)
}
}
func testLoadIfNeeded()
{
networkStub.responses["/bjempf"] = ResponseStub(data: Data())
let resource = service.resource("/bjempf")
let load = self.expectation(description: "load")
resource.load().onCompletion { _ in load.fulfill() }
self.waitForExpectations(timeout: 1)
measure
{
for _ in 0 ..< 100000
{
resource.loadIfNeeded()
resource.loadIfNeeded()
resource.loadIfNeeded()
}
}
}
}
struct NetworkStub: NetworkingProvider
{
var responses: [String:ResponseStub] = [:]
let dummyHeaders =
[
"A-LITTLE": "madness in the Spring",
"Is-wholesome": "even for the King",
"But-God-be": "with the Clown",
"Who-ponders": "this tremendous scene",
"This-whole": "experiment of green",
"As-if-it": "were his own!",
"X-Author": "Emily Dickinson"
]
func startRequest(
_ request: URLRequest,
completion: @escaping RequestNetworkingCompletionCallback)
-> RequestNetworking
{
let responseStub = responses[request.url!.path]
let statusCode = (responseStub != nil) ? 200 : 404
var headers = dummyHeaders
headers["Content-Type"] = responseStub?.contentType
let response = HTTPURLResponse(
url: request.url!,
statusCode: statusCode,
httpVersion: "HTTP/1.1",
headerFields: headers)
completion(response, responseStub?.data, nil)
return RequestStub()
}
}
struct ResponseStub
{
let contentType: String = "application/octet-stream"
let data: Data
}
struct RequestStub: RequestNetworking
{
func cancel() { }
/// Returns raw data used for progress calculation.
var transferMetrics: RequestTransferMetrics
{
return RequestTransferMetrics(
requestBytesSent: 0,
requestBytesTotal: nil,
responseBytesReceived: 0,
responseBytesTotal: nil)
}
}
class TestObserver: ResourceObserver
{
public var eventCount = 0
func resourceChanged(_ resource: Resource, event: ResourceEvent)
{ eventCount += 1 }
}
| mit | 8fae7c215767dc14335ada08b94fb7e4 | 28.447099 | 101 | 0.532221 | 4.68913 | false | true | false | false |
jum/Charts | Source/Charts/Data/Implementations/Standard/ChartData.swift | 5 | 18114 | //
// ChartData.swift
// Charts
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/Charts
//
import Foundation
open class ChartData: NSObject
{
internal var _yMax: Double = -Double.greatestFiniteMagnitude
internal var _yMin: Double = Double.greatestFiniteMagnitude
internal var _xMax: Double = -Double.greatestFiniteMagnitude
internal var _xMin: Double = Double.greatestFiniteMagnitude
internal var _leftAxisMax: Double = -Double.greatestFiniteMagnitude
internal var _leftAxisMin: Double = Double.greatestFiniteMagnitude
internal var _rightAxisMax: Double = -Double.greatestFiniteMagnitude
internal var _rightAxisMin: Double = Double.greatestFiniteMagnitude
internal var _dataSets = [IChartDataSet]()
public override init()
{
super.init()
_dataSets = [IChartDataSet]()
}
@objc public init(dataSets: [IChartDataSet]?)
{
super.init()
_dataSets = dataSets ?? [IChartDataSet]()
self.initialize(dataSets: _dataSets)
}
@objc public convenience init(dataSet: IChartDataSet?)
{
self.init(dataSets: dataSet === nil ? nil : [dataSet!])
}
internal func initialize(dataSets: [IChartDataSet])
{
notifyDataChanged()
}
/// Call this method to let the ChartData know that the underlying data has changed.
/// Calling this performs all necessary recalculations needed when the contained data has changed.
@objc open func notifyDataChanged()
{
calcMinMax()
}
@objc open func calcMinMaxY(fromX: Double, toX: Double)
{
_dataSets.forEach { $0.calcMinMaxY(fromX: fromX, toX: toX) }
// apply the new data
calcMinMax()
}
/// calc minimum and maximum y value over all datasets
@objc open func calcMinMax()
{
_yMax = -Double.greatestFiniteMagnitude
_yMin = Double.greatestFiniteMagnitude
_xMax = -Double.greatestFiniteMagnitude
_xMin = Double.greatestFiniteMagnitude
_dataSets.forEach { calcMinMax(dataSet: $0) }
_leftAxisMax = -Double.greatestFiniteMagnitude
_leftAxisMin = Double.greatestFiniteMagnitude
_rightAxisMax = -Double.greatestFiniteMagnitude
_rightAxisMin = Double.greatestFiniteMagnitude
// left axis
let firstLeft = getFirstLeft(dataSets: dataSets)
if firstLeft !== nil
{
_leftAxisMax = firstLeft!.yMax
_leftAxisMin = firstLeft!.yMin
for dataSet in _dataSets
{
if dataSet.axisDependency == .left
{
if dataSet.yMin < _leftAxisMin
{
_leftAxisMin = dataSet.yMin
}
if dataSet.yMax > _leftAxisMax
{
_leftAxisMax = dataSet.yMax
}
}
}
}
// right axis
let firstRight = getFirstRight(dataSets: dataSets)
if firstRight !== nil
{
_rightAxisMax = firstRight!.yMax
_rightAxisMin = firstRight!.yMin
for dataSet in _dataSets
{
if dataSet.axisDependency == .right
{
if dataSet.yMin < _rightAxisMin
{
_rightAxisMin = dataSet.yMin
}
if dataSet.yMax > _rightAxisMax
{
_rightAxisMax = dataSet.yMax
}
}
}
}
}
/// Adjusts the current minimum and maximum values based on the provided Entry object.
@objc open func calcMinMax(entry e: ChartDataEntry, axis: YAxis.AxisDependency)
{
if _yMax < e.y
{
_yMax = e.y
}
if _yMin > e.y
{
_yMin = e.y
}
if _xMax < e.x
{
_xMax = e.x
}
if _xMin > e.x
{
_xMin = e.x
}
if axis == .left
{
if _leftAxisMax < e.y
{
_leftAxisMax = e.y
}
if _leftAxisMin > e.y
{
_leftAxisMin = e.y
}
}
else
{
if _rightAxisMax < e.y
{
_rightAxisMax = e.y
}
if _rightAxisMin > e.y
{
_rightAxisMin = e.y
}
}
}
/// Adjusts the minimum and maximum values based on the given DataSet.
@objc open func calcMinMax(dataSet d: IChartDataSet)
{
if _yMax < d.yMax
{
_yMax = d.yMax
}
if _yMin > d.yMin
{
_yMin = d.yMin
}
if _xMax < d.xMax
{
_xMax = d.xMax
}
if _xMin > d.xMin
{
_xMin = d.xMin
}
if d.axisDependency == .left
{
if _leftAxisMax < d.yMax
{
_leftAxisMax = d.yMax
}
if _leftAxisMin > d.yMin
{
_leftAxisMin = d.yMin
}
}
else
{
if _rightAxisMax < d.yMax
{
_rightAxisMax = d.yMax
}
if _rightAxisMin > d.yMin
{
_rightAxisMin = d.yMin
}
}
}
/// The number of LineDataSets this object contains
@objc open var dataSetCount: Int
{
return _dataSets.count
}
/// The smallest y-value the data object contains.
@objc open var yMin: Double
{
return _yMin
}
@nonobjc
open func getYMin() -> Double
{
return _yMin
}
@objc open func getYMin(axis: YAxis.AxisDependency) -> Double
{
if axis == .left
{
if _leftAxisMin == Double.greatestFiniteMagnitude
{
return _rightAxisMin
}
else
{
return _leftAxisMin
}
}
else
{
if _rightAxisMin == Double.greatestFiniteMagnitude
{
return _leftAxisMin
}
else
{
return _rightAxisMin
}
}
}
/// The greatest y-value the data object contains.
@objc open var yMax: Double
{
return _yMax
}
@nonobjc
open func getYMax() -> Double
{
return _yMax
}
@objc open func getYMax(axis: YAxis.AxisDependency) -> Double
{
if axis == .left
{
if _leftAxisMax == -Double.greatestFiniteMagnitude
{
return _rightAxisMax
}
else
{
return _leftAxisMax
}
}
else
{
if _rightAxisMax == -Double.greatestFiniteMagnitude
{
return _leftAxisMax
}
else
{
return _rightAxisMax
}
}
}
/// The minimum x-value the data object contains.
@objc open var xMin: Double
{
return _xMin
}
/// The maximum x-value the data object contains.
@objc open var xMax: Double
{
return _xMax
}
/// All DataSet objects this ChartData object holds.
@objc open var dataSets: [IChartDataSet]
{
get
{
return _dataSets
}
set
{
_dataSets = newValue
notifyDataChanged()
}
}
/// Retrieve the index of a ChartDataSet with a specific label from the ChartData. Search can be case sensitive or not.
///
/// **IMPORTANT: This method does calculations at runtime, do not over-use in performance critical situations.**
///
/// - Parameters:
/// - dataSets: the DataSet array to search
/// - type:
/// - ignorecase: if true, the search is not case-sensitive
/// - Returns: The index of the DataSet Object with the given label. Sensitive or not.
internal func getDataSetIndexByLabel(_ label: String, ignorecase: Bool) -> Int
{
// TODO: Return nil instead of -1
if ignorecase
{
return dataSets.firstIndex {
guard let label = $0.label else { return false }
return label.caseInsensitiveCompare(label) == .orderedSame
} ?? -1
}
else
{
return dataSets.firstIndex { $0.label == label }
?? -1
}
}
/// Get the Entry for a corresponding highlight object
///
/// - Parameters:
/// - highlight:
/// - Returns: The entry that is highlighted
@objc open func entryForHighlight(_ highlight: Highlight) -> ChartDataEntry?
{
if highlight.dataSetIndex >= dataSets.count
{
return nil
}
else
{
return dataSets[highlight.dataSetIndex].entryForXValue(highlight.x, closestToY: highlight.y)
}
}
/// **IMPORTANT: This method does calculations at runtime. Use with care in performance critical situations.**
///
/// - Parameters:
/// - label:
/// - ignorecase:
/// - Returns: The DataSet Object with the given label. Sensitive or not.
@objc open func getDataSetByLabel(_ label: String, ignorecase: Bool) -> IChartDataSet?
{
let index = getDataSetIndexByLabel(label, ignorecase: ignorecase)
if index < 0 || index >= _dataSets.count
{
return nil
}
else
{
return _dataSets[index]
}
}
@objc open func getDataSetByIndex(_ index: Int) -> IChartDataSet!
{
if index < 0 || index >= _dataSets.count
{
return nil
}
return _dataSets[index]
}
@objc open func addDataSet(_ dataSet: IChartDataSet!)
{
calcMinMax(dataSet: dataSet)
_dataSets.append(dataSet)
}
/// Removes the given DataSet from this data object.
/// Also recalculates all minimum and maximum values.
///
/// - Returns: `true` if a DataSet was removed, `false` ifno DataSet could be removed.
@objc @discardableResult open func removeDataSet(_ dataSet: IChartDataSet) -> Bool
{
guard let i = _dataSets.firstIndex(where: { $0 === dataSet }) else { return false }
return removeDataSetByIndex(i)
}
/// Removes the DataSet at the given index in the DataSet array from the data object.
/// Also recalculates all minimum and maximum values.
///
/// - Returns: `true` if a DataSet was removed, `false` ifno DataSet could be removed.
@objc @discardableResult open func removeDataSetByIndex(_ index: Int) -> Bool
{
if index >= _dataSets.count || index < 0
{
return false
}
_dataSets.remove(at: index)
calcMinMax()
return true
}
/// Adds an Entry to the DataSet at the specified index. Entries are added to the end of the list.
@objc open func addEntry(_ e: ChartDataEntry, dataSetIndex: Int)
{
if _dataSets.count > dataSetIndex && dataSetIndex >= 0
{
let set = _dataSets[dataSetIndex]
if !set.addEntry(e) { return }
calcMinMax(entry: e, axis: set.axisDependency)
}
else
{
print("ChartData.addEntry() - Cannot add Entry because dataSetIndex too high or too low.", terminator: "\n")
}
}
/// Removes the given Entry object from the DataSet at the specified index.
@objc @discardableResult open func removeEntry(_ entry: ChartDataEntry, dataSetIndex: Int) -> Bool
{
// entry outofbounds
if dataSetIndex >= _dataSets.count
{
return false
}
// remove the entry from the dataset
let removed = _dataSets[dataSetIndex].removeEntry(entry)
if removed
{
calcMinMax()
}
return removed
}
/// Removes the Entry object closest to the given xIndex from the ChartDataSet at the
/// specified index.
///
/// - Returns: `true` if an entry was removed, `false` ifno Entry was found that meets the specified requirements.
@objc @discardableResult open func removeEntry(xValue: Double, dataSetIndex: Int) -> Bool
{
if dataSetIndex >= _dataSets.count
{
return false
}
if let entry = _dataSets[dataSetIndex].entryForXValue(xValue, closestToY: Double.nan)
{
return removeEntry(entry, dataSetIndex: dataSetIndex)
}
return false
}
/// - Returns: The DataSet that contains the provided Entry, or null, if no DataSet contains this entry.
@objc open func getDataSetForEntry(_ e: ChartDataEntry) -> IChartDataSet?
{
return _dataSets.first { $0.entryForXValue(e.x, closestToY: e.y) === e }
}
/// - Returns: The index of the provided DataSet in the DataSet array of this data object, or -1 if it does not exist.
@objc open func indexOfDataSet(_ dataSet: IChartDataSet) -> Int
{
// TODO: Return nil instead of -1
return _dataSets.firstIndex { $0 === dataSet } ?? -1
}
/// - Returns: The first DataSet from the datasets-array that has it's dependency on the left axis. Returns null if no DataSet with left dependency could be found.
@objc open func getFirstLeft(dataSets: [IChartDataSet]) -> IChartDataSet?
{
return dataSets.first { $0.axisDependency == .left }
}
/// - Returns: The first DataSet from the datasets-array that has it's dependency on the right axis. Returns null if no DataSet with right dependency could be found.
@objc open func getFirstRight(dataSets: [IChartDataSet]) -> IChartDataSet?
{
return dataSets.first { $0.axisDependency == .right }
}
/// - Returns: All colors used across all DataSet objects this object represents.
@objc open func getColors() -> [NSUIColor]?
{
// TODO: Don't return nil
return _dataSets.flatMap { $0.colors }
}
/// Sets a custom IValueFormatter for all DataSets this data object contains.
@objc open func setValueFormatter(_ formatter: IValueFormatter)
{
dataSets.forEach { $0.valueFormatter = formatter }
}
/// Sets the color of the value-text (color in which the value-labels are drawn) for all DataSets this data object contains.
@objc open func setValueTextColor(_ color: NSUIColor)
{
dataSets.forEach { $0.valueTextColor = color }
}
/// Sets the font for all value-labels for all DataSets this data object contains.
@objc open func setValueFont(_ font: NSUIFont)
{
dataSets.forEach { $0.valueFont = font }
}
/// Enables / disables drawing values (value-text) for all DataSets this data object contains.
@objc open func setDrawValues(_ enabled: Bool)
{
dataSets.forEach { $0.drawValuesEnabled = enabled }
}
/// Enables / disables highlighting values for all DataSets this data object contains.
/// If set to true, this means that values can be highlighted programmatically or by touch gesture.
@objc open var highlightEnabled: Bool
{
get { return dataSets.allSatisfy { $0.highlightEnabled } }
set { dataSets.forEach { $0.highlightEnabled = newValue } }
}
/// if true, value highlightning is enabled
@objc open var isHighlightEnabled: Bool { return highlightEnabled }
/// Clears this data object from all DataSets and removes all Entries.
/// Don't forget to invalidate the chart after this.
@objc open func clearValues()
{
dataSets.removeAll(keepingCapacity: false)
notifyDataChanged()
}
/// Checks if this data object contains the specified DataSet.
///
/// - Returns: `true` if so, `false` ifnot.
@objc open func contains(dataSet: IChartDataSet) -> Bool
{
return dataSets.contains { $0 === dataSet }
}
/// The total entry count across all DataSet objects this data object contains.
@objc open var entryCount: Int
{
return _dataSets.reduce(0) { $0 + $1.entryCount }
}
/// The DataSet object with the maximum number of entries or null if there are no DataSets.
@objc open var maxEntryCountSet: IChartDataSet?
{
return dataSets.max { $0.entryCount < $1.entryCount }
}
// MARK: - Accessibility
/// When the data entry labels are generated identifiers, set this property to prepend a string before each identifier
///
/// For example, if a label is "#3", settings this property to "Item" allows it to be spoken as "Item #3"
@objc open var accessibilityEntryLabelPrefix: String?
/// When the data entry value requires a unit, use this property to append the string representation of the unit to the value
///
/// For example, if a value is "44.1", setting this property to "m" allows it to be spoken as "44.1 m"
@objc open var accessibilityEntryLabelSuffix: String?
/// If the data entry value is a count, set this to true to allow plurals and other grammatical changes
/// **default**: false
@objc open var accessibilityEntryLabelSuffixIsCount: Bool = false
}
| apache-2.0 | 72ee32370a51aea38acda61b57ee478e | 28.598039 | 169 | 0.549409 | 5.127087 | false | false | false | false |
zmarvin/EnjoyMusic | Pods/Macaw/Source/animation/types/ContentsAnimation.swift | 1 | 2678 |
internal class ContentsAnimation: AnimationImpl<[Node]> {
init(animatedGroup: Group, valueFunc: @escaping (Double) -> [Node], animationDuration: Double, delay: Double = 0.0, autostart: Bool = false, fps: UInt = 30) {
super.init(observableValue: animatedGroup.contentsVar, valueFunc: valueFunc, animationDuration: animationDuration, delay: delay, fps: fps)
type = .contents
node = animatedGroup
if autostart {
self.play()
}
}
init(animatedGroup: Group, factory: @escaping (() -> ((Double) -> [Node])), animationDuration: Double, delay: Double = 0.0, autostart: Bool = false, fps: UInt = 30) {
super.init(observableValue: animatedGroup.contentsVar, factory: factory, animationDuration: animationDuration, delay: delay, fps: fps)
type = .contents
node = animatedGroup
if autostart {
self.play()
}
}
open override func reverse() -> Animation {
let factory = { () -> (Double) -> [Node] in
let original = self.timeFactory()
return { (t: Double) -> [Node] in
return original(1.0 - t)
}
}
let reversedAnimation = ContentsAnimation(animatedGroup: node as! Group,
factory: factory, animationDuration: duration, fps: logicalFps)
reversedAnimation.progress = progress
reversedAnimation.completion = completion
return reversedAnimation
}
}
public extension AnimatableVariable where T: GroupInterpolation {
public func animation(_ f: @escaping (Double) -> [Node]) -> Animation {
let group = node! as! Group
return ContentsAnimation(animatedGroup: group, valueFunc: f, animationDuration: 1.0, delay: 0.0, autostart: false)
}
public func animation(_ f: @escaping (Double) -> [Node], during: Double = 1.0, delay: Double = 0.0) -> Animation {
let group = node! as! Group
return ContentsAnimation(animatedGroup: group, valueFunc: f, animationDuration: during, delay: delay, autostart: false)
}
public func animate(_ f: @escaping (Double) -> [Node]) {
let group = node! as! Group
let _ = ContentsAnimation(animatedGroup: group, valueFunc: f, animationDuration: 1.0, delay: 0.0, autostart: true)
}
public func animate(_ f: @escaping (Double) -> [Node], during: Double = 1.0, delay: Double = 0.0) {
let group = node! as! Group
let _ = ContentsAnimation(animatedGroup: group, valueFunc: f, animationDuration: during, delay: delay, autostart: true)
}
}
| mit | 3e93c9810ffddd376961cc1a454b97f5 | 40.84375 | 170 | 0.61165 | 4.419142 | false | false | false | false |
grafiti-io/SwiftCharts | SwiftCharts/Axis/ChartAxisXHighLayerDefault.swift | 1 | 2708 | //
// ChartAxisXHighLayerDefault.swift
// SwiftCharts
//
// Created by ischuetz on 25/04/15.
// Copyright (c) 2015 ivanschuetz. All rights reserved.
//
import UIKit
/// A ChartAxisLayer for high X axes
class ChartAxisXHighLayerDefault: ChartAxisXLayerDefault {
override var low: Bool {return false}
/// The start point of the axis line.
override var lineP1: CGPoint {
return CGPoint(x: origin.x, y: origin.y + lineOffset)
}
/// The end point of the axis line
override var lineP2: CGPoint {
return CGPoint(x: end.x, y: end.y + lineOffset)
}
/// The offset of the axis labels from the edge of the axis bounds
///
/// ````
/// ─ ─ ─ ─ ▲
/// Title │
/// │
/// ▼
/// Label
/// ````
fileprivate var labelsOffset: CGFloat {
return axisTitleLabelsHeight + settings.axisTitleLabelsToLabelsSpacing
}
/// The offset of the axis line from the edge of the axis bounds
///
/// ````
/// ─ ─ ─ ─ ▲
/// Title │
/// │
/// │
/// Label │
/// │
/// │
/// ─────── ▼
/// ````
fileprivate var lineOffset: CGFloat {
return labelsOffset + settings.labelsToAxisSpacingX + labelsTotalHeight
}
override func chartViewDrawing(context: CGContext, chart: Chart) {
super.chartViewDrawing(context: context, chart: chart)
}
override func updateInternal() {
guard let chart = chart else {return}
super.updateInternal()
if lastFrame.height != frame.height {
chart.notifyAxisInnerFrameChange(xHigh: ChartAxisLayerWithFrameDelta(layer: self, delta: frame.height - lastFrame.height))
}
}
override func handleAxisInnerFrameChange(_ xLow: ChartAxisLayerWithFrameDelta?, yLow: ChartAxisLayerWithFrameDelta?, xHigh: ChartAxisLayerWithFrameDelta?, yHigh: ChartAxisLayerWithFrameDelta?) {
super.handleAxisInnerFrameChange(xLow, yLow: yLow, xHigh: xHigh, yHigh: yHigh)
// handle resizing of other high x axes
if let xHigh = xHigh, xHigh.layer.frame.minY < frame.minY {
offset = offset + xHigh.delta
initDrawers()
}
}
override func axisLineY(offset: CGFloat) -> CGFloat {
return lineP1.y + settings.axisStrokeWidth / 2
}
override func initDrawers() {
axisTitleLabelDrawers = generateAxisTitleLabelsDrawers(offset: 0)
labelDrawers = generateLabelDrawers(offset: labelsOffset)
lineDrawer = generateLineDrawer(offset: lineOffset)
}
}
| apache-2.0 | deb77909a890f257ed31a7e3d4b68273 | 28.820225 | 198 | 0.603994 | 4.372323 | false | false | false | false |
abdullah-chhatra/iLayout | Example/Example/ExampleViews/FillSuperviewView.swift | 1 | 1650 | //
// FillSuperviewView.swift
// Example
//
// Created by Abdulmunaf Chhatra on 6/7/15.
// Copyright (c) 2015 Abdulmunaf Chhatra. All rights reserved.
//
import Foundation
import iLayout
class FillSuperviewView : AutoLayoutView {
var fillTopView = UILabel.createWithText(text: "Fill top")
var fillBottomView = UILabel.createWithText(text: "Fill bottom")
var fillLeftView = UILabel.createWithText(text: "Fill left")
var fillRightView = UILabel.createWithText(text: "Fill right")
var fillCenter = UILabel.createWithText(text: "Fill center")
override func initializeView() {
super.initializeView()
backgroundColor = UIColor.white
addSubview(fillTopView)
addSubview(fillBottomView)
addSubview(fillLeftView)
addSubview(fillRightView)
addSubview(fillCenter)
fillTopView.backgroundColor = UIColor.yellow
fillBottomView.backgroundColor = UIColor.yellow
fillRightView.backgroundColor = UIColor.green
fillLeftView.backgroundColor = UIColor.green
fillCenter.backgroundColor = UIColor.lightGray
for view in subviews {
view.alpha = 0.5
}
}
override func addConstraints(_ layout: Layout) {
layout.fillTopOfSuperview(fillTopView, respectMargin: false)
layout.fillBottomOfSuperview(fillBottomView, respectMargin: false)
layout.fillLeadingSideOfSuperview(fillLeftView)
layout.fillTrailingSideOfSuperview(fillRightView)
layout.fillSuperview(fillCenter, respectMargin: false)
}
}
| mit | e808060ade9351cc5ff99b0f94cb1958 | 30.132075 | 74 | 0.676364 | 4.727794 | false | false | false | false |
zixun/GodEye | Core/AppBaseKit/Classes/Extension/Foundation/NSFileManager+AppBaseKit.swift | 2 | 1088 | //
// NSFileManager+AppBaseKit.swift
// Pods
//
// Created by zixun on 16/9/25.
//
//
import Foundation
extension FileManager {
public class func createDirectoryIfNotExists(path:String) -> Bool {
let fileManager = self.default
var isDir: ObjCBool = false
let exists = fileManager.fileExists(atPath: path, isDirectory: &isDir)
if exists == false || isDir.boolValue == false {
do {
try fileManager.createDirectory(atPath: path, withIntermediateDirectories: true, attributes: nil)
}catch {
return false
}
}
return true
}
public class func removeItemIfExists(path:String) ->Bool {
let fileManager = self.default
var isDir: ObjCBool = false
let exists = fileManager.fileExists(atPath: path, isDirectory: &isDir)
if exists == true {
do {
try fileManager.removeItem(atPath: path)
}catch {
return false
}
}
return true
}
}
| mit | 05865ed8fbf5d74d448c08ff8a454d98 | 25.536585 | 113 | 0.5625 | 4.923077 | false | false | false | false |
ontouchstart/mythical-mind-bike | mythical-mind-bike.playgroundbook/Contents/Chapters/00.playgroundchapter/Pages/02.playgroundpage/Contents.swift | 1 | 1249 | import Foundation
/*: # Emoji
One of the topics in the [tweet](https://twitter.com/worrydream/status/811082333587578880) by [@worrydream](https://twitter.com/worrydream) is the new emoji features in iOS. What you see above is the emoji 4.0 test data from following URL:
*/
URL(string: "http://unicode.org/Public/emoji/4.0/emoji-test.txt")
/*:
Here is a simple function to show a list of emoji characters and their code.
*/
func emoji(from: String, n: Int ) -> [String] {
var output: [String] = []
var v = from.unicodeScalars.first!.value
for i in 1 ... n {
var c = ""
if let x = UnicodeScalar(v) {
c.unicodeScalars.append(x)
output.append("\(c) #\(String(v, radix: 16)) [\(i)]")
}
v += 1
}
return output
}
func emojiWithSkin(base: UInt32, skin: [UInt32]) -> [String] {
var output: [String] = []
for s in skin {
var c = ""
c.unicodeScalars.append(UnicodeScalar(base)!)
c.unicodeScalars.append(UnicodeScalar(s)!)
output.append(c)
}
return output
}
// Tests
emoji(from: "😀", n: 80)
emoji(from: "🍏", n: 80)
emoji(from: "🐀", n: 80)
emojiWithSkin(base: 0x1f467, skin: [0x1f3fb, 0x1f3fc, 0x1f3fd, 0x1f3fe, 0x1f3ff])
| gpl-3.0 | 8564116f62970212aa9eb6cc7211c28a | 29.243902 | 239 | 0.615323 | 3.092269 | false | true | false | false |
worchyld/FanDuelSample | FanDuelSample/Pods/Cent/Sources/Array.swift | 2 | 9173 | //
// Array.swift
// Cent
//
// Created by Ankur Patel on 6/28/14.
// Copyright (c) 2014 Encore Dev Labs LLC. All rights reserved.
//
import Foundation
import Dollar
public extension Array {
/// Creates an array of elements from the specified indexes, or keys, of the collection.
/// Indexes may be specified as individual arguments or as arrays of indexes.
///
/// - parameter indexes: Get elements from these indexes
/// - returns: New array with elements from the indexes specified.
func at(indexes: Int...) -> [Element] {
return $.at(self, indexes: indexes)
}
/// Cycles through the array n times passing each element into the callback function
///
/// - parameter times: Number of times to cycle through the array
/// - parameter callback: function to call with the element
func cycle<U>(times: Int, callback: (Element) -> U) {
$.cycle(self, times, callback: callback)
}
/// Cycles through the array indefinetly passing each element into the callback function
///
/// - parameter callback: function to call with the element
func cycle<U>(callback: (Element) -> U) {
$.cycle(self, callback: callback)
}
/// For each item in the array invoke the callback by passing the elem
///
/// - parameter callback: The callback function to invoke that take an element
/// - returns: array itself
@discardableResult func eachWithIndex(callback: (Int, Element) -> ()) -> [Element] {
for (index, elem) in self.enumerated() {
callback(index, elem)
}
return self
}
/// For each item in the array invoke the callback by passing the elem along with the index
///
/// - parameter callback: The callback function to invoke
/// - returns: The array itself
@discardableResult func each(callback: (Element) -> ()) -> [Element] {
self.eachWithIndex { (index, elem) -> () in
callback(elem)
}
return self
}
/// For each item in the array that meets the when conditon, invoke the callback by passing the elem
///
/// - parameter when: The condition to check each element against
/// - parameter callback: The callback function to invoke
/// - returns: The array itself
@discardableResult func each(when: (Element) -> Bool, callback: (Element) -> ()) -> [Element] {
return $.each(self, when: when, callback: callback)
}
/// Checks if the given callback returns true value for all items in the array.
///
/// - parameter callback: Check whether element value is true or false.
/// - returns: First element from the array.
func every(callback: (Element) -> Bool) -> Bool {
return $.every(self, callback: callback)
}
/// Get element from an array at the given index which can be negative
/// to find elements from the end of the array
///
/// - parameter index: Can be positive or negative to find from end of the array
/// - parameter orElse: Default value to use if index is out of bounds
/// - returns: Element fetched from the array or the default value passed in orElse
func fetch(index: Int, orElse: Element? = .none) -> Element! {
return $.fetch(self, index, orElse: orElse)
}
/// This method is like find except that it returns the index of the first element
/// that passes the callback check.
///
/// - parameter callback: Function used to figure out whether element is the same.
/// - returns: First element's index from the array found using the callback.
func findIndex(callback: (Element) -> Bool) -> Int? {
return $.findIndex(self, callback: callback)
}
/// This method is like findIndex except that it iterates over elements of the array
/// from right to left.
///
/// - parameter callback: Function used to figure out whether element is the same.
/// - returns: Last element's index from the array found using the callback.
func findLastIndex(callback: (Element) -> Bool) -> Int? {
return $.findLastIndex(self, callback: callback)
}
/// Gets the first element in the array.
///
/// - returns: First element from the array.
func first() -> Element? {
return $.first(self)
}
/// Flattens the array
///
/// - returns: Flatten array of elements
func flatten() -> [Element] {
return $.flatten(self)
}
/// Get element at index
///
/// - parameter index: The index in the array
/// - returns: Element at that index
func get(index: Int) -> Element! {
return self.fetch(index: index)
}
/// Gets all but the last element or last n elements of an array.
///
/// - parameter numElements: The number of elements to ignore in the end.
/// - returns: Array of initial values.
func initial(numElements: Int? = 1) -> [Element] {
return $.initial(self, numElements: numElements!)
}
/// Gets the last element from the array.
///
/// - returns: Last element from the array.
func last() -> Element? {
return $.last(self)
}
/// The opposite of initial this method gets all but the first element or first n elements of an array.
///
/// - parameter numElements: The number of elements to exclude from the beginning.
/// - returns: The rest of the elements.
func rest(numElements: Int? = 1) -> [Element] {
return $.rest(self, numElements: numElements!)
}
/// Retrieves the minimum value in an array.
///
/// - returns: Minimum value from array.
func min<T: Comparable>() -> T? {
return $.min(map { $0 as! T })
}
/// Retrieves the maximum value in an array.
///
/// - returns: Maximum element in array.
func max<T: Comparable>() -> T? {
return $.max(map { $0 as! T })
}
/// Gets the index at which the first occurrence of value is found.
///
/// - parameter value: Value whose index needs to be found.
/// - returns: Index of the element otherwise returns nil if not found.
func indexOf<T: Equatable>(value: T) -> Int? {
return $.indexOf(map { $0 as! T }, value: value)
}
/// Remove element from array
///
/// - parameter value: Value that is to be removed from array
/// - returns: Element at that index
mutating func remove<T: Equatable>(value: T) -> T? {
if let index = $.indexOf(map { $0 as! T }, value: value) {
return (remove(at: index) as? T)
} else {
return .none
}
}
/// Checks if a given value is present in the array.
///
/// - parameter value: The value to check.
/// - returns: Whether value is in the array.
func contains<T: Equatable>(value: T) -> Bool {
return $.contains(map { $0 as! T }, value: value)
}
/// Return the result of repeatedly calling `combine` with an accumulated value initialized
/// to `initial` on each element of `self`, in turn with a corresponding index.
///
/// - parameter initial: the value to be accumulated
/// - parameter combine: the combiner with the result, index, and current element
/// - throws: Rethrows the error generated from combine
/// - returns: combined result
func reduceWithIndex<T>(initial: T, combine: (T, Int, Array.Generator.Element) throws -> T) rethrows -> T {
var result = initial
for (index, element) in self.enumerated() {
result = try combine(result, index, element)
}
return result
}
/// Checks if the array has one or more elements.
///
/// - returns: true if the array is not empty, or false if it is empty.
public var isNotEmpty: Bool {
get {
return !self.isEmpty
}
}
}
extension Array where Element: Hashable {
/// Creates an object composed from arrays of keys and values.
///
/// - parameter values: The array of values.
/// - returns: Dictionary based on the keys and values passed in order.
public func zipObject<T>(values: [T]) -> [Element:T] {
return $.zipObject(self, values: values)
}
}
/// Overloaded operator to appends another array to an array
///
/// - parameter left: array to insert elements into
/// - parameter right: array to source elements from
/// - returns: array with the element appended in the end
public func<<<T>(left: inout [T], right: [T]) -> [T] {
left += right
return left
}
/// Overloaded operator to append element to an array
///
/// - parameter array: array to insert element into
/// - parameter elem: element to insert
/// - returns: array with the element appended in the end
public func<<<T>( array: inout [T], elem: T) -> [T] {
array.append(elem)
return array
}
/// Overloaded operator to remove elements from first array
///
/// - parameter left: array from which elements will be removed
/// - parameter right: array containing elements to remove
/// - returns: array with the elements from second array removed
public func -<T: Hashable>(left: [T], right: [T]) -> [T] {
return $.difference(left, right)
}
| gpl-3.0 | 798c8b98a62c885cc40963d6bd83cf98 | 34.832031 | 111 | 0.626404 | 4.318738 | false | false | false | false |
andreipitis/ASPVideoPlayer | Sources/ControlButtons.swift | 1 | 4577 | //
// ControlButtons.swift
// ASPVideoPlayer
//
// Created by Andrei-Sergiu Pițiș on 12/12/2016.
// Copyright © 2016 Andrei-Sergiu Pițiș. All rights reserved.
//
import UIKit
/*
Play and pause button.
*/
open class PlayPauseButton: UIButton {
public enum ButtonState {
case play
case pause
}
open override var isSelected: Bool {
didSet {
if isSelected == true {
playPauseLayer.animationDirection = 0.0
} else {
playPauseLayer.animationDirection = 1.0
}
}
}
open override var tintColor: UIColor! {
didSet {
playPauseLayer.color = tintColor
}
}
open var buttonState: ButtonState {
set {
switch newValue {
case .play:
isSelected = false
default:
isSelected = true
}
}
get {
return isSelected == true ? .pause : .play
}
}
private let playPauseLayer = PlayPauseLayer()
override init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
open override func layoutSubviews() {
super.layoutSubviews()
playPauseLayer.frame = bounds.insetBy(dx: (bounds.width / 4.0), dy: (bounds.height / 4.0))
playPauseLayer.color = tintColor
}
@objc fileprivate func changeState() {
isSelected = !isSelected
}
private func commonInit() {
playPauseLayer.frame = bounds.insetBy(dx: (bounds.width / 4.0), dy: (bounds.height / 4.0))
playPauseLayer.color = tintColor
layer.addSublayer(playPauseLayer)
addTarget(self, action: #selector(changeState), for: .touchUpInside)
}
}
/*
Next button.
*/
open class NextButton: UIButton {
override open func draw(_ rect: CGRect) {
if let context = UIGraphicsGetCurrentContext() {
context.setFillColor(tintColor.cgColor)
let frame = bounds.insetBy(dx: bounds.width / 4.0 + 4.0, dy: bounds.height / 4.0 + 4.0)
context.move(to: frame.origin)
context.addLine(to: CGPoint(x: frame.origin.x + frame.size.width * 0.75, y: frame.origin.y + frame.size.height / 2.0))
context.addLine(to: CGPoint(x: frame.origin.x, y: (frame.origin.y + frame.size.height)))
context.closePath()
context.setShadow(offset: CGSize(width: 0.5, height: 0.5), blur: 3.0)
context.fillPath()
context.move(to: CGPoint(x: frame.origin.x + frame.size.width * 0.85, y: frame.origin.y))
context.addLine(to: CGPoint(x: frame.origin.x + frame.size.width, y: frame.origin.y))
context.addLine(to: CGPoint(x: frame.origin.x + frame.size.width, y: frame.origin.y + frame.size.height))
context.addLine(to: CGPoint(x: frame.origin.x + frame.size.width * 0.85, y: frame.origin.y + frame.size.height))
context.closePath()
context.setShadow(offset: CGSize(width: 0.5, height: 0.5), blur: 3.0)
context.fillPath()
}
}
}
/*
Previous button.
*/
open class PreviousButton: UIButton {
override open func draw(_ rect: CGRect) {
if let context = UIGraphicsGetCurrentContext() {
context.setFillColor(tintColor.cgColor)
let frame = bounds.insetBy(dx: bounds.width / 4.0 + 4.0, dy: bounds.height / 4.0 + 4.0)
context.move(to: frame.origin)
context.addLine(to: CGPoint(x: frame.origin.x + frame.size.width * 0.15, y: frame.origin.y))
context.addLine(to: CGPoint(x: frame.origin.x + frame.size.width * 0.15, y: frame.origin.y + frame.size.height))
context.addLine(to: CGPoint(x: frame.origin.x, y: frame.origin.y + frame.size.height))
context.closePath()
context.setShadow(offset: CGSize(width: -0.5, height: 0.5), blur: 3.0)
context.fillPath()
context.move(to: CGPoint(x: frame.origin.x + frame.size.width * 0.25, y: frame.origin.y + frame.size.height / 2.0))
context.addLine(to: CGPoint(x: frame.origin.x + frame.size.width, y: frame.origin.y))
context.addLine(to: CGPoint(x: frame.origin.x + frame.size.width, y: (frame.origin.y + frame.size.height)))
context.closePath()
context.setShadow(offset: CGSize(width: -0.5, height: 0.5), blur: 3.0)
context.fillPath()
}
}
}
| mit | a00f6a417f0ab4fb68c4038de0c30124 | 32.372263 | 130 | 0.591645 | 3.772277 | false | false | false | false |
adapter00/FlickableCalendar | Example/FlickableCalendar/ViewController.swift | 1 | 3068 | //
// ViewController.swift
// FlickableCalendar
//
// Created by maeda_t on 02/26/2017.
// Copyright (c) 2017 maeda_t. All rights reserved.
//
import UIKit
import FlickableCalendar
class ViewController: UIViewController,CalendarViewDelegate{
public func didMoveCalendar(date: Date) {
let formatter = DateFormatter()
formatter.locale = Locale.current
formatter.dateFormat = "yyyy/MM"
let str = formatter.string(from: date)
self.monthLabel.text = str
}
@IBOutlet var monthLabel: UILabel!
@IBOutlet var calendarView: ADCalendarView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.calendarView.parent = self
self.calendarView.register(UINib(nibName: "CustomCalendarCell", bundle: nil), forCellWithReuseIdentifier: "CustomCell")
self.calendarView.move(to: Date(),animated:false)
}
func cellForDate(indexPath: IndexPath, date: Date,position:ADCalendarMonthPosition) -> CalendarCell? {
let cell:CustomCell = self.calendarView.dequeueReusableCell(withReuseIdentifier: "CustomCell", for: indexPath) as! CustomCell
cell.date = date
switch position {
case .next:
fallthrough
case .previsious:
cell.dayLabel.textColor = UIColor.lightGray
case .current:
cell.dayLabel.textColor = UIColor.black
}
return cell
}
func didSelectedCalendarCell(indexPath: IndexPath, date: Date,position:ADCalendarMonthPosition) {
}
func calendarConfiguration() -> ADCalendarConfigurator {
// let start = Date.init(timeIntervalSinceNow: TimeInterval((60 * 60 * 24 * 30 * 12) * -1))
let start = Date.init(timeIntervalSince1970: TimeInterval(0))
let end = Date.init(timeIntervalSinceNow: TimeInterval(60 * 60 * 24 * 30 * 12))
return ADCalendarConfigurator(start:start,end:end)
}
@IBAction func didClickOneYear(_ sender: Any) {
self.calendarView.move(to: Date())
}
@IBAction func didClickBackButton(_ sender: Any) {
self.dismiss(animated: true, completion: nil)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
class CustomCell:CalendarCell {
@IBOutlet var dayLabel: UILabel!
override var isSelected: Bool {
didSet {
if isSelected {
self.backgroundColor = UIColor.blue
}else {
self.backgroundColor = UIColor.white
}
}
}
override var date:Date? {
didSet {
let formatter = DateFormatter()
formatter.dateFormat = "d"
self.dayLabel.text = formatter.string(from: date!)
}
}
override init(frame: CGRect) {
super.init(frame: frame)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
}
| mit | 9153104ce4ac6972746fbd13e3846665 | 31.294737 | 133 | 0.637549 | 4.613534 | false | false | false | false |
melvitax/AFViewHelper | Sources/InspectableView.swift | 1 | 3827 | //
// InspectableView.swift
// ViewHelper: Version 4.2.4
// Created by Melvin Rivera on 7/24/14.
// https://github.com/melvitax/ViewHelper
//
import Foundation
import UIKit
import QuartzCore
@IBDesignable open class InspectableView :UIView {
// MARK: Border
/**
The layer border color
*/
@IBInspectable override public var borderColor: UIColor {
get {
return layer.borderColor == nil ? UIColor.clear : UIColor(cgColor: layer.borderColor!)
}
set {
layer.borderColor = newValue.cgColor
}
}
/**
The layer border width
*/
@IBInspectable override public var borderWidth: CGFloat {
get {
return layer.borderWidth
}
set {
layer.borderWidth = newValue
}
}
// MARK: Corner Radius
/**
The layer corner radius
*/
@IBInspectable override public var cornerRadius: CGFloat {
get {
return layer.cornerRadius
}
set {
layer.cornerRadius = newValue
layer.masksToBounds = newValue > 0
setupView()
}
}
// MARK: Shadow
/**
The shadow color of the layer
*/
@IBInspectable override public var shadowColor: UIColor {
get {
return layer.shadowColor == nil ? UIColor.clear : UIColor(cgColor: layer.shadowColor!)
}
set {
layer.shadowColor = newValue.cgColor
}
}
/**
The shadow offset of the layer
*/
@IBInspectable override public var shadowOffset:CGSize {
get {
return layer.shadowOffset
}
set {
layer.shadowOffset = newValue
}
}
/**
The shadow opacity of the layer
- Returns: Float
*/
@IBInspectable override public var shadowOpacity:Float {
get {
return layer.shadowOpacity
}
set {
layer.shadowOpacity = newValue
}
}
/**
The shadow radius of the layer
- Returns: CGFloat
*/
@IBInspectable override public var shadowRadius:CGFloat {
get {
return layer.shadowRadius
}
set {
layer.shadowRadius = newValue
}
}
// MARK: Inspectable properties
@IBInspectable var startColor: UIColor = UIColor.white {
didSet{
setupView()
}
}
@IBInspectable var endColor: UIColor = UIColor.black {
didSet{
setupView()
}
}
@IBInspectable var isHorizontal: Bool = false {
didSet{
setupView()
}
}
// MARK: Internal functions
fileprivate func setupView(){
let colors = [startColor.cgColor, endColor.cgColor]
gradientLayer.colors = colors
gradientLayer.cornerRadius = cornerRadius
if (isHorizontal){
gradientLayer.endPoint = CGPoint(x: 1, y: 0)
} else {
gradientLayer.endPoint = CGPoint(x: 0, y: 1)
}
self.setNeedsDisplay()
}
// Helper to return the main layer as CAGradientLayer
var gradientLayer: CAGradientLayer {
return layer as! CAGradientLayer
}
// MARK: Overrides ******************************************
override open class var layerClass:AnyClass{
return CAGradientLayer.self
}
override init(frame: CGRect) {
super.init(frame: frame)
setupView()
}
required public init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)!
setupView()
}
open override func prepareForInterfaceBuilder() {
setupView()
}
}
| mit | 8d2d15a5d59afa693c7a14e23ec62647 | 20.744318 | 98 | 0.535668 | 5.397743 | false | false | false | false |
hejunbinlan/Nuke | Example/Nuke/ViewController.swift | 2 | 12166 | //
// ViewController.swift
// Nuke
//
// Created by kean on 09/13/2015.
// Copyright (c) 2015 kean. All rights reserved.
//
import UIKit
import Nuke
class ViewController: UICollectionViewController {
var photos: [NSURL]!
let cellReuseID = "reuseID"
override func viewDidLoad() {
super.viewDidLoad()
self.photos = self.createPhotos()
self.collectionView?.backgroundColor = UIColor.whiteColor()
self.collectionView?.registerClass(UICollectionViewCell.self, forCellWithReuseIdentifier: cellReuseID)
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
self.updateItemSize()
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
self.updateItemSize()
}
func updateItemSize() {
let layout = self.collectionViewLayout as! UICollectionViewFlowLayout
layout.minimumLineSpacing = 2.0
layout.minimumInteritemSpacing = 2.0
let itemsPerRow = 4
let side = (Double(self.view.bounds.size.width) - Double(itemsPerRow - 1) * 2.0) / Double(itemsPerRow)
layout.itemSize = CGSize(width: side, height: side)
}
// MARK: UICollectionView
override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return self.photos.count
}
override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(cellReuseID, forIndexPath: indexPath)
cell.backgroundColor = UIColor(white: 235.0 / 255.0, alpha: 1.0)
let imageView = self.imageViewForCell(cell)
imageView.prepareForReuse()
let imageURL = self.photos[indexPath.row]
imageView.setImageWithURL(imageURL)
return cell
}
override func collectionView(collectionView: UICollectionView, didEndDisplayingCell cell: UICollectionViewCell, forItemAtIndexPath indexPath: NSIndexPath) {
self.imageViewForCell(cell).prepareForReuse()
}
func imageViewForCell(cell: UICollectionViewCell) -> Nuke.ImageView {
var imageView = cell.viewWithTag(15) as? Nuke.ImageView
if imageView == nil {
imageView = Nuke.ImageView(frame: cell.bounds)
imageView!.autoresizingMask = [.FlexibleWidth, .FlexibleHeight]
imageView!.tag = 15
cell.addSubview(imageView!)
}
return imageView!
}
// MARK: Misc
private func createPhotos() -> [NSURL] {
return [
NSURL(string: "https://cloud.githubusercontent.com/assets/1567433/9781817/ecb16e82-57a0-11e5-9b43-6b4f52659997.jpg")!,
NSURL(string: "https://cloud.githubusercontent.com/assets/1567433/9781832/0719dd5e-57a1-11e5-9324-9764de25ed47.jpg")!,
NSURL(string: "https://cloud.githubusercontent.com/assets/1567433/9781833/09021316-57a1-11e5-817b-85b57a2a8a77.jpg")!,
NSURL(string: "https://cloud.githubusercontent.com/assets/1567433/9781834/0931ad74-57a1-11e5-9080-c8f6ecea19ce.jpg")!,
NSURL(string: "https://cloud.githubusercontent.com/assets/1567433/9781838/0e6274f4-57a1-11e5-82fd-872e735eea73.jpg")!,
NSURL(string: "https://cloud.githubusercontent.com/assets/1567433/9781839/0e63ad92-57a1-11e5-8841-bd3c5ea1bb9c.jpg")!,
NSURL(string: "https://cloud.githubusercontent.com/assets/1567433/9781843/0f4064b2-57a1-11e5-9fb7-f258e81a4214.jpg")!,
NSURL(string: "https://cloud.githubusercontent.com/assets/1567433/9781840/0e95f978-57a1-11e5-8179-36dfed72f985.jpg")!,
NSURL(string: "https://cloud.githubusercontent.com/assets/1567433/9781841/0e96b5fc-57a1-11e5-82ae-699b113bb85a.jpg")!,
NSURL(string: "https://cloud.githubusercontent.com/assets/1567433/9781894/839cf99c-57a1-11e5-9602-d56d99a31abc.jpg")!,
NSURL(string: "https://cloud.githubusercontent.com/assets/1567433/9781896/83c5e1f4-57a1-11e5-9961-97730da2a7ad.jpg")!,
NSURL(string: "https://cloud.githubusercontent.com/assets/1567433/9781897/83c622cc-57a1-11e5-98dd-3a7d54b60170.jpg")!,
NSURL(string: "https://cloud.githubusercontent.com/assets/1567433/9781900/83cbc934-57a1-11e5-8152-e9ecab92db75.jpg")!,
NSURL(string: "https://cloud.githubusercontent.com/assets/1567433/9781899/83cb13a4-57a1-11e5-88c4-48feb134a9f0.jpg")!,
NSURL(string: "https://cloud.githubusercontent.com/assets/1567433/9781898/83c85ba0-57a1-11e5-8569-778689bff1ed.jpg")!,
NSURL(string: "https://cloud.githubusercontent.com/assets/1567433/9781895/83b7f3fa-57a1-11e5-8579-e2fd6098052d.jpg")!,
NSURL(string: "https://cloud.githubusercontent.com/assets/1567433/9781901/83d5d500-57a1-11e5-9894-78467657874c.jpg")!,
NSURL(string: "https://cloud.githubusercontent.com/assets/1567433/9781902/83df3b72-57a1-11e5-82b0-e6eb08915402.jpg")!,
NSURL(string: "https://cloud.githubusercontent.com/assets/1567433/9781903/83e400bc-57a1-11e5-881d-c0ed2c5136f6.jpg")!,
NSURL(string: "https://cloud.githubusercontent.com/assets/1567433/9781964/f4553bea-57a1-11e5-9abf-f23470a5efc1.jpg")!,
NSURL(string: "https://cloud.githubusercontent.com/assets/1567433/9781955/f3b2ed18-57a1-11e5-8fc7-0579e44de0b0.jpg")!,
NSURL(string: "https://cloud.githubusercontent.com/assets/1567433/9781959/f3b7e624-57a1-11e5-8982-8017f53a4898.jpg")!,
NSURL(string: "https://cloud.githubusercontent.com/assets/1567433/9781957/f3b52e98-57a1-11e5-9f1a-8741acddb12d.jpg")!,
NSURL(string: "https://cloud.githubusercontent.com/assets/1567433/9781958/f3b5544a-57a1-11e5-880a-478507b2e189.jpg")!,
NSURL(string: "https://cloud.githubusercontent.com/assets/1567433/9781956/f3b35082-57a1-11e5-9d2f-2c364e3f9b68.jpg")!,
NSURL(string: "https://cloud.githubusercontent.com/assets/1567433/9781963/f3da11b8-57a1-11e5-838e-c75e6b00f33e.jpg")!,
NSURL(string: "https://cloud.githubusercontent.com/assets/1567433/9781961/f3d865de-57a1-11e5-87fd-bb8f28515a16.jpg")!,
NSURL(string: "https://cloud.githubusercontent.com/assets/1567433/9781960/f3d7f306-57a1-11e5-833f-f3802344619e.jpg")!,
NSURL(string: "https://cloud.githubusercontent.com/assets/1567433/9781962/f3d98c20-57a1-11e5-838e-10f9d20fbc9b.jpg")!,
NSURL(string: "https://cloud.githubusercontent.com/assets/1567433/9781982/2b67875a-57a2-11e5-91b2-ec4ca2a65674.jpg")!,
NSURL(string: "https://cloud.githubusercontent.com/assets/1567433/9781985/2b92e576-57a2-11e5-955f-73889423b552.jpg")!,
NSURL(string: "https://cloud.githubusercontent.com/assets/1567433/9781986/2b94c288-57a2-11e5-8ebd-4cc107444e70.jpg")!,
NSURL(string: "https://cloud.githubusercontent.com/assets/1567433/9781987/2b94ba72-57a2-11e5-8259-8d4b5fce1f6c.jpg")!,
NSURL(string: "https://cloud.githubusercontent.com/assets/1567433/9781984/2b9244ea-57a2-11e5-89b1-edc6922d1909.jpg")!,
NSURL(string: "https://cloud.githubusercontent.com/assets/1567433/9781988/2b94f32a-57a2-11e5-94f6-2c68c15f711f.jpg")!,
NSURL(string: "https://cloud.githubusercontent.com/assets/1567433/9781983/2b80e9ca-57a2-11e5-9a90-54884428affe.jpg")!,
NSURL(string: "https://cloud.githubusercontent.com/assets/1567433/9781989/2b9d462e-57a2-11e5-8c5c-d005e79e0070.jpg")!,
NSURL(string: "https://cloud.githubusercontent.com/assets/1567433/9781990/2babeeae-57a2-11e5-828d-6c050683274d.jpg")!,
NSURL(string: "https://cloud.githubusercontent.com/assets/1567433/9781991/2bb13a94-57a2-11e5-8a70-1d7e519c1631.jpg")!,
NSURL(string: "https://cloud.githubusercontent.com/assets/1567433/9781992/2bb2161c-57a2-11e5-8715-9b7d2df58708.jpg")!,
NSURL(string: "https://cloud.githubusercontent.com/assets/1567433/9781993/2bb397a8-57a2-11e5-853d-4d4f1854d1fe.jpg")!,
NSURL(string: "https://cloud.githubusercontent.com/assets/1567433/9781994/2bb61e88-57a2-11e5-8e45-bc2ed096cf97.jpg")!,
NSURL(string: "https://cloud.githubusercontent.com/assets/1567433/9781995/2bbdf73e-57a2-11e5-8847-afb709e28495.jpg")!,
NSURL(string: "https://cloud.githubusercontent.com/assets/1567433/9781996/2bc90a66-57a2-11e5-9154-6cc3a08a3e93.jpg")!,
NSURL(string: "https://cloud.githubusercontent.com/assets/1567433/9782000/2bd232a8-57a2-11e5-8617-eaff327b927f.jpg")!,
NSURL(string: "https://cloud.githubusercontent.com/assets/1567433/9781997/2bced964-57a2-11e5-9021-970f1f92608e.jpg")!,
NSURL(string: "https://cloud.githubusercontent.com/assets/1567433/9781998/2bd0def8-57a2-11e5-850f-e60701db4f62.jpg")!,
NSURL(string: "https://cloud.githubusercontent.com/assets/1567433/9781999/2bd2551c-57a2-11e5-82e3-54bb80f7c114.jpg")!,
NSURL(string: "https://cloud.githubusercontent.com/assets/1567433/9782001/2bdb5bb2-57a2-11e5-8a18-05fe673e2315.jpg")!,
NSURL(string: "https://cloud.githubusercontent.com/assets/1567433/9782002/2be52ed0-57a2-11e5-8e12-2f6e17787553.jpg")!,
NSURL(string: "https://cloud.githubusercontent.com/assets/1567433/9782003/2bed36de-57a2-11e5-9d4f-7c214e828fe6.jpg")!,
NSURL(string: "https://cloud.githubusercontent.com/assets/1567433/9782004/2bef8ed4-57a2-11e5-8949-26e1b80a0ebb.jpg")!,
NSURL(string: "https://cloud.githubusercontent.com/assets/1567433/9782005/2bf08622-57a2-11e5-86e2-c5d71ef615e9.jpg")!,
NSURL(string: "https://cloud.githubusercontent.com/assets/1567433/9782006/2bf2d968-57a2-11e5-8f44-3cd169219e78.jpg")!,
NSURL(string: "https://cloud.githubusercontent.com/assets/1567433/9782007/2bf5e95a-57a2-11e5-9b7a-96f355a5334b.jpg")!,
NSURL(string: "https://cloud.githubusercontent.com/assets/1567433/9782008/2c04b458-57a2-11e5-9381-feb4ae365a1d.jpg")!,
NSURL(string: "https://cloud.githubusercontent.com/assets/1567433/9782011/2c0e4054-57a2-11e5-89f0-7c91bb0e01a2.jpg")!,
NSURL(string: "https://cloud.githubusercontent.com/assets/1567433/9782009/2c0c4254-57a2-11e5-984d-0e44cc762219.jpg")!,
NSURL(string: "https://cloud.githubusercontent.com/assets/1567433/9782010/2c0ca730-57a2-11e5-834c-79153b496d44.jpg")!,
NSURL(string: "https://cloud.githubusercontent.com/assets/1567433/9782012/2c1277e6-57a2-11e5-862a-ec0c8fad727a.jpg")!,
NSURL(string: "https://cloud.githubusercontent.com/assets/1567433/9782122/543bc690-57a3-11e5-83eb-156108681377.jpg")!,
NSURL(string: "https://cloud.githubusercontent.com/assets/1567433/9782128/546af1f4-57a3-11e5-8ad6-78527accf642.jpg")!,
NSURL(string: "https://cloud.githubusercontent.com/assets/1567433/9782127/546ae2cc-57a3-11e5-9ad5-f0c7157eda5b.jpg")!,
NSURL(string: "https://cloud.githubusercontent.com/assets/1567433/9782124/5468528c-57a3-11e5-9cf9-89f763b473b4.jpg")!,
NSURL(string: "https://cloud.githubusercontent.com/assets/1567433/9782126/5468cf50-57a3-11e5-9d97-c8fc94e7b9a4.jpg")!,
NSURL(string: "https://cloud.githubusercontent.com/assets/1567433/9782125/54687d66-57a3-11e5-860f-c66597fd212c.jpg")!,
NSURL(string: "https://cloud.githubusercontent.com/assets/1567433/9782123/545728cc-57a3-11e5-83ab-51462737c19d.jpg")!,
NSURL(string: "https://cloud.githubusercontent.com/assets/1567433/9782129/54737694-57a3-11e5-9e1e-b626db67e625.jpg")!,
NSURL(string: "https://cloud.githubusercontent.com/assets/1567433/9782130/5483fee2-57a3-11e5-8928-e7706c765016.jpg")!,
NSURL(string: "https://cloud.githubusercontent.com/assets/1567433/9782133/54dd0c62-57a3-11e5-85ee-a02c1b9dd223.jpg")!,
NSURL(string: "https://cloud.githubusercontent.com/assets/1567433/9782131/54872b30-57a3-11e5-8903-db1f81ea1abb.jpg")!,
NSURL(string: "https://cloud.githubusercontent.com/assets/1567433/9782132/548a3b9a-57a3-11e5-8228-8ee523e7809e.jpg")!
]
}
}
| mit | 490f0cf9399602a374f0dab8823ed5d8 | 76.987179 | 160 | 0.716834 | 2.913314 | false | false | false | false |
edragoev1/pdfjet | Sources/PDFjet/Hexadecimal.swift | 1 | 1502 | /**
* Hexadecimal.swift
*
Copyright 2020 Innovatics Inc.
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.
*/
public class Hexadecimal {
static let instance = Hexadecimal()
var digits = [UInt8]()
private init() {
for row in 0..<16 {
for col in 0..<16 {
let offset1 = (row <= 9) ? 48 : 55
digits.append(UInt8(row + offset1))
let offset2 = (col <= 9) ? 48 : 55
digits.append(UInt8(col + offset2))
}
}
}
}
| mit | 6bd5776cf5e609927de7de7925033b25 | 37.512821 | 78 | 0.702397 | 4.456973 | false | false | false | false |
sloik/CoJezdzi | CoJezdzi/CoJezdzi/SceneDelegate.swift | 1 | 2765 | //
// SceneDelegate.swift
// CoJezdzi
//
// Created by Lukasz Stocki on 29/12/2019.
// Copyright © 2019 Lukasz Stocki. All rights reserved.
//
import UIKit
import SwiftUI
class SceneDelegate: UIResponder, UIWindowSceneDelegate {
var window: UIWindow?
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
// Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`.
// If using a storyboard, the `window` property will automatically be initialized and attached to the scene.
// This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead).
// Create the SwiftUI view that provides the window contents.
let contentView = ContentView()
// Use a UIHostingController as window root view controller.
if let windowScene = scene as? UIWindowScene {
let window = UIWindow(windowScene: windowScene)
window.rootViewController = UIHostingController(rootView: contentView)
self.window = window
window.makeKeyAndVisible()
}
}
func sceneDidDisconnect(_ scene: UIScene) {
// Called as the scene is being released by the system.
// This occurs shortly after the scene enters the background, or when its session is discarded.
// Release any resources associated with this scene that can be re-created the next time the scene connects.
// The scene may re-connect later, as its session was not neccessarily discarded (see `application:didDiscardSceneSessions` instead).
}
func sceneDidBecomeActive(_ scene: UIScene) {
// Called when the scene has moved from an inactive state to an active state.
// Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive.
}
func sceneWillResignActive(_ scene: UIScene) {
// Called when the scene will move from an active state to an inactive state.
// This may occur due to temporary interruptions (ex. an incoming phone call).
}
func sceneWillEnterForeground(_ scene: UIScene) {
// Called as the scene transitions from the background to the foreground.
// Use this method to undo the changes made on entering the background.
}
func sceneDidEnterBackground(_ scene: UIScene) {
// Called as the scene transitions from the foreground to the background.
// Use this method to save data, release shared resources, and store enough scene-specific state information
// to restore the scene back to its current state.
}
}
| gpl-3.0 | 33f7f4f914ac1872161d09467ef9d65e | 42.1875 | 147 | 0.704052 | 5.284895 | false | false | false | false |
zweigraf/march-thirteen | MarchThirteen/MarchThirteen/ViewController.swift | 1 | 3735 | //
// ViewController.swift
// MarchThirteen
//
// Created by Luis Reisewitz on 13.03.17.
// Copyright © 2017 ZweiGraf. All rights reserved.
//
import UIKit
import PureLayout
import Sensitive
import JSQMessagesViewController
class ViewController: JSQMessagesViewController {
let startTime = mach_absolute_time()
let incomingBubble = JSQMessagesBubbleImageFactory().incomingMessagesBubbleImage(with: UIColor(red: 10/255, green: 180/255, blue: 230/255, alpha: 1.0))
let outgoingBubble = JSQMessagesBubbleImageFactory().outgoingMessagesBubbleImage(with: UIColor.lightGray)
override func viewDidLoad() {
super.viewDidLoad()
automaticallyScrollsToMostRecentMessage = true
chatRoom.messagesChanged = messagesChanged
chatRoom.typingStatusChanged = typingStatusChanged
chatRoom.usersChanged = usersChanged
}
// MARK: Model
let chatRoom = ChatRoom()
}
// MARK: - JSQMessagesViewController Overrides
extension ViewController {
override func senderId() -> String {
return chatRoom.ownName
}
override func senderDisplayName() -> String {
return chatRoom.ownName
}
override func didPressSend(_ button: UIButton, withMessageText text: String, senderId: String, senderDisplayName: String, date: Date) {
chatRoom.send(message: text)
finishSendingMessage(animated: true)
}
override func textViewDidChange(_ textView: UITextView) {
super.textViewDidChange(textView)
// Send start typing message when the textfield has one character
guard textView.text?.characters.count == 1 else { return }
chatRoom.sendStartTyping()
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return chatRoom.messages.count
}
override func collectionView(_ collectionView: JSQMessagesCollectionView, messageDataForItemAt indexPath: IndexPath) -> JSQMessageData {
let data = chatRoom.messages[indexPath.row]
let text: String
if case let .message(messageText) = data.event {
text = messageText
} else {
text = ""
}
return JSQMessage(senderId: data.username, displayName: data.username, text: text)
}
override func collectionView(_ collectionView: JSQMessagesCollectionView, messageBubbleImageDataForItemAt indexPath: IndexPath) -> JSQMessageBubbleImageDataSource? {
let data = self.collectionView(collectionView, messageDataForItemAt: indexPath)
switch(data.senderId()) {
case senderId():
return self.outgoingBubble
default:
return self.incomingBubble
}
}
override func collectionView(_ collectionView: JSQMessagesCollectionView, avatarImageDataForItemAt indexPath: IndexPath) -> JSQMessageAvatarImageDataSource? {
let data = chatRoom.messages[indexPath.row]
guard let image = UIImage.initialsImage(for: data.username) else {
return nil
}
return JSQMessagesAvatarImage(avatarImage: image, highlightedImage: nil, placeholderImage: image)
}
}
// MARK: - Chat Room Callbacks
extension ViewController {
func messagesChanged() {
DispatchQueue.main.async {
self.finishReceivingMessage(animated: true)
}
}
func typingStatusChanged(shouldShowTypingIndicator: Bool) {
DispatchQueue.main.async {
self.showTypingIndicator = shouldShowTypingIndicator
}
}
func usersChanged(users: [String]) {
DispatchQueue.main.async {
self.title = users.joined(separator: ", ")
}
}
}
| mit | fc94385da2fa7ea21faddcdfa9eb4050 | 33.897196 | 169 | 0.684253 | 5.288952 | false | false | false | false |
wiseguy16/iOS-Portfolio | NacdNews/BlogDetailViewController.swift | 1 | 2023 | //
// BlogDetailViewController.swift
// NacdNews
//
// Created by Gregory Weiss on 8/31/16.
// Copyright © 2016 Gregory Weiss. All rights reserved.
//
import UIKit
import WebKit
class BlogDetailViewController: UIViewController {
@IBOutlet weak var blogScrollView: UIScrollView!
@IBOutlet weak var contentView: UIView!
var aBlogItem: BlogItem!
var shareBody: String?
@IBOutlet weak var blogImage: UIImageView!
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var authorLabel: UILabel!
@IBOutlet weak var dateLabel: UILabel!
@IBOutlet weak var subTextLabel: UILabel!
@IBOutlet weak var bodyLabel: UILabel!
@IBOutlet weak var bioLabel: UILabel!
// @IBOutlet weak var awesomeWebView: UIWebView!
override func viewDidLoad() {
super.viewDidLoad()
shareBody = aBlogItem.body
configureView()
}
override func viewWillLayoutSubviews()
{
super.viewWillLayoutSubviews();
self.blogScrollView.frame = self.view.bounds; // Instead of using auto layout
self.blogScrollView.contentSize.height = 3000; // Or whatever you want it to be.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func sharingTapped(sender: UIButton)
{
let vc = UIActivityViewController(activityItems: [shareBody!], applicationActivities: nil)
self.presentViewController(vc, animated: true, completion: nil)
}
func configureView()
{
titleLabel.text = aBlogItem.title
authorLabel.text = aBlogItem.author.uppercaseString
dateLabel.text = aBlogItem.entry_date
subTextLabel.text = aBlogItem.subText
bodyLabel.text = aBlogItem.body
bioLabel.text = aBlogItem.bioDisclaimer
blogImage.image = UIImage(named: aBlogItem.blog_primary)
}
}
| gpl-3.0 | 19c311777aa3a7fbed2ece3030fe884b | 25.96 | 98 | 0.660237 | 4.791469 | false | false | false | false |
remobjects/ElementsSamples | Iodine/Gotham/Command Line/Mandelbrot/Program.swift | 1 | 669 | let cols = 78
let lines = 30
var chars = [" ",".",",","`","'",":","=","|","+","i","h","I","H","E","O","Q","S","B","#","$"]
let maxIter = count(chars)
var minRe = -2.0
var maxRe = 1.0
var minIm = -1.0
var maxIm = 1.0
var im = minIm
while im <= maxIm
{
var re = minRe
while re <= maxRe
{
var zr = re
var zi = im
var n = -1
while n < maxIter-1
{
n++
var a = zr * zr
var b = zi * zi
if a + b > 4.0 { break }
zi = 2 * zr * zi + im
zr = a - b + re
}
print(chars[n], separator: "", terminator: "")
re += (maxRe - minRe) / /*Double*/(cols)
}
print()
im += (maxIm - minIm) / /*Double*/(lines)
}
| mit | 5ba02b83e52b02dbe21b614fb01af485 | 16.527778 | 93 | 0.443778 | 2.332168 | false | false | false | false |
ingresse/ios-sdk | IngresseSDK/Model/Highlight.swift | 1 | 348 | //
// Copyright © 2017 Ingresse. All rights reserved.
//
public struct Highlight: Decodable {
public var banner: String = ""
public var target: String = ""
}
extension Highlight: Equatable {
public static func == (lhs: Highlight, rhs: Highlight) -> Bool {
return lhs.banner == rhs.banner && lhs.target == rhs.target
}
}
| mit | 3b3799983556f85b6527c8084925b7db | 23.785714 | 68 | 0.642651 | 3.988506 | false | false | false | false |
RichRelevance/rr-ios-sdk | Demo/RichRelevanceSDKDemo/RCHCatalogCollectionViewController.swift | 1 | 3802 | //
// Copyright (c) 2016 Rich Relevance Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import UIKit
private let reuseIdentifier = "productCell"
class RCHCatalogCollectionViewController: UICollectionViewController {
@IBOutlet var spinner: UIActivityIndicatorView!
var productArray: [RCHRecommendedProduct] = []
override func viewDidLoad() {
super.viewDidLoad()
collectionView!.register(UINib(nibName: "RCHProductCollectionViewCell", bundle: nil), forCellWithReuseIdentifier: reuseIdentifier)
}
override func viewWillAppear(_ animated: Bool) {
loadData()
}
func loadData() {
navigationItem.title = UserDefaults.standard.string(forKey: kRCHUserDefaultKeyClientName)
spinner.startAnimating()
spinner.isHidden = false
let strategyBuilder: RCHStrategyRecsBuilder = RCHSDK.builderForRecs(with: .siteWideBestSellers)
RCHSDK.defaultClient().sendRequest(strategyBuilder.build(), success: { (responseObject) in
guard let strategyResponse = responseObject as? RCHStrategyResult else {
print("Result Error")
return
}
guard let productArray = strategyResponse.recommendedProducts else {
print("Recommended Products Error")
return
}
self.productArray = productArray
self.collectionView?.reloadData()
self.spinner.stopAnimating()
}) { (responseObject, error) in
self.spinner.stopAnimating()
let alert = UIAlertController(title: "Error", message: error?.localizedDescription, preferredStyle: .alert)
let okAction = UIAlertAction(title: "OK", style: .default, handler: nil)
alert.addAction(okAction)
self.present(alert, animated: true, completion: nil)
print(error)
}
}
@IBAction func menuSelected(sender: UIBarButtonItem) {
self.dismiss(animated: true, completion: nil)
}
// MARK: UICollectionViewDataSource
override func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return productArray.count
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! RCHProductCollectionViewCell
let product = productArray[indexPath.row]
let numberFormatter = NumberFormatter()
numberFormatter.numberStyle = .currency
let priceCentsToDollars = (product.priceCents?.intValue)! / 100 as NSNumber
cell.priceLabel.text = numberFormatter.string(from: priceCentsToDollars)
cell.productImage.sd_setImage(with: URL(string: product.imageURL!))
cell.brandLabel.text = product.brand?.uppercased()
cell.titleLabel.text = product.name
return cell
}
}
| apache-2.0 | dcff7d9e90a9e5b8d7ec1c8b8f6f5ce8 | 37.02 | 140 | 0.664124 | 5.273232 | false | false | false | false |
hakeemsyd/twitter | twitter/ProfileHeader.swift | 1 | 1503 | //
// ProfileHeader.swift
// twitter
//
// Created by Syed Hakeem Abbas on 10/7/17.
// Copyright © 2017 codepath. All rights reserved.
//
import UIKit
class ProfileHeader: UITableViewCell {
var user: User! {
didSet {
if user != nil {
update()
}
}
}
@IBOutlet weak var followerCount: UILabel!
@IBOutlet weak var followingCount: UILabel!
@IBOutlet weak var tweetsCount: UILabel!
@IBOutlet weak var displayName: UILabel!
@IBOutlet weak var userName: UILabel!
@IBOutlet weak var profilePicture: UIImageView!
@IBOutlet weak var coverPhoto: UIImageView!
override func awakeFromNib() {
super.awakeFromNib()
if user != nil {
update()
}
}
func update() {
if let coverImageUrl = user.coverImageUrl {
Helper.loadPhoto(withUrl: coverImageUrl, into: coverPhoto)
}
if let profileImageUrl = user.profileImageUrl {
Helper.loadPhoto(withUrl: profileImageUrl, into: profilePicture)
}
userName.text = user.name
displayName.text = "@\(user.screenname ?? "")"
tweetsCount.text = "\(user.tweetCount ?? 0)"
followingCount.text = "\(user.followingCount ?? 0)"
followerCount.text = "\(user.followersCount ?? 0)"
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
}
}
| apache-2.0 | d98216ad5dad032e08ea30e62899808c | 25.821429 | 76 | 0.596538 | 4.650155 | false | false | false | false |
rporzuc/FindFriends | FindFriends/FindFriends/MessagesViews/MessagesTableViewController.swift | 1 | 6245 | //
// MessagesTableViewController.swift
// FindFriends
//
// Created by MacOSXRAFAL on 10/9/17.
// Copyright © 2017 MacOSXRAFAL. All rights reserved.
//
import UIKit
class MessagesTableViewController: UITableViewController, ObserverMessagesProtocol {
var idNewConverser : Int?
var nameNewConverser : String?
var imageNewConverser : UIImage?
public struct conversation{
var birthdayConverser: NSDate?
var firstNameConverser: String?
var idConversation: Int32
var idConverser: Int32
var imageConverser: NSData?
var lastNameConverser: String?
var sexConverser: String?
var newMessages : Bool?
var dateOfLastMessage : NSDate?
var descriptionOfConverser: String?
}
var arrayConversations : [conversation] = [conversation]()
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewDidAppear(_ animated: Bool) {
self.refreshArrayWithDataConversations()
DataManagement.shared.attachObserverMessages(observer: self)
}
override func viewDidDisappear(_ animated: Bool) {
DataManagement.shared.removeObserverMessages(observer: self)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func refreshArrayWithDataConversations()
{
// arrayConversations.removeAll()
DispatchQueue.global(qos: .background).async {
if self.idNewConverser != nil{
DataManagement.shared.getNameAndImagePeopleNearby(idPerson: self.idNewConverser!, completion: {
(name, image) in
self.nameNewConverser = name
self.imageNewConverser = image
})
}
DataManagement.shared.getConversationsData(completion: { array in
self.arrayConversations = array!
self.arrayConversations.sort(by: { (lhs : conversation, rhs: conversation) -> Bool in
if lhs.dateOfLastMessage != nil && rhs.dateOfLastMessage != nil{
return (lhs.dateOfLastMessage?.timeIntervalSince1970)! > (rhs.dateOfLastMessage?.timeIntervalSince1970)!
}else{
return true
}
})
DispatchQueue.main.async {
print("refresh")
self.tableView.reloadData()
self.refreshControl?.endRefreshing()
if self.idNewConverser != nil{
let index = self.arrayConversations.index(where: {
Int($0.idConverser) == self.idNewConverser!
})
if index != nil{
let indexPath = IndexPath(item : index!, section: 0)
let cell = self.tableView.cellForRow(at: indexPath) as! CustomMessagesTableViewCell
cell.labelName.textColor = UIColor.darkGray
cell.markerNewMessage.isHidden = true
self.idNewConverser = nil
self.performSegue(withIdentifier: "segueConversationView", sender: indexPath)
}else{
self.performSegue(withIdentifier: "segueConversationView", sender: nil)
}
}
}
})
}
}
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return arrayConversations.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "customMessageCell", for: indexPath) as! CustomMessagesTableViewCell
cell.labelName.text = arrayConversations[indexPath.row].firstNameConverser! + " " + arrayConversations[indexPath.row].lastNameConverser!
cell.labelName.textColor = UIColor.darkGray
cell.imgPerson.image = UIImage(data: arrayConversations[indexPath.row].imageConverser as! Data)
if arrayConversations[indexPath.row].newMessages!{
cell.markerNewMessage.isHidden = false
}
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let cell = tableView.cellForRow(at: indexPath) as! CustomMessagesTableViewCell
cell.labelName.textColor = UIColor.darkGray
cell.markerNewMessage.isHidden = true
self.performSegue(withIdentifier: "segueConversationView", sender: indexPath)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let destinationView = segue.destination as! ConversationViewController
if sender != nil {
let cell = self.tableView.cellForRow(at: sender as! IndexPath) as! CustomMessagesTableViewCell
destinationView.idConversation = Int(arrayConversations[(sender as! IndexPath).row].idConversation)
destinationView.idConverser = Int(arrayConversations[(sender as! IndexPath).row].idConverser)
destinationView.name = cell.labelName.text
destinationView.imgOfTheSender = cell.imgPerson.image
}else{
destinationView.idConversation = nil
destinationView.idConverser = self.idNewConverser
destinationView.name = self.nameNewConverser
destinationView.imgOfTheSender = self.imageNewConverser
self.idNewConverser = nil
}
}
//MARK: - observer message update func
func updateObserverMessages() {
self.refreshArrayWithDataConversations()
}
}
| gpl-3.0 | ae395dd7a8eeab40af9443f4dd47a465 | 35.946746 | 144 | 0.59353 | 5.579982 | false | false | false | false |
stripe/stripe-ios | Tests/Tests/STPPaymentHandlerStubbedMockedFilesTests.swift | 1 | 15488 | //
// STPPaymentHandlerStubbedMockedFilesTests.swift
// StripeiOS Tests
//
// Copyright © 2022 Stripe, Inc. All rights reserved.
//
import OHHTTPStubs
import StripeCoreTestUtils
import XCTest
@testable@_spi(STP) import Stripe
@testable@_spi(STP) import StripeApplePay
@testable@_spi(STP) import StripeCore
class STPPaymentHandlerStubbedMockedFilesTests: APIStubbedTestCase, STPAuthenticationContext {
override func setUp() {
let expectation = expectation(description: "Load Specs")
FormSpecProvider.shared.load { success in
expectation.fulfill()
}
wait(for: [expectation], timeout: 2.0)
}
func testCallConfirmAfterpay_Redirect_thenCanceled() {
let nextActionData = """
{
"redirect_to_url": {
"return_url": "payments-example://stripe-redirect",
"url": "https://hooks.stripe.com/afterpay_clearpay/acct_123/pa_nonce_321/redirect"
},
"type": "redirect_to_url"
}
"""
let paymentMethod = """
{
"id": "pm_123123123123123",
"object": "payment_method",
"afterpay_clearpay": {},
"billing_details": {
"address": {
"city": "San Francisco",
"country": "AT",
"line1": "510 Townsend St.",
"line2": "",
"postal_code": "94102",
"state": null
},
"email": "[email protected]",
"name": "Jane Doe",
"phone": null
},
"created": 1658187899,
"customer": null,
"livemode": false,
"type": "afterpay_clearpay"
}
"""
stubConfirm(
fileMock: .paymentIntentResponse,
responseCallback: { data in
self.replaceData(
data: data,
variables: [
"<next_action>": nextActionData,
"<payment_method>": paymentMethod,
"<status>": "\"requires_action\"",
]
)
}
)
let paymentHandler = STPPaymentHandler(apiClient: stubbedAPIClient())
let paymentIntentParams = STPPaymentIntentParams(clientSecret: "pi_123456_secret_654321")
paymentIntentParams.returnURL = "payments-example://stripe-redirect"
paymentIntentParams.paymentMethodParams = STPPaymentMethodParams(
afterpayClearpay: STPPaymentMethodAfterpayClearpayParams(),
billingDetails: STPPaymentMethodBillingDetails(),
metadata: nil
)
paymentIntentParams.paymentMethodParams?.afterpayClearpay =
STPPaymentMethodAfterpayClearpayParams()
let didRedirect = expectation(description: "didRedirect")
paymentHandler._redirectShim = { redirectTo, returnToURL in
XCTAssertEqual(
redirectTo.absoluteString,
"https://hooks.stripe.com/afterpay_clearpay/acct_123/pa_nonce_321/redirect"
)
XCTAssertEqual(returnToURL?.absoluteString, "payments-example://stripe-redirect")
didRedirect.fulfill()
}
let expectConfirmWasCanceled = expectation(description: "didCancel")
paymentHandler.confirmPayment(paymentIntentParams, with: self) {
status,
paymentIntent,
error in
if case .canceled = status {
expectConfirmWasCanceled.fulfill()
}
}
guard XCTWaiter.wait(for: [didRedirect], timeout: 2.0) != .timedOut else {
XCTFail("Unable to redirect")
return
}
//Test the cancel case
stubRetrievePaymentIntent(
fileMock: .paymentIntentResponse,
responseCallback: { data in
self.replaceData(
data: data,
variables: [
"<next_action>": nextActionData,
"<payment_method>": paymentMethod,
"<status>": "\"requires_action\"",
]
)
}
)
paymentHandler._retrieveAndCheckIntentForCurrentAction()
wait(for: [expectConfirmWasCanceled], timeout: 2.0)
}
func testCallConfirmAfterpay_Redirect_thenSucceeded() {
let nextActionData = """
{
"redirect_to_url": {
"return_url": "payments-example://stripe-redirect",
"url": "https://hooks.stripe.com/afterpay_clearpay/acct_123/pa_nonce_321/redirect"
},
"type": "redirect_to_url"
}
"""
let paymentMethod = """
{
"id": "pm_123123123123123",
"object": "payment_method",
"afterpay_clearpay": {},
"billing_details": {
"address": {
"city": "San Francisco",
"country": "AT",
"line1": "510 Townsend St.",
"line2": "",
"postal_code": "94102",
"state": null
},
"email": "[email protected]",
"name": "Jane Doe",
"phone": null
},
"created": 1658187899,
"customer": null,
"livemode": false,
"type": "afterpay_clearpay"
}
"""
stubConfirm(
fileMock: .paymentIntentResponse,
responseCallback: { data in
self.replaceData(
data: data,
variables: [
"<next_action>": nextActionData,
"<payment_method>": paymentMethod,
"<status>": "\"requires_action\"",
]
)
}
)
let paymentHandler = STPPaymentHandler(apiClient: stubbedAPIClient())
let paymentIntentParams = STPPaymentIntentParams(clientSecret: "pi_123456_secret_654321")
paymentIntentParams.returnURL = "payments-example://stripe-redirect"
paymentIntentParams.paymentMethodParams = STPPaymentMethodParams(
afterpayClearpay: STPPaymentMethodAfterpayClearpayParams(),
billingDetails: STPPaymentMethodBillingDetails(),
metadata: nil
)
paymentIntentParams.paymentMethodParams?.afterpayClearpay =
STPPaymentMethodAfterpayClearpayParams()
let didRedirect = expectation(description: "didRedirect")
paymentHandler._redirectShim = { redirectTo, returnToURL in
XCTAssertEqual(
redirectTo.absoluteString,
"https://hooks.stripe.com/afterpay_clearpay/acct_123/pa_nonce_321/redirect"
)
XCTAssertEqual(returnToURL?.absoluteString, "payments-example://stripe-redirect")
didRedirect.fulfill()
}
let expectConfirmSucceeded = expectation(description: "didSucceed")
paymentHandler.confirmPayment(paymentIntentParams, with: self) {
status,
paymentIntent,
error in
if case .succeeded = status {
expectConfirmSucceeded.fulfill()
}
}
guard XCTWaiter.wait(for: [didRedirect], timeout: 2.0) != .timedOut else {
XCTFail("Unable to redirect")
return
}
// Test status as succeeded
stubRetrievePaymentIntent(
fileMock: .paymentIntentResponse,
responseCallback: { data in
self.replaceData(
data: data,
variables: [
"<next_action>": nextActionData,
"<payment_method>": paymentMethod,
"<status>": "\"succeeded\"",
]
)
}
)
paymentHandler._retrieveAndCheckIntentForCurrentAction()
wait(for: [expectConfirmSucceeded], timeout: 2.0)
}
func testCallConfirmAfterpay_Redirect_thenSucceeded_withoutNextActionSpec() {
// Validate affirm is read in with next action spec
guard let affirm = FormSpecProvider.shared.formSpec(for: "affirm"),
affirm.fields.count == 1,
affirm.fields.first == .affirm_header,
case .redirect_to_url = affirm.nextActionSpec?.confirmResponseStatusSpecs[
"requires_action"
]?.type,
case .finished = affirm.nextActionSpec?.postConfirmHandlingPiStatusSpecs?["succeeded"]?
.type,
case .canceled = affirm.nextActionSpec?.postConfirmHandlingPiStatusSpecs?[
"requires_action"
]?.type
else {
XCTFail()
return
}
// Override it with a spec that doesn't define a next action so that we force the SDK to default behavior
let updatedSpecJson =
"""
[{
"type": "affirm",
"async": false,
"fields": [
{
"type": "name"
}
]
}]
""".data(using: .utf8)!
let formSpec = try! JSONSerialization.jsonObject(with: updatedSpecJson) as! [NSDictionary]
FormSpecProvider.shared.load(from: formSpec)
guard let affirmUpdated = FormSpecProvider.shared.formSpec(for: "affirm") else {
XCTFail()
return
}
XCTAssertNil(affirmUpdated.nextActionSpec)
let nextActionData = """
{
"redirect_to_url": {
"return_url": "payments-example://stripe-redirect",
"url": "https://hooks.stripe.com/affirm/acct_123/pa_nonce_321/redirect"
},
"type": "redirect_to_url"
}
"""
let paymentMethod = """
{
"id": "pm_123123123123123",
"object": "payment_method",
"afterpay_clearpay": {},
"billing_details": {
"address": {
"city": "San Francisco",
"country": "AT",
"line1": "510 Townsend St.",
"line2": "",
"postal_code": "94102",
"state": null
},
"email": "[email protected]",
"name": "Jane Doe",
"phone": null
},
"created": 1658187899,
"customer": null,
"livemode": false,
"type": "afterpay_clearpay"
}
"""
stubConfirm(
fileMock: .paymentIntentResponse,
responseCallback: { data in
self.replaceData(
data: data,
variables: [
"<next_action>": nextActionData,
"<payment_method>": paymentMethod,
"<status>": "\"requires_action\"",
]
)
}
)
let paymentHandler = STPPaymentHandler(apiClient: stubbedAPIClient())
let paymentIntentParams = STPPaymentIntentParams(clientSecret: "pi_123456_secret_654321")
paymentIntentParams.returnURL = "payments-example://stripe-redirect"
paymentIntentParams.paymentMethodParams = STPPaymentMethodParams(
afterpayClearpay: STPPaymentMethodAfterpayClearpayParams(),
billingDetails: STPPaymentMethodBillingDetails(),
metadata: nil
)
paymentIntentParams.paymentMethodParams?.afterpayClearpay =
STPPaymentMethodAfterpayClearpayParams()
let didRedirect = expectation(description: "didRedirect")
paymentHandler._redirectShim = { redirectTo, returnToURL in
XCTAssertEqual(
redirectTo.absoluteString,
"https://hooks.stripe.com/affirm/acct_123/pa_nonce_321/redirect"
)
XCTAssertEqual(returnToURL?.absoluteString, "payments-example://stripe-redirect")
didRedirect.fulfill()
}
let expectConfirmSucceeded = expectation(description: "didSucceed")
paymentHandler.confirmPayment(paymentIntentParams, with: self) {
status,
paymentIntent,
error in
if case .succeeded = status {
expectConfirmSucceeded.fulfill()
}
}
guard XCTWaiter.wait(for: [didRedirect], timeout: 2.0) != .timedOut else {
XCTFail("Unable to redirect")
return
}
// Test status as succeeded
stubRetrievePaymentIntent(
fileMock: .paymentIntentResponse,
responseCallback: { data in
self.replaceData(
data: data,
variables: [
"<next_action>": nextActionData,
"<payment_method>": paymentMethod,
"<status>": "\"succeeded\"",
]
)
}
)
paymentHandler._retrieveAndCheckIntentForCurrentAction()
wait(for: [expectConfirmSucceeded], timeout: 2.0)
}
private func replaceData(data: Data, variables: [String: String]) -> Data {
var template = String(data: data, encoding: .utf8)!
for (templateKey, templateValue) in variables {
let translated = template.replacingOccurrences(of: templateKey, with: templateValue)
template = translated
}
return template.data(using: .utf8)!
}
private func stubConfirm(fileMock: FileMock, responseCallback: ((Data) -> Data)? = nil) {
stub { urlRequest in
return urlRequest.url?.absoluteString.contains("/confirm") ?? false
} response: { urlRequest in
let mockResponseData = try! fileMock.data()
let data = responseCallback?(mockResponseData) ?? mockResponseData
return HTTPStubsResponse(data: data, statusCode: 200, headers: nil)
}
}
private func stubRetrievePaymentIntent(
fileMock: FileMock,
responseCallback: ((Data) -> Data)? = nil
) {
stub { urlRequest in
return urlRequest.url?.absoluteString.contains("/payment_intents") ?? false
} response: { urlRequest in
let mockResponseData = try! fileMock.data()
let data = responseCallback?(mockResponseData) ?? mockResponseData
return HTTPStubsResponse(data: data, statusCode: 200, headers: nil)
}
}
}
extension STPPaymentHandlerStubbedMockedFilesTests {
func authenticationPresentingViewController() -> UIViewController {
return UIViewController()
}
}
public class ClassForBundle {}
@_spi(STP) public enum FileMock: String, MockData {
public typealias ResponseType = StripeFile
public var bundle: Bundle { return Bundle(for: ClassForBundle.self) }
case paymentIntentResponse = "MockFiles/paymentIntentResponse"
}
| mit | 30dd9e38bc81f94e26045da3bad045e1 | 37.42928 | 113 | 0.527216 | 5.258744 | false | true | false | false |
TurfDb/Turf | Turf/Observable/MiniRx/SharedObservable.swift | 1 | 1245 | import Foundation
///
/// Reference counted multicast observable.
/// Will only dispose of the source when all subscribers have been disposed.
///
open class SharedObservable<Value>: Producer<Value> {
// MARK: Private methods
private let subject: Subject<Value>
private let disposable: Disposable
// MARK: Object lifecycle
init(source: Observable<Value>, subject: Subject<Value>) {
self.disposable = source.subscribe(subject)
self.subject = subject
}
// MARK: Public methods
override func run<Observer: ObserverType>(_ observer: Observer) -> Disposable where Observer.Value == Value {
let subscriberDisposable = subject.subscribe(observer)
return BasicDisposable {
subscriberDisposable.dispose()
self.subject.safeSubscriberCount { count in
if count == 0 {
self.disposable.dispose()
}
}
}
}
}
extension Observable {
public func share() -> SharedObservable<Value> {
return multicast(subject: Subject())
}
public func multicast(subject: Subject<Value>) -> SharedObservable<Value> {
return SharedObservable(source: self, subject: subject)
}
}
| mit | ebd813e1fca46d52eb47be904a59fea0 | 26.666667 | 113 | 0.641767 | 4.960159 | false | false | false | false |
CatchChat/Yep | Yep/ViewControllers/PodsHelpYep/PodsHelpYepViewController.swift | 1 | 5308 | //
// PodsHelpYepViewController.swift
// Yep
//
// Created by nixzhu on 15/8/31.
// Copyright (c) 2015年 Catch Inc. All rights reserved.
//
import UIKit
final class PodsHelpYepViewController: UITableViewController {
private let pods: [[String: String]] = [
[
"name": "RealmSwift",
"URLString": "https://github.com/realm/realm-cocoa",
],
[
"name": "Proposer",
"URLString": "https://github.com/nixzhu/Proposer",
],
[
"name": "KeyboardMan",
"URLString": "https://github.com/nixzhu/KeyboardMan",
],
[
"name": "Ruler",
"URLString": "https://github.com/nixzhu/Ruler",
],
[
"name": "MonkeyKing",
"URLString": "https://github.com/nixzhu/MonkeyKing",
],
[
"name": "Navi",
"URLString": "https://github.com/nixzhu/Navi",
],
[
"name": "AudioBot",
"URLString": "https://github.com/nixzhu/AudioBot",
],
[
"name": "AutoReview",
"URLString": "https://github.com/nixzhu/AutoReview",
],
[
"name": "Kingfisher",
"URLString": "https://github.com/onevcat/Kingfisher",
],
[
"name": "FXBlurView",
"URLString": "https://github.com/nicklockwood/FXBlurView",
],
[
"name": "TPKeyboardAvoiding",
"URLString": "https://github.com/michaeltyson/TPKeyboardAvoiding",
],
[
"name": "DeviceGuru",
"URLString": "https://github.com/InderKumarRathore/DeviceGuru",
],
[
"name": "Alamofire",
"URLString": "https://github.com/Alamofire/Alamofire",
],
[
"name": "Pop",
"URLString": "https://github.com/facebook/pop",
],
[
"name": "RxSwift",
"URLString": "https://github.com/ReactiveX/RxSwift",
],
].sort({ a, b in
if let nameA = a["name"], nameB = b["name"] {
return nameA < nameB
}
return true
})
override func viewDidLoad() {
super.viewDidLoad()
title = NSLocalizedString("Open Source", comment: "")
tableView.tableFooterView = UIView()
}
// MARK: - Table view data source
enum Section: Int {
case Yep
case Pods
var headerTitle: String {
switch self {
case .Yep:
return NSLocalizedString("Yep", comment: "")
case .Pods:
return NSLocalizedString("Third Party", comment: "")
}
}
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 2
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
guard let section = Section(rawValue: section) else {
fatalError()
}
switch section {
case .Yep:
return 1
case .Pods:
return pods.count
}
}
override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
guard let section = Section(rawValue: section) else {
fatalError()
}
return section.headerTitle
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
guard let section = Section(rawValue: indexPath.section) else {
fatalError()
}
switch section {
case .Yep:
let cell = tableView.dequeueReusableCellWithIdentifier("YepCell", forIndexPath: indexPath)
cell.textLabel?.text = NSLocalizedString("Yep on GitHub", comment: "")
cell.detailTextLabel?.text = NSLocalizedString("Welcome contributions!", comment: "")
return cell
case .Pods:
let cell = tableView.dequeueReusableCellWithIdentifier("PodCell", forIndexPath: indexPath)
let pod = pods[indexPath.row]
cell.textLabel?.text = pod["name"]
return cell
}
}
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
guard let section = Section(rawValue: indexPath.section) else {
fatalError()
}
switch section {
case .Yep:
return 60
case .Pods:
return 44
}
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
defer {
tableView.deselectRowAtIndexPath(indexPath, animated: true)
}
guard let section = Section(rawValue: indexPath.section) else {
fatalError()
}
switch section {
case .Yep:
if let URL = NSURL(string: "https://github.com/CatchChat/Yep") {
yep_openURL(URL)
}
case .Pods:
let pod = pods[indexPath.row]
if let URLString = pod["URLString"], URL = NSURL(string: URLString) {
yep_openURL(URL)
}
}
}
}
| mit | 023360bba423604502406e7679a02fd3 | 26.071429 | 118 | 0.529024 | 4.758744 | false | false | false | false |
MaartenBrijker/project | project/External/AudioKit-master/AudioKit/iOS/AudioKit/AudioKit.playground/Pages/Pink and White Noise Generators.xcplaygroundpage/Contents.swift | 4 | 1621 | //: [TOC](Table%20Of%20Contents) | [Previous](@previous) | [Next](@next)
//:
//: ---
//:
//: ## Pink and White Noise Generators
//:
import XCPlayground
import AudioKit
var pink = AKPinkNoise(amplitude: 0.1)
var white = AKWhiteNoise(amplitude: 0.1)
var pinkWhiteMixer = AKDryWetMixer(pink, white, balance: 0)
AudioKit.output = pinkWhiteMixer
AudioKit.start()
pink.start()
white.start()
//: User Interface Set up
class PlaygroundView: AKPlaygroundView {
var volumeLabel: Label?
var balanceLabel: Label?
override func setup() {
addTitle("Pink and White Noise")
volumeLabel = addLabel("Volume: \(pink.amplitude)")
addSlider(#selector(setVolume), value: pink.amplitude)
balanceLabel = addLabel("Pink to White Noise Balance: \(pinkWhiteMixer.balance)")
addSlider(#selector(setBalance), value: pinkWhiteMixer.balance)
}
func setBalance(slider: Slider) {
pinkWhiteMixer.balance = Double(slider.value)
balanceLabel!.text = "Pink to White Noise Balance: \(String(format: "%0.3f", pinkWhiteMixer.balance))"
pinkWhiteMixer.balance // to plot value history
}
func setVolume(slider: Slider) {
pink.amplitude = Double(slider.value)
white.amplitude = Double(slider.value)
volumeLabel!.text = "Volume: \(String(format: "%0.3f", pink.amplitude))"
}
}
let view = PlaygroundView(frame: CGRect(x: 0, y: 0, width: 500, height: 300))
XCPlaygroundPage.currentPage.needsIndefiniteExecution = true
XCPlaygroundPage.currentPage.liveView = view
//: [TOC](Table%20Of%20Contents) | [Previous](@previous) | [Next](@next)
| apache-2.0 | 32ab742fe8cf48d4315c90f02db22ce1 | 30.173077 | 110 | 0.685379 | 3.859524 | false | false | false | false |
luizlopezm/ios-Luis-Trucking | Pods/Eureka/Source/Rows/Common/DateInlineFieldRow.swift | 1 | 1637 | //
// DateInlineFieldRow.swift
// Eureka
//
// Created by Martin Barreto on 2/24/16.
// Copyright © 2016 Xmartlabs. All rights reserved.
//
import Foundation
public class DateInlineCell : Cell<NSDate>, CellType {
public required init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
height = { BaseRow.estimatedRowHeight }
}
public override func setup() {
super.setup()
accessoryType = .None
editingAccessoryType = .None
}
public override func update() {
super.update()
selectionStyle = row.isDisabled ? .None : .Default
detailTextLabel?.text = row.displayValueFor?(row.value)
}
public override func didSelect() {
super.didSelect()
row.deselect()
}
}
public class _DateInlineFieldRow: Row<NSDate, DateInlineCell>, DatePickerRowProtocol {
/// The minimum value for this row's UIDatePicker
public var minimumDate : NSDate?
/// The maximum value for this row's UIDatePicker
public var maximumDate : NSDate?
/// The interval between options for this row's UIDatePicker
public var minuteInterval : Int?
/// The formatter for the date picked by the user
public var dateFormatter: NSDateFormatter?
required public init(tag: String?) {
super.init(tag: tag)
displayValueFor = { [unowned self] value in
guard let val = value, let formatter = self.dateFormatter else { return nil }
return formatter.stringFromDate(val)
}
}
}
| mit | 245131b1346e06d71a5c1ecb4d695e3b | 26.728814 | 89 | 0.646699 | 4.912913 | false | false | false | false |
ifelseboyxx/xx_Notes | contents/Parallex/ParallexDemo/ParallexDemo/ViewController.swift | 1 | 2006 | //
// ViewController.swift
// ParallexDemo
//
// Created by lx13417 on 2018/1/9.
// Copyright © 2018年 ifelseboyxx. All rights reserved.
//
import UIKit
private let ItemPicIdentifier = "ItemPic"
class ViewController: UIViewController {
@IBOutlet weak var cvParallex: UICollectionView!
let datas = [UIImage.init(named: "p0.jpg"),UIImage.init(named: "p1.jpg"),UIImage.init(named: "p2.jpg")]
override func viewDidLoad() {
super.viewDidLoad()
self.cvParallex.register(UINib.init(nibName: NSStringFromClass(ItemPic.self).components(separatedBy: ".").last!, bundle: nil), forCellWithReuseIdentifier: ItemPicIdentifier);
}
}
extension ViewController: UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return datas.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: ItemPicIdentifier, for: indexPath) as! ItemPic
cell.image = datas[indexPath.row]!
return cell
}
}
extension ViewController: UIScrollViewDelegate {
func scrollViewDidScroll(_ scrollView: UIScrollView) {
cvParallex.visibleCells.forEach { (bannerCell) in
handleEffect(cell: bannerCell as! ItemPic)
}
}
private func handleEffect(cell: ItemPic){
let minusX = cvParallex.contentOffset.x - cell.frame.origin.x
let imageOffsetX = (-minusX) * 0.5;
cell.scrollView.contentOffset = CGPoint(x: imageOffsetX, y: 0)
}
}
extension ViewController: UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: UIScreen.main.bounds.size.width, height: 200)
}
}
| mit | 46d364604f556ddc25e30a86d68af54e | 33.534483 | 182 | 0.705442 | 4.604598 | false | false | false | false |
lightningkite/LKAPI | Example/Tests/StringTests.swift | 1 | 2688 | //
// StringTests.swift
// LKAPI
//
// Created by Erik Sargent on 5/17/17.
// Copyright © 2017 CocoaPods. All rights reserved.
//
import XCTest
class StringTests: XCTestCase {
let camel = "thisIsWonderfulCamelCase"
let snakedCamel = "this_is_wonderful_camel_case"
let numberCamel = "thisAnd34Numbers"
let snakedNumberCamel = "this_and_34_numbers"
let SuperCamel = "ThisIsWonderfulCamelCase"
let snakedSuperCamel = "this_is_wonderful_camel_case"
let numberSnake = "this_is_34_and_some"
let cameledNumberSnake = "thisIs34AndSome"
let snake = "this_is_horrible_snake_case"
let cameledSnake = "thisIsHorribleSnakeCase"
let capitalSnake = "This_Is_Horrible_Snake_Case"
let cameledCapitalSnake = "ThisIsHorribleSnakeCase"
let spaced = "this is what we are used to"
let blank = ""
let emoji = "😀_😃"
let cameledEmoji = "😀😃"
let kata = "カ_ヌ"
let cameledKata = "カヌ"
let accented = "résumé"
let date = "2017-04-03"
let dateTime = "2017-5-4T02:40:90"
let dateTimeZ = "2017-5-4T02:40:90Z"
let dateTimeZone = "2017-5-4T02:40:90-0700"
let dateGarbage = "2017-5-4stuff"
let dateTimeGarbage = "2017-5-4T02:40:90Stuff"
func testToCamel() {
XCTAssertEqual(camel.toCamel, camel)
XCTAssertEqual(SuperCamel.toCamel, SuperCamel)
XCTAssertEqual(snake.toCamel, cameledSnake)
XCTAssertEqual(capitalSnake.toCamel, cameledCapitalSnake)
XCTAssertEqual(spaced.toCamel, spaced)
XCTAssertEqual(blank.toCamel, blank)
XCTAssertEqual(emoji.toCamel, cameledEmoji)
XCTAssertEqual(kata.toCamel, cameledKata)
XCTAssertEqual(accented.toCamel, accented)
XCTAssertEqual(numberSnake.toCamel, cameledNumberSnake)
}
func testToSnake() {
XCTAssertEqual(camel.toSnake, snakedCamel)
XCTAssertEqual(SuperCamel.toSnake, snakedSuperCamel)
XCTAssertEqual(snake.toSnake, snake)
XCTAssertEqual(capitalSnake.toSnake, capitalSnake.lowercased())
XCTAssertEqual(spaced.toSnake, spaced)
XCTAssertEqual(blank.toSnake, blank)
XCTAssertEqual(emoji.toSnake, emoji)
XCTAssertEqual(kata.toSnake, kata)
XCTAssertEqual(accented.toSnake, accented)
XCTAssertEqual(numberCamel.toSnake, snakedNumberCamel)
}
func testIsDate() {
XCTAssertTrue(date.isDate)
XCTAssertFalse(dateTime.isDate)
XCTAssertFalse(dateTimeZ.isDate)
XCTAssertFalse(dateTimeZone.isDate)
XCTAssertFalse(dateGarbage.isDate)
XCTAssertFalse(dateTimeGarbage.isDate)
}
func testIsDateTime() {
XCTAssertFalse(date.isDateTime)
XCTAssertTrue(dateTime.isDateTime)
XCTAssertTrue(dateTimeZ.isDateTime)
XCTAssertTrue(dateTimeZone.isDateTime)
XCTAssertFalse(dateGarbage.isDateTime)
XCTAssertFalse(dateTimeGarbage.isDateTime)
}
}
| mit | 40d128cef0fa40752850d0e93f70dd31 | 28.611111 | 65 | 0.760225 | 3.218599 | false | true | false | false |
badoo/FreehandDrawing-iOS | FreehandDrawing-iOS/FreehandDrawController.swift | 1 | 3775 | //
// FreehandDrawController.swift
// FreehandDrawing-iOS
//
// Created by Miguel Angel Quinones on 03/06/2015.
// Copyright (c) 2015 badoo. All rights reserved.
//
import UIKit
class FreehandDrawController : NSObject {
var color: UIColor = UIColor.blackColor()
var width: CGFloat = 5.0
required init(canvas: protocol<Canvas, DrawCommandReceiver>, view: UIView) {
self.canvas = canvas
super.init()
self.setupGestureRecognizersInView(view)
}
// MARK: API
func undo() {
if self.commandQueue.count > 0{
self.commandQueue.removeLast()
self.canvas.reset()
self.canvas.executeCommands(self.commandQueue)
}
}
// MARK: Gestures
private func setupGestureRecognizersInView(view: UIView) {
// Pan gesture recognizer to track lines
let panRecognizer = UIPanGestureRecognizer(target: self, action: "handlePan:")
view.addGestureRecognizer(panRecognizer)
// Tap gesture recognizer to track points
let tapRecognizer = UITapGestureRecognizer(target: self, action: "handleTap:")
view.addGestureRecognizer(tapRecognizer)
}
@objc private func handlePan(sender: UIPanGestureRecognizer) {
let point = sender.locationInView(sender.view)
switch sender.state {
case .Began:
self.startAtPoint(point)
case .Changed:
self.continueAtPoint(point, velocity: sender.velocityInView(sender.view))
case .Ended:
self.endAtPoint(point)
case .Failed:
self.endAtPoint(point)
default:
assert(false, "State not handled")
}
}
@objc private func handleTap(sender: UITapGestureRecognizer) {
let point = sender.locationInView(sender.view)
if sender.state == .Ended {
self.tapAtPoint(point)
}
}
// MARK: Draw commands
private func startAtPoint(point: CGPoint) {
self.lastPoint = point
self.lineStrokeCommand = ComposedCommand(commands: [])
}
private func continueAtPoint(point: CGPoint, velocity: CGPoint) {
let segmentWidth = modulatedWidth(self.width, velocity, self.lastVelocity, self.lastWidth ?? self.width)
let segment = Segment(a: self.lastPoint, b: point, width: segmentWidth)
let lineCommand = LineDrawCommand(current: segment, previous: lastSegment, width: segmentWidth, color: self.color)
self.canvas.executeCommands([lineCommand])
self.lineStrokeCommand?.addCommand(lineCommand)
self.lastPoint = point
self.lastSegment = segment
self.lastVelocity = velocity
self.lastWidth = segmentWidth
}
private func endAtPoint(point: CGPoint) {
if let lineStrokeCommand = self.lineStrokeCommand {
self.commandQueue.append(lineStrokeCommand)
}
self.lastPoint = CGPointZero
self.lastSegment = nil
self.lastVelocity = CGPointZero
self.lastWidth = nil
self.lineStrokeCommand = nil
}
private func tapAtPoint(point: CGPoint) {
let circleCommand = CircleDrawCommand(center: point, radius: self.width/2.0, color: self.color)
self.canvas.executeCommands([circleCommand])
self.commandQueue.append(circleCommand)
}
private let canvas: protocol<Canvas, DrawCommandReceiver>
private var lineStrokeCommand: ComposedCommand?
private var commandQueue: Array<DrawCommand> = []
private var lastPoint: CGPoint = CGPointZero
private var lastSegment: Segment?
private var lastVelocity: CGPoint = CGPointZero
private var lastWidth: CGFloat?
}
| mit | 480a69f10638a771dc19b0ed842658a6 | 32.114035 | 122 | 0.646623 | 4.71875 | false | false | false | false |
vokal-isaac/Vokoder | SwiftSampleProject/SwiftyVokoder/Models/Stop.swift | 1 | 2989 | //
// Stop.swift
// SwiftyVokoder
//
// Created by Carl Hill-Popper on 11/13/15.
// Copyright © 2015 Vokal.
//
import Foundation
import CoreData
import Vokoder
//lets pretend we're using mogenerator to create attribute constants
enum StopAttributes: String {
case directionString
case identifier
case name
}
@objc(Stop)
class Stop: NSManagedObject {
enum Direction: String {
case North = "N"
case South = "S"
case East = "E"
case West = "W"
case Unknown
init(value: String?) {
if let
value = value,
knownDirection = Direction(rawValue: value) {
self = knownDirection
} else {
self = .Unknown
}
}
}
lazy private(set) var direction: Direction = {
Direction(value: self.directionString)
}()
}
extension Stop: VOKMappableModel {
/*
Example JSON input:
{
"STOP_ID":30096,
"DIRECTION_ID":"S",
"STOP_NAME":"Grand/Milwaukee (Forest Pk-bound)",
"STATION_NAME":"Grand",
"STATION_DESCRIPTIVE_NAME":"Grand (Blue Line)",
"MAP_ID":40490,
"ADA":false,
"RED":false,
"BLUE":true,
"G":false,
"BRN":false,
"P":false,
"Pexp":false,
"Y":false,
"Pnk":false,
"O":false,
"Location":"(41.891189, -87.647578)"
},
*/
static func coreDataMaps() -> [VOKManagedObjectMap] {
return [
VOKManagedObjectMap(foreignKeyPath: "STOP_ID",
coreDataKeyEnum: StopAttributes.identifier),
VOKManagedObjectMap(foreignKeyPath: "STOP_NAME",
coreDataKeyEnum: StopAttributes.name),
VOKManagedObjectMap(foreignKeyPath: "DIRECTION_ID",
coreDataKeyEnum: StopAttributes.directionString),
]
}
static func uniqueKey() -> String? {
return StopAttributes.identifier.rawValue
}
static func importCompletionBlock() -> VOKPostImportBlock {
//explicit typing for clarity
return { (inputDict: [String: AnyObject], inputObject: NSManagedObject) in
guard let stop = inputObject as? Stop else {
return
}
//NOTE: the input JSON is denormalized so we can pass in the inputDict to create stations
stop.station = Station.vok_addWithDictionary(inputDict,
forManagedObjectContext: stop.managedObjectContext)
//train lines are mapped manually because CTA data is strange
stop.trainLine = TrainLine.trainLineFromStopDictionary(inputDict,
forManagedObjectContext: stop.managedObjectContext)
}
}
}
//MARK: VokoderTypedManagedObject
//the empty protocol implementation is used to mixin the functionality of VokoderTypedManagedObject
extension Stop: VokoderTypedManagedObject { }
| mit | 07aa89b0596eca2f72cf406301fc9099 | 27.730769 | 101 | 0.588019 | 4.413589 | false | false | false | false |
mrgerych/Cuckoo | Generator/Source/CuckooGeneratorFramework/Tokens/Import.swift | 2 | 444 | //
// Import.swift
// CuckooGenerator
//
// Created by Filip Dolnik on 17.06.16.
// Copyright © 2016 Brightify. All rights reserved.
//
public struct Import: Token {
public let range: CountableRange<Int>
public let library: String
public func isEqual(to other: Token) -> Bool {
guard let other = other as? Import else { return false }
return self.range == other.range && self.library == other.library
}
}
| mit | 2feeea022c5648890511080affc949d4 | 25.058824 | 73 | 0.656885 | 3.920354 | false | false | false | false |
karivalkama/Agricola-Scripture-Editor | TranslationEditor/UserCell.swift | 1 | 1699 | //
// UserCell.swift
// TranslationEditor
//
// Created by Mikko Hilpinen on 6.6.2017.
// Copyright © 2017 SIL. All rights reserved.
//
import UIKit
class UserCell: UITableViewCell
{
// OUTLETS ---------------------
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var createdLabel: UILabel!
@IBOutlet weak var isAdminSwitch: UISwitch!
@IBOutlet weak var clearPasswordButton: BasicButton!
@IBOutlet weak var deleteButton: BasicButton!
// ATTRIBUTES -----------------
static let identifier = "UserCell"
private var setAdminAction: ((UITableViewCell, Bool) -> ())?
private var passwordAction: ((UITableViewCell) -> ())?
private var deleteAction: ((UITableViewCell) -> ())?
// ACTIONS ---------------------
@IBAction func adminValueChanged(_ sender: Any)
{
setAdminAction?(self, isAdminSwitch.isOn)
}
@IBAction func clearPasswordPressed(_ sender: Any)
{
passwordAction?(self)
}
@IBAction func deletePressed(_ sender: Any)
{
deleteAction?(self)
}
// OTHER METHODS -------------
func configure(name: String, created: Date, isAdmin: Bool, hasPassword: Bool, deleteEnabled: Bool, setAdminAction: @escaping (UITableViewCell, Bool) -> (), clearPasswordAction: @escaping (UITableViewCell) -> (), deleteAction: @escaping (UITableViewCell) -> ())
{
self.passwordAction = clearPasswordAction
self.deleteAction = deleteAction
self.setAdminAction = setAdminAction
nameLabel.text = name
isAdminSwitch.isOn = isAdmin
clearPasswordButton.isEnabled = hasPassword
deleteButton.isEnabled = deleteEnabled
let formatter = DateFormatter()
formatter.dateStyle = .medium
createdLabel.text = formatter.string(from: created)
}
}
| mit | 04a547506bc62422c3748b0e97ff3bfc | 24.343284 | 261 | 0.693168 | 3.985915 | false | false | false | false |
twtstudio/WePeiYang-iOS | WePeiYang/Library/Model/LibraryDataManager.swift | 1 | 3743 | //
// LibraryDataManager.swift
// WePeiYang
//
// Created by Qin Yubo on 16/4/20.
// Copyright © 2016年 Qin Yubo. All rights reserved.
//
import UIKit
import ObjectMapper
import SwiftyJSON
import FMDB
let LIBRARY_FAVORITE_DB_NAME = "fav.db"
class LibraryDataManager: NSObject {
class func searchLibrary(keyword: String, page: Int, success: (data: [LibraryDataItem]) -> (), failure: (errorMsg: String) -> ()) {
twtSDK.getLibrarySearchResultWithTitle(keyword, page: page, success: { (task, responseObject) in
let jsonData = JSON(responseObject)
if jsonData["error_code"].intValue == -1 {
if let data = Mapper<LibraryDataItem>().mapArray(jsonData["data"].arrayObject) {
success(data: data)
}
}
}, failure: { (task, error) in
failure(errorMsg: error.localizedDescription)
})
}
class func addLibraryItemToFavorite(item: LibraryDataItem) {
let documents = try! NSFileManager.defaultManager().URLForDirectory(.DocumentDirectory, inDomain: .UserDomainMask, appropriateForURL: nil, create: false)
let fileURL = documents.URLByAppendingPathComponent(LIBRARY_FAVORITE_DB_NAME)
let database = FMDatabase(path: fileURL!.path)
if !database.open() {
return
}
do {
try database.executeUpdate("CREATE TABLE Libfav(id, title, author, publisher, location)", values: nil)
} catch let error as NSError {
print("Failed: \(error.localizedDescription)")
}
do {
try database.executeUpdate("INSERT INTO Libfav VALUES(?, ?, ?, ?, ?)", values: [item.index, item.title, item.author, item.publisher, item.location])
} catch let error as NSError {
print("Failed: \(error.localizedDescription)")
}
database.close()
}
class func favoriteLibraryItems() -> [LibraryDataItem] {
let documents = try! NSFileManager.defaultManager().URLForDirectory(.DocumentDirectory, inDomain: .UserDomainMask, appropriateForURL: nil, create: false)
let fileURL = documents.URLByAppendingPathComponent(LIBRARY_FAVORITE_DB_NAME)
let database = FMDatabase(path: fileURL!.path)
if !database.open() {
return []
}
var dataArr: [LibraryDataItem] = []
do {
let result = try database.executeQuery("SELECT * FROM Libfav", values: nil)
while result.next() {
let item = LibraryDataItem(index: result.stringForColumn("id"), title: result.stringForColumn("title"), author: result.stringForColumn("author"), publisher: result.stringForColumn("publisher"), location: result.stringForColumn("location"))
dataArr.append(item)
}
} catch let error as NSError {
print("Failed: \(error.localizedDescription)")
}
database.close()
return dataArr
}
class func removeLibraryItem(item: LibraryDataItem) {
let documents = try! NSFileManager.defaultManager().URLForDirectory(.DocumentDirectory, inDomain: .UserDomainMask, appropriateForURL: nil, create: false)
let fileURL = documents.URLByAppendingPathComponent(LIBRARY_FAVORITE_DB_NAME)
let database = FMDatabase(path: fileURL!.path)
if !database.open() {
return
}
do {
try database.executeUpdate("DELETE FROM Libfav WHERE id=?", values: [item.index])
} catch let error as NSError {
print("Failed: \(error.localizedDescription)")
}
database.close()
}
}
| mit | 9947c0a528a7c2fc2002dcb9145074d8 | 37.556701 | 255 | 0.615241 | 4.838292 | false | false | false | false |
modocache/Gift | Gift/Repository/Options/Initialization/RepositoryInitializationMode.swift | 1 | 480 | /**
File mode options for the files created when initializing a repository.
*/
public enum RepositoryInitializationMode: UInt32 {
/** Permissions used by umask--the default. */
case User = 0
/**
Emulates the permissions used by `git clone --shared=group`.
The repository is made group-writeable.
*/
case Group = 0002775
/**
Emulates the permissions used by `git clone --shared=all`.
The repository is made world-readable.
*/
case All = 0002777
}
| mit | dd5374829bb02605e05c678138306e92 | 27.235294 | 73 | 0.691667 | 4.137931 | false | false | false | false |
loretoparisi/ios-json-benchmark | JSONlibs/ObjectMapper/Core/Mapper.swift | 1 | 14156 | //
// Mapper.swift
// ObjectMapper
//
// Created by Tristan Himmelman on 2014-10-09.
//
// The MIT License (MIT)
//
// Copyright (c) 2014-2015 Hearst
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import class Foundation.NSString;
import var Foundation.NSUTF8StringEncoding;
import class Foundation.NSJSONSerialization;
import struct Foundation.NSJSONReadingOptions;
import struct Foundation.NSJSONWritingOptions;
import class Foundation.NSData;
public enum MappingType {
case FromJSON
case ToJSON
}
/// The Mapper class provides methods for converting Model objects to JSON and methods for converting JSON to Model objects
public final class Mapper<N: Mappable> {
public init(){}
// MARK: Mapping functions that map to an existing object toObject
/// Maps a JSON object to an existing Mappable object if it is a JSON dictionary, or returns the passed object as is
public func map(JSON: AnyObject?, toObject object: N) -> N {
if let JSON = JSON as? [String : AnyObject] {
return map(JSON, toObject: object)
}
return object
}
/// Map a JSON string onto an existing object
public func map(JSONString: String, toObject object: N) -> N {
if let JSON = Mapper.parseJSONDictionary(JSONString) {
return map(JSON, toObject: object)
}
return object
}
/// Maps a JSON dictionary to an existing object that conforms to Mappable.
/// Usefull for those pesky objects that have crappy designated initializers like NSManagedObject
public func map(JSONDictionary: [String : AnyObject], var toObject object: N) -> N {
let map = Map(mappingType: .FromJSON, JSONDictionary: JSONDictionary, toObject: true)
object.mapping(map)
return object
}
//MARK: Mapping functions that create an object
/// Map an optional JSON string to an object that conforms to Mappable
public func map(JSONString: String?) -> N? {
if let JSONString = JSONString {
return map(JSONString)
}
return nil
}
/// Map a JSON string to an object that conforms to Mappable
public func map(JSONString: String) -> N? {
if let JSON = Mapper.parseJSONDictionary(JSONString) {
return map(JSON)
}
return nil
}
/// Map a JSON NSString to an object that conforms to Mappable
public func map(JSONString: NSString) -> N? {
return map(JSONString as String)
}
/// Maps a JSON object to a Mappable object if it is a JSON dictionary or NSString, or returns nil.
public func map(JSON: AnyObject?) -> N? {
if let JSON = JSON as? [String : AnyObject] {
return map(JSON)
}
return nil
}
/// Maps a JSON dictionary to an object that conforms to Mappable
public func map(JSONDictionary: [String : AnyObject]) -> N? {
let map = Map(mappingType: .FromJSON, JSONDictionary: JSONDictionary)
// check if N is of type MappableCluster
if let klass = N.self as? MappableCluster.Type {
if var object = klass.objectForMapping(map) as? N {
object.mapping(map)
return object
}
}
if var object = N(map) {
object.mapping(map)
return object
}
return nil
}
// MARK: Mapping functions for Arrays and Dictionaries
/// Maps a JSON array to an object that conforms to Mappable
public func mapArray(JSONString: String) -> [N]? {
let parsedJSON: AnyObject? = Mapper.parseJSONString(JSONString)
if let objectArray = mapArray(parsedJSON) {
return objectArray
}
// failed to parse JSON into array form
// try to parse it into a dictionary and then wrap it in an array
if let object = map(parsedJSON) {
return [object]
}
return nil
}
/// Maps a optional JSON String into an array of objects that conforms to Mappable
public func mapArray(JSONString: String?) -> [N]? {
if let JSONString = JSONString {
return mapArray(JSONString)
}
return nil
}
/// Maps a JSON object to an array of Mappable objects if it is an array of JSON dictionary, or returns nil.
public func mapArray(JSON: AnyObject?) -> [N]? {
if let JSONArray = JSON as? [[String : AnyObject]] {
return mapArray(JSONArray)
}
return nil
}
/// Maps an array of JSON dictionary to an array of Mappable objects
public func mapArray(JSONArray: [[String : AnyObject]]) -> [N]? {
// map every element in JSON array to type N
let result = JSONArray.flatMap(map)
return result
}
/// Maps a JSON object to a dictionary of Mappable objects if it is a JSON dictionary of dictionaries, or returns nil.
public func mapDictionary(JSONString: String) -> [String : N]? {
let parsedJSON: AnyObject? = Mapper.parseJSONString(JSONString)
return mapDictionary(parsedJSON)
}
/// Maps a JSON object to a dictionary of Mappable objects if it is a JSON dictionary of dictionaries, or returns nil.
public func mapDictionary(JSON: AnyObject?) -> [String : N]? {
if let JSONDictionary = JSON as? [String : [String : AnyObject]] {
return mapDictionary(JSONDictionary)
}
return nil
}
/// Maps a JSON dictionary of dictionaries to a dictionary of Mappble objects
public func mapDictionary(JSONDictionary: [String : [String : AnyObject]]) -> [String : N]? {
// map every value in dictionary to type N
let result = JSONDictionary.filterMap(map)
if result.isEmpty == false {
return result
}
return nil
}
/// Maps a JSON object to a dictionary of Mappable objects if it is a JSON dictionary of dictionaries, or returns nil.
public func mapDictionary(JSON: AnyObject?, toDictionary dictionary: [String : N]) -> [String : N] {
if let JSONDictionary = JSON as? [String : [String : AnyObject]] {
return mapDictionary(JSONDictionary, toDictionary: dictionary)
}
return dictionary
}
/// Maps a JSON dictionary of dictionaries to an existing dictionary of Mappble objects
public func mapDictionary(JSONDictionary: [String : [String : AnyObject]], var toDictionary dictionary: [String : N]) -> [String : N] {
for (key, value) in JSONDictionary {
if let object = dictionary[key] {
Mapper().map(value, toObject: object)
} else {
dictionary[key] = Mapper().map(value)
}
}
return dictionary
}
/// Maps a JSON object to a dictionary of arrays of Mappable objects
public func mapDictionaryOfArrays(JSON: AnyObject?) -> [String : [N]]? {
if let JSONDictionary = JSON as? [String : [[String : AnyObject]]] {
return mapDictionaryOfArrays(JSONDictionary)
}
return nil
}
///Maps a JSON dictionary of arrays to a dictionary of arrays of Mappable objects
public func mapDictionaryOfArrays(JSONDictionary: [String : [[String : AnyObject]]]) -> [String : [N]]? {
// map every value in dictionary to type N
let result = JSONDictionary.filterMap {
mapArray($0)
}
if result.isEmpty == false {
return result
}
return nil
}
/// Maps an 2 dimentional array of JSON dictionaries to a 2 dimentional array of Mappable objects
public func mapArrayOfArrays(JSON: AnyObject?) -> [[N]]? {
if let JSONArray = JSON as? [[[String : AnyObject]]] {
var objectArray = [[N]]()
for innerJSONArray in JSONArray {
if let array = mapArray(innerJSONArray){
objectArray.append(array)
}
}
if objectArray.isEmpty == false {
return objectArray
}
}
return nil
}
// MARK: Utility functions for converting strings to JSON objects
/// Convert a JSON String into a Dictionary<String, AnyObject> using NSJSONSerialization
public static func parseJSONDictionary(JSON: String) -> [String : AnyObject]? {
let parsedJSON: AnyObject? = Mapper.parseJSONString(JSON)
return Mapper.parseJSONDictionary(parsedJSON)
}
/// Convert a JSON Object into a Dictionary<String, AnyObject> using NSJSONSerialization
public static func parseJSONDictionary(JSON: AnyObject?) -> [String : AnyObject]? {
if let JSONDict = JSON as? [String : AnyObject] {
return JSONDict
}
return nil
}
/// Convert a JSON String into an Object using NSJSONSerialization
public static func parseJSONString(JSON: String) -> AnyObject? {
let data = JSON.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)
if let data = data {
let parsedJSON: AnyObject?
do {
parsedJSON = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments)
} catch let error {
print(error)
parsedJSON = nil
}
return parsedJSON
}
return nil
}
}
extension Mapper {
// MARK: Functions that create JSON from objects
///Maps an object that conforms to Mappable to a JSON dictionary <String : AnyObject>
public func toJSON(var object: N) -> [String : AnyObject] {
let map = Map(mappingType: .ToJSON, JSONDictionary: [:])
object.mapping(map)
return map.JSONDictionary
}
///Maps an array of Objects to an array of JSON dictionaries [[String : AnyObject]]
public func toJSONArray(array: [N]) -> [[String : AnyObject]] {
return array.map {
// convert every element in array to JSON dictionary equivalent
self.toJSON($0)
}
}
///Maps a dictionary of Objects that conform to Mappable to a JSON dictionary of dictionaries.
public func toJSONDictionary(dictionary: [String : N]) -> [String : [String : AnyObject]] {
return dictionary.map { k, v in
// convert every value in dictionary to its JSON dictionary equivalent
return (k, self.toJSON(v))
}
}
///Maps a dictionary of Objects that conform to Mappable to a JSON dictionary of dictionaries.
public func toJSONDictionaryOfArrays(dictionary: [String : [N]]) -> [String : [[String : AnyObject]]] {
return dictionary.map { k, v in
// convert every value (array) in dictionary to its JSON dictionary equivalent
return (k, self.toJSONArray(v))
}
}
/// Maps an Object to a JSON string with option of pretty formatting
public func toJSONString(object: N, prettyPrint: Bool = false) -> String? {
let JSONDict = toJSON(object)
return Mapper.toJSONString(JSONDict, prettyPrint: prettyPrint)
}
/// Maps an array of Objects to a JSON string with option of pretty formatting
public func toJSONString(array: [N], prettyPrint: Bool = false) -> String? {
let JSONDict = toJSONArray(array)
return Mapper.toJSONString(JSONDict, prettyPrint: prettyPrint)
}
public static func toJSONString(JSONObject: AnyObject, prettyPrint: Bool) -> String? {
if NSJSONSerialization.isValidJSONObject(JSONObject) {
let JSONData: NSData?
do {
let options: NSJSONWritingOptions = prettyPrint ? .PrettyPrinted : []
JSONData = try NSJSONSerialization.dataWithJSONObject(JSONObject, options: options)
} catch let error {
print(error)
JSONData = nil
}
if let JSON = JSONData {
return String(data: JSON, encoding: NSUTF8StringEncoding)
}
}
return nil
}
}
extension Mapper where N: Hashable {
/// Maps a JSON array to an object that conforms to Mappable
public func mapSet(JSONString: String) -> Set<N>? {
let parsedJSON: AnyObject? = Mapper.parseJSONString(JSONString)
if let objectArray = mapArray(parsedJSON){
return Set(objectArray)
}
// failed to parse JSON into array form
// try to parse it into a dictionary and then wrap it in an array
if let object = map(parsedJSON) {
return Set([object])
}
return nil
}
/// Maps a JSON object to an Set of Mappable objects if it is an array of JSON dictionary, or returns nil.
public func mapSet(JSON: AnyObject?) -> Set<N>? {
if let JSONArray = JSON as? [[String : AnyObject]] {
return mapSet(JSONArray)
}
return nil
}
/// Maps an Set of JSON dictionary to an array of Mappable objects
public func mapSet(JSONArray: [[String : AnyObject]]) -> Set<N> {
// map every element in JSON array to type N
return Set(JSONArray.flatMap(map))
}
///Maps a Set of Objects to a Set of JSON dictionaries [[String : AnyObject]]
public func toJSONSet(set: Set<N>) -> [[String : AnyObject]] {
return set.map {
// convert every element in set to JSON dictionary equivalent
self.toJSON($0)
}
}
/// Maps a set of Objects to a JSON string with option of pretty formatting
public func toJSONString(set: Set<N>, prettyPrint: Bool = false) -> String? {
let JSONDict = toJSONSet(set)
return Mapper.toJSONString(JSONDict, prettyPrint: prettyPrint)
}
}
extension Dictionary {
internal func map<K: Hashable, V>(@noescape f: Element -> (K, V)) -> [K : V] {
var mapped = [K : V]()
for element in self {
let newElement = f(element)
mapped[newElement.0] = newElement.1
}
return mapped
}
internal func map<K: Hashable, V>(@noescape f: Element -> (K, [V])) -> [K : [V]] {
var mapped = [K : [V]]()
for element in self {
let newElement = f(element)
mapped[newElement.0] = newElement.1
}
return mapped
}
internal func filterMap<U>(@noescape f: Value -> U?) -> [Key : U] {
var mapped = [Key : U]()
for (key, value) in self {
if let newValue = f(value){
mapped[key] = newValue
}
}
return mapped
}
}
| mit | c66b305f8f2eedc1d11739ee578dcb25 | 30.668904 | 139 | 0.689884 | 4.025021 | false | false | false | false |
fredfoc/OpenWit | OpenWit/Classes/OpenWitConverseModel.swift | 1 | 1829 | //
// OpenWitConverseModel.swift
// OpenWit
//
// Created by fauquette fred on 8/12/16.
// Copyright © 2016 Fred Fauquette. All rights reserved.
//
import Foundation
import ObjectMapper
public enum OpenWitConverseType: String {
case unknwon = "unknwon"
case msg = "msg"
case merge = "merge"
case action = "action"
case stop = "stop"
}
/// A Model to handle Wit Message Response
public struct OpenWitConverseModel: Mappable, EntitiesCompatible{
public fileprivate(set) var type = OpenWitConverseType.unknwon
public fileprivate(set) var confidence: Float?
public fileprivate(set) var jsonEntities: [String: Any]?
fileprivate var map: Map
public init?(map: Map) {
self.map = map
}
mutating public func mapping(map: Map) {
self.map = map
type <- map[OpenWitJsonKey.type.rawValue]
confidence <- map[OpenWitJsonKey.confidence.rawValue]
jsonEntities = map.JSON[OpenWitJsonKey.entities.rawValue] as? [String: Any]
}
}
extension OpenWitConverseModel {
public var msg: String? {
return try? map.value(OpenWitConverseType.msg.rawValue)
}
public var action: String? {
return try? map.value(OpenWitConverseType.action.rawValue)
}
public var quickreplies: [String]? {
return try? map.value(OpenWitJsonKey.quickreplies.rawValue)
}
}
extension OpenWitConverseModel: CustomStringConvertible {
public var description: String {
return
"type: " + type.rawValue
+ "\naction: "
+ (action ?? "no action")
+ "\nentities: "
+ (jsonEntities?.description ?? "no entities")
+ "\nquickreplies: "
+ (quickreplies?.description ?? "no quickreply")
}
}
| mit | ba47251ab6bfed578cb30ae567cddc53 | 27.123077 | 83 | 0.627462 | 3.95671 | false | false | false | false |
dreamsxin/swift | stdlib/public/core/Unicode.swift | 1 | 45268 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import SwiftShims
// Conversions between different Unicode encodings. Note that UTF-16 and
// UTF-32 decoding are *not* currently resilient to erroneous data.
/// The result of one Unicode decoding step.
///
/// Each `UnicodeDecodingResult` instance can represent a Unicode scalar value,
/// an indication that no more Unicode scalars are available, or an indication
/// of a decoding error.
///
/// - SeeAlso: `UnicodeCodec.decode(next:)`
public enum UnicodeDecodingResult : Equatable {
/// A decoded Unicode scalar value.
case scalarValue(UnicodeScalar)
/// An indication that no more Unicode scalars are available in the input.
case emptyInput
/// An indication of a decoding error.
case error
}
public func == (
lhs: UnicodeDecodingResult,
rhs: UnicodeDecodingResult
) -> Bool {
switch (lhs, rhs) {
case (.scalarValue(let lhsScalar), .scalarValue(let rhsScalar)):
return lhsScalar == rhsScalar
case (.emptyInput, .emptyInput):
return true
case (.error, .error):
return true
default:
return false
}
}
/// A Unicode encoding form that translates between Unicode scalar values and
/// form-specific code units.
///
/// The `UnicodeCodec` protocol declares methods that decode code unit
/// sequences into Unicode scalar values and encode Unicode scalar values
/// into code unit sequences. The standard library implements codecs for the
/// UTF-8, UTF-16, and UTF-32 encoding schemes as the `UTF8`, `UTF16`, and
/// `UTF32` types, respectively. Use the `UnicodeScalar` type to work with
/// decoded Unicode scalar values.
///
/// - SeeAlso: `UTF8`, `UTF16`, `UTF32`, `UnicodeScalar`
public protocol UnicodeCodec {
/// A type that can hold code unit values for this encoding.
associatedtype CodeUnit
/// Creates an instance of the codec.
init()
/// Starts or continues decoding a code unit sequence into Unicode scalar
/// values.
///
/// To decode a code unit sequence completely, call this method repeatedly
/// until it returns `UnicodeDecodingResult.emptyInput`. Checking that the
/// iterator was exhausted is not sufficient, because the decoder can store
/// buffered data from the input iterator.
///
/// Because of buffering, it is impossible to find the corresponding position
/// in the iterator for a given returned `UnicodeScalar` or an error.
///
/// The following example decodes the UTF-8 encoded bytes of a string into an
/// array of `UnicodeScalar` instances:
///
/// let str = "✨Unicode✨"
/// print(Array(str.utf8))
/// // Prints "[226, 156, 168, 85, 110, 105, 99, 111, 100, 101, 226, 156, 168]"
///
/// var bytesIterator = str.utf8.makeIterator()
/// var scalars: [UnicodeScalar] = []
/// var utf8Decoder = UTF8()
/// Decode: while true {
/// switch utf8Decoder.decode(&bytesIterator) {
/// case .scalarValue(let v): scalars.append(v)
/// case .emptyInput: break Decode
/// case .error:
/// print("Decoding error")
/// break Decode
/// }
/// }
/// print(scalars)
/// // Prints "["\u{2728}", "U", "n", "i", "c", "o", "d", "e", "\u{2728}"]"
///
/// - Parameter next: An iterator of code units to be decoded. `next` must be
/// the same iterator instance in repeated calls to this method. Do not
/// advance the iterator or any copies of the iterator outside this
/// method.
/// - Returns: A `UnicodeDecodingResult` instance, representing the next
/// Unicode scalar, an indication of an error, or an indication that the
/// UTF sequence has been fully decoded.
mutating func decode<I : IteratorProtocol>(
_ next: inout I
) -> UnicodeDecodingResult where I.Element == CodeUnit
/// Encodes a Unicode scalar as a series of code units by calling the given
/// closure on each code unit.
///
/// For example, the musical fermata symbol ("𝄐") is a single Unicode scalar
/// value (`\u{1D110}`) but requires four code units for its UTF-8
/// representation. The following code uses the `UTF8` codec to encode a
/// fermata in UTF-8:
///
/// var bytes: [UTF8.CodeUnit] = []
/// UTF8.encode("𝄐", sendingOutputTo: { bytes.append($0) })
/// print(bytes)
/// // Prints "[240, 157, 132, 144]"
///
/// - Parameters:
/// - input: The Unicode scalar value to encode.
/// - processCodeUnit: A closure that processes one code unit argument at a
/// time.
static func encode(
_ input: UnicodeScalar,
sendingOutputTo processCodeUnit: @noescape (CodeUnit) -> Void
)
/// Searches for the first occurrence of a `CodeUnit` that is equal to 0.
///
/// Is an equivalent of `strlen` for C-strings.
/// - Complexity: O(n)
static func _nullCodeUnitOffset(in input: UnsafePointer<CodeUnit>) -> Int
}
/// A codec for translating between Unicode scalar values and UTF-8 code
/// units.
public struct UTF8 : UnicodeCodec {
// See Unicode 8.0.0, Ch 3.9, UTF-8.
// http://www.unicode.org/versions/Unicode8.0.0/ch03.pdf
/// A type that can hold code unit values for this encoding.
public typealias CodeUnit = UInt8
/// Creates an instance of the UTF-8 codec.
public init() {}
/// Lookahead buffer used for UTF-8 decoding. New bytes are inserted at MSB,
/// and bytes are read at LSB. Note that we need to use a buffer, because
/// in case of invalid subsequences we sometimes don't know whether we should
/// consume a certain byte before looking at it.
internal var _decodeBuffer: UInt32 = 0
/// The number of bits in `_decodeBuffer` that are current filled.
internal var _bitsInBuffer: UInt8 = 0
/// Whether we have exhausted the iterator. Note that this doesn't mean
/// we are done decoding, as there might still be bytes left in the buffer.
internal var _didExhaustIterator: Bool = false
/// Starts or continues decoding a UTF-8 sequence.
///
/// To decode a code unit sequence completely, call this method repeatedly
/// until it returns `UnicodeDecodingResult.emptyInput`. Checking that the
/// iterator was exhausted is not sufficient, because the decoder can store
/// buffered data from the input iterator.
///
/// Because of buffering, it is impossible to find the corresponding position
/// in the iterator for a given returned `UnicodeScalar` or an error.
///
/// The following example decodes the UTF-8 encoded bytes of a string into an
/// array of `UnicodeScalar` instances. This is a demonstration only---if
/// you need the Unicode scalar representation of a string, use its
/// `unicodeScalars` view.
///
/// let str = "✨Unicode✨"
/// print(Array(str.utf8))
/// // Prints "[226, 156, 168, 85, 110, 105, 99, 111, 100, 101, 226, 156, 168]"
///
/// var bytesIterator = str.utf8.makeIterator()
/// var scalars: [UnicodeScalar] = []
/// var utf8Decoder = UTF8()
/// Decode: while true {
/// switch utf8Decoder.decode(&bytesIterator) {
/// case .scalarValue(let v): scalars.append(v)
/// case .emptyInput: break Decode
/// case .error:
/// print("Decoding error")
/// break Decode
/// }
/// }
/// print(scalars)
/// // Prints "["\u{2728}", "U", "n", "i", "c", "o", "d", "e", "\u{2728}"]"
///
/// - Parameter next: An iterator of code units to be decoded. `next` must be
/// the same iterator instance in repeated calls to this method. Do not
/// advance the iterator or any copies of the iterator outside this
/// method.
/// - Returns: A `UnicodeDecodingResult` instance, representing the next
/// Unicode scalar, an indication of an error, or an indication that the
/// UTF sequence has been fully decoded.
public mutating func decode<I : IteratorProtocol>(
_ next: inout I
) -> UnicodeDecodingResult where I.Element == CodeUnit {
refillBuffer: if !_didExhaustIterator {
// Bufferless ASCII fastpath.
if _fastPath(_bitsInBuffer == 0) {
if let codeUnit = next.next() {
if codeUnit & 0x80 == 0 {
return .scalarValue(UnicodeScalar(_unchecked: UInt32(codeUnit)))
}
// Non-ASCII, proceed to buffering mode.
_decodeBuffer = UInt32(codeUnit)
_bitsInBuffer = 8
} else {
_didExhaustIterator = true
return .emptyInput
}
} else if (_decodeBuffer & 0x80 == 0) {
// ASCII in buffer. We don't refill the buffer so we can return
// to bufferless mode once we've exhausted it.
break refillBuffer
}
// Buffering mode.
// Fill buffer back to 4 bytes (or as many as are left in the iterator).
_sanityCheck(_bitsInBuffer < 32)
repeat {
if let codeUnit = next.next() {
// We use & 0x1f to make the compiler omit a bounds check branch.
_decodeBuffer |= (UInt32(codeUnit) << UInt32(_bitsInBuffer & 0x1f))
_bitsInBuffer = _bitsInBuffer &+ 8
} else {
_didExhaustIterator = true
if _bitsInBuffer == 0 { return .emptyInput }
break // We still have some bytes left in our buffer.
}
} while _bitsInBuffer < 32
} else if _bitsInBuffer == 0 {
return .emptyInput
}
// Decode one unicode scalar.
// Note our empty bytes are always 0x00, which is required for this call.
let (result, length) = UTF8._decodeOne(_decodeBuffer)
// Consume the decoded bytes (or maximal subpart of ill-formed sequence).
let bitsConsumed = 8 &* length
_sanityCheck(1...4 ~= length && bitsConsumed <= _bitsInBuffer)
// Swift doesn't allow shifts greater than or equal to the type width.
// _decodeBuffer >>= UInt32(bitsConsumed) // >>= 32 crashes.
// Mask with 0x3f to let the compiler omit the '>= 64' bounds check.
_decodeBuffer = UInt32(truncatingBitPattern:
UInt64(_decodeBuffer) >> (UInt64(bitsConsumed) & 0x3f))
_bitsInBuffer = _bitsInBuffer &- bitsConsumed
if _fastPath(result != nil) {
return .scalarValue(UnicodeScalar(_unchecked: result!))
} else {
return .error // Ill-formed UTF-8 code unit sequence.
}
}
/// Attempts to decode a single UTF-8 code unit sequence starting at the LSB
/// of `buffer`.
///
/// - Returns:
/// - result: The decoded code point if the code unit sequence is
/// well-formed; `nil` otherwise.
/// - length: The length of the code unit sequence in bytes if it is
/// well-formed; otherwise the *maximal subpart of the ill-formed
/// sequence* (Unicode 8.0.0, Ch 3.9, D93b), i.e. the number of leading
/// code units that were valid or 1 in case none were valid. Unicode
/// recommends to skip these bytes and replace them by a single
/// replacement character (U+FFFD).
///
/// - Requires: There is at least one used byte in `buffer`, and the unused
/// space in `buffer` is filled with some value not matching the UTF-8
/// continuation byte form (`0b10xxxxxx`).
public // @testable
static func _decodeOne(_ buffer: UInt32) -> (result: UInt32?, length: UInt8) {
// Note the buffer is read least significant byte first: [ #3 #2 #1 #0 ].
if buffer & 0x80 == 0 { // 1-byte sequence (ASCII), buffer: [ … … … CU0 ].
let value = buffer & 0xff
return (value, 1)
}
// Determine sequence length using high 5 bits of 1st byte. We use a
// look-up table to branch less. 1-byte sequences are handled above.
//
// case | pattern | description
// ----------------------------
// 00 | 110xx | 2-byte sequence
// 01 | 1110x | 3-byte sequence
// 10 | 11110 | 4-byte sequence
// 11 | other | invalid
//
// 11xxx 10xxx 01xxx 00xxx
let lut0: UInt32 = 0b1011_0000__1111_1111__1111_1111__1111_1111
let lut1: UInt32 = 0b1100_0000__1111_1111__1111_1111__1111_1111
let index = (buffer >> 3) & 0x1f
let bit0 = (lut0 >> index) & 1
let bit1 = (lut1 >> index) & 1
switch (bit1, bit0) {
case (0, 0): // 2-byte sequence, buffer: [ … … CU1 CU0 ].
// Require 10xx xxxx 110x xxxx.
if _slowPath(buffer & 0xc0e0 != 0x80c0) { return (nil, 1) }
// Disallow xxxx xxxx xxx0 000x (<= 7 bits case).
if _slowPath(buffer & 0x001e == 0x0000) { return (nil, 1) }
// Extract data bits.
let value = (buffer & 0x3f00) >> 8
| (buffer & 0x001f) << 6
return (value, 2)
case (0, 1): // 3-byte sequence, buffer: [ … CU2 CU1 CU0 ].
// Disallow xxxx xxxx xx0x xxxx xxxx 0000 (<= 11 bits case).
if _slowPath(buffer & 0x00200f == 0x000000) { return (nil, 1) }
// Disallow xxxx xxxx xx1x xxxx xxxx 1101 (surrogate code points).
if _slowPath(buffer & 0x00200f == 0x00200d) { return (nil, 1) }
// Require 10xx xxxx 10xx xxxx 1110 xxxx.
if _slowPath(buffer & 0xc0c0f0 != 0x8080e0) {
if buffer & 0x00c000 != 0x008000 { return (nil, 1) }
return (nil, 2) // All checks on CU0 & CU1 passed.
}
// Extract data bits.
let value = (buffer & 0x3f0000) >> 16
| (buffer & 0x003f00) >> 2
| (buffer & 0x00000f) << 12
return (value, 3)
case (1, 0): // 4-byte sequence, buffer: [ CU3 CU2 CU1 CU0 ].
// Disallow xxxx xxxx xxxx xxxx xx00 xxxx xxxx x000 (<= 16 bits case).
if _slowPath(buffer & 0x00003007 == 0x00000000) { return (nil, 1) }
// If xxxx xxxx xxxx xxxx xxxx xxxx xxxx x1xx.
if buffer & 0x00000004 == 0x00000004 {
// Require xxxx xxxx xxxx xxxx xx00 xxxx xxxx xx00 (<= 0x10FFFF).
if _slowPath(buffer & 0x00003003 != 0x00000000) { return (nil, 1) }
}
// Require 10xx xxxx 10xx xxxx 10xx xxxx 1111 0xxx.
if _slowPath(buffer & 0xc0c0c0f8 != 0x808080f0) {
if buffer & 0x0000c000 != 0x00008000 { return (nil, 1) }
// All other checks on CU0, CU1 & CU2 passed.
if buffer & 0x00c00000 != 0x00800000 { return (nil, 2) }
return (nil, 3)
}
// Extract data bits.
let value = (buffer & 0x3f000000) >> 24
| (buffer & 0x003f0000) >> 10
| (buffer & 0x00003f00) << 4
| (buffer & 0x00000007) << 18
return (value, 4)
default: // Invalid sequence (CU0 invalid).
return (nil, 1)
}
}
/// Encodes a Unicode scalar as a series of code units by calling the given
/// closure on each code unit.
///
/// For example, the musical fermata symbol ("𝄐") is a single Unicode scalar
/// value (`\u{1D110}`) but requires four code units for its UTF-8
/// representation. The following code encodes a fermata in UTF-8:
///
/// var bytes: [UTF8.CodeUnit] = []
/// UTF8.encode("𝄐", sendingOutputTo: { bytes.append($0) })
/// print(bytes)
/// // Prints "[240, 157, 132, 144]"
///
/// - Parameters:
/// - input: The Unicode scalar value to encode.
/// - processCodeUnit: A closure that processes one code unit argument at a
/// time.
public static func encode(
_ input: UnicodeScalar,
sendingOutputTo processCodeUnit: @noescape (CodeUnit) -> Void
) {
var c = UInt32(input)
var buf3 = UInt8(c & 0xFF)
if c >= UInt32(1<<7) {
c >>= 6
buf3 = (buf3 & 0x3F) | 0x80 // 10xxxxxx
var buf2 = UInt8(c & 0xFF)
if c < UInt32(1<<5) {
buf2 |= 0xC0 // 110xxxxx
}
else {
c >>= 6
buf2 = (buf2 & 0x3F) | 0x80 // 10xxxxxx
var buf1 = UInt8(c & 0xFF)
if c < UInt32(1<<4) {
buf1 |= 0xE0 // 1110xxxx
}
else {
c >>= 6
buf1 = (buf1 & 0x3F) | 0x80 // 10xxxxxx
processCodeUnit(UInt8(c | 0xF0)) // 11110xxx
}
processCodeUnit(buf1)
}
processCodeUnit(buf2)
}
processCodeUnit(buf3)
}
/// Returns a Boolean value indicating whether the specified code unit is a
/// UTF-8 continuation byte.
///
/// Continuation bytes take the form `0b10xxxxxx`. For example, a lowercase
/// "e" with an acute accent above it (`"é"`) uses 2 bytes for its UTF-8
/// representation: `0b11000011` (195) and `0b10101001` (169). The second
/// byte is a continuation byte.
///
/// let eAcute = "é"
/// for codePoint in eAcute.utf8 {
/// print(codePoint, UTF8.isContinuation(codePoint))
/// }
/// // Prints "195 false"
/// // Prints "169 true"
///
/// - Parameter byte: A UTF-8 code unit.
/// - Returns: `true` if `byte` is a continuation byte; otherwise, `false`.
public static func isContinuation(_ byte: CodeUnit) -> Bool {
return byte & 0b11_00__0000 == 0b10_00__0000
}
public static func _nullCodeUnitOffset(in input: UnsafePointer<CodeUnit>) -> Int {
return Int(_swift_stdlib_strlen(UnsafePointer(input)))
}
}
/// A codec for translating between Unicode scalar values and UTF-16 code
/// units.
public struct UTF16 : UnicodeCodec {
/// A type that can hold code unit values for this encoding.
public typealias CodeUnit = UInt16
/// Creates an instance of the UTF-16 codec.
public init() {}
/// A lookahead buffer for one UTF-16 code unit.
internal var _decodeLookahead: UInt32 = 0
/// Flags with layout: `0b0000_00xy`.
///
/// `y` is the EOF flag.
///
/// `x` is set when `_decodeLookahead` contains a code unit.
internal var _lookaheadFlags: UInt8 = 0
/// Starts or continues decoding a UTF-16 sequence.
///
/// To decode a code unit sequence completely, call this method repeatedly
/// until it returns `UnicodeDecodingResult.emptyInput`. Checking that the
/// iterator was exhausted is not sufficient, because the decoder can store
/// buffered data from the input iterator.
///
/// Because of buffering, it is impossible to find the corresponding position
/// in the iterator for a given returned `UnicodeScalar` or an error.
///
/// The following example decodes the UTF-16 encoded bytes of a string into an
/// array of `UnicodeScalar` instances. This is a demonstration only---if
/// you need the Unicode scalar representation of a string, use its
/// `unicodeScalars` view.
///
/// let str = "✨Unicode✨"
/// print(Array(str.utf16))
/// // Prints "[10024, 85, 110, 105, 99, 111, 100, 101, 10024]"
///
/// var codeUnitIterator = str.utf16.makeIterator()
/// var scalars: [UnicodeScalar] = []
/// var utf16Decoder = UTF16()
/// Decode: while true {
/// switch utf16Decoder.decode(&codeUnitIterator) {
/// case .scalarValue(let v): scalars.append(v)
/// case .emptyInput: break Decode
/// case .error:
/// print("Decoding error")
/// break Decode
/// }
/// }
/// print(scalars)
/// // Prints "["\u{2728}", "U", "n", "i", "c", "o", "d", "e", "\u{2728}"]"
///
/// - Parameter next: An iterator of code units to be decoded. `next` must be
/// the same iterator instance in repeated calls to this method. Do not
/// advance the iterator or any copies of the iterator outside this
/// method.
/// - Returns: A `UnicodeDecodingResult` instance, representing the next
/// Unicode scalar, an indication of an error, or an indication that the
/// UTF sequence has been fully decoded.
public mutating func decode<I : IteratorProtocol>(
_ input: inout I
) -> UnicodeDecodingResult where I.Element == CodeUnit {
if _lookaheadFlags & 0b01 != 0 {
return .emptyInput
}
// Note: maximal subpart of ill-formed sequence for UTF-16 can only have
// length 1. Length 0 does not make sense. Neither does length 2 -- in
// that case the sequence is valid.
var unit0: UInt32
if _fastPath(_lookaheadFlags & 0b10 == 0) {
if let first = input.next() {
unit0 = UInt32(first)
} else {
// Set EOF flag.
_lookaheadFlags |= 0b01
return .emptyInput
}
} else {
// Fetch code unit from the lookahead buffer and note this fact in flags.
unit0 = _decodeLookahead
_lookaheadFlags &= 0b01
}
// A well-formed pair of surrogates looks like this:
// [1101 10ww wwxx xxxx] [1101 11xx xxxx xxxx]
if _fastPath((unit0 >> 11) != 0b1101_1) {
// Neither high-surrogate, nor low-surrogate -- sequence of 1 code unit,
// decoding is trivial.
return .scalarValue(UnicodeScalar(unit0))
}
if _slowPath((unit0 >> 10) == 0b1101_11) {
// `unit0` is a low-surrogate. We have an ill-formed sequence.
return .error
}
// At this point we know that `unit0` is a high-surrogate.
var unit1: UInt32
if let second = input.next() {
unit1 = UInt32(second)
} else {
// EOF reached. Set EOF flag.
_lookaheadFlags |= 0b01
// We have seen a high-surrogate and EOF, so we have an ill-formed
// sequence.
return .error
}
if _fastPath((unit1 >> 10) == 0b1101_11) {
// `unit1` is a low-surrogate. We have a well-formed surrogate pair.
let result = 0x10000 + (((unit0 & 0x03ff) << 10) | (unit1 & 0x03ff))
return .scalarValue(UnicodeScalar(result))
}
// Otherwise, we have an ill-formed sequence. These are the possible
// cases:
//
// * `unit1` is a high-surrogate, so we have a pair of two high-surrogates.
//
// * `unit1` is not a surrogate. We have an ill-formed sequence:
// high-surrogate followed by a non-surrogate.
// Save the second code unit in the lookahead buffer.
_decodeLookahead = unit1
_lookaheadFlags |= 0b10
return .error
}
/// Try to decode one Unicode scalar, and return the actual number of code
/// units it spanned in the input. This function may consume more code
/// units than required for this scalar.
@_versioned
internal mutating func _decodeOne<I : IteratorProtocol>(
_ input: inout I
) -> (UnicodeDecodingResult, Int) where I.Element == CodeUnit {
let result = decode(&input)
switch result {
case .scalarValue(let us):
return (result, UTF16.width(us))
case .emptyInput:
return (result, 0)
case .error:
return (result, 1)
}
}
/// Encodes a Unicode scalar as a series of code units by calling the given
/// closure on each code unit.
///
/// For example, the musical fermata symbol ("𝄐") is a single Unicode scalar
/// value (`\u{1D110}`) but requires two code units for its UTF-16
/// representation. The following code encodes a fermata in UTF-16:
///
/// var codeUnits: [UTF16.CodeUnit] = []
/// UTF16.encode("𝄐", sendingOutputTo: { codeUnits.append($0) })
/// print(codeUnits)
/// // Prints "[55348, 56592]"
///
/// - Parameters:
/// - input: The Unicode scalar value to encode.
/// - processCodeUnit: A closure that processes one code unit argument at a
/// time.
public static func encode(
_ input: UnicodeScalar,
sendingOutputTo processCodeUnit: @noescape (CodeUnit) -> Void
) {
let scalarValue: UInt32 = UInt32(input)
if scalarValue <= UInt32(UInt16.max) {
processCodeUnit(UInt16(scalarValue))
}
else {
let lead_offset = UInt32(0xd800) - UInt32(0x10000 >> 10)
processCodeUnit(UInt16(lead_offset + (scalarValue >> 10)))
processCodeUnit(UInt16(0xdc00 + (scalarValue & 0x3ff)))
}
}
}
/// A codec for translating between Unicode scalar values and UTF-32 code
/// units.
public struct UTF32 : UnicodeCodec {
/// A type that can hold code unit values for this encoding.
public typealias CodeUnit = UInt32
/// Creates an instance of the UTF-32 codec.
public init() {}
/// Starts or continues decoding a UTF-32 sequence.
///
/// To decode a code unit sequence completely, call this method repeatedly
/// until it returns `UnicodeDecodingResult.emptyInput`. Checking that the
/// iterator was exhausted is not sufficient, because the decoder can store
/// buffered data from the input iterator.
///
/// Because of buffering, it is impossible to find the corresponding position
/// in the iterator for a given returned `UnicodeScalar` or an error.
///
/// The following example decodes the UTF-16 encoded bytes of a string
/// into an array of `UnicodeScalar` instances. This is a demonstration
/// only---if you need the Unicode scalar representation of a string, use
/// its `unicodeScalars` view.
///
/// // UTF-32 representation of "✨Unicode✨"
/// let codeUnits: [UTF32.CodeUnit] =
/// [10024, 85, 110, 105, 99, 111, 100, 101, 10024]
///
/// var codeUnitIterator = codeUnits.makeIterator()
/// var scalars: [UnicodeScalar] = []
/// var utf32Decoder = UTF32()
/// Decode: while true {
/// switch utf32Decoder.decode(&codeUnitIterator) {
/// case .scalarValue(let v): scalars.append(v)
/// case .emptyInput: break Decode
/// case .error:
/// print("Decoding error")
/// break Decode
/// }
/// }
/// print(scalars)
/// // Prints "["\u{2728}", "U", "n", "i", "c", "o", "d", "e", "\u{2728}"]"
///
/// - Parameter next: An iterator of code units to be decoded. `next` must be
/// the same iterator instance in repeated calls to this method. Do not
/// advance the iterator or any copies of the iterator outside this
/// method.
/// - Returns: A `UnicodeDecodingResult` instance, representing the next
/// Unicode scalar, an indication of an error, or an indication that the
/// UTF sequence has been fully decoded.
public mutating func decode<I : IteratorProtocol>(
_ input: inout I
) -> UnicodeDecodingResult where I.Element == CodeUnit {
return UTF32._decode(&input)
}
internal static func _decode<I : IteratorProtocol>(
_ input: inout I
) -> UnicodeDecodingResult where I.Element == CodeUnit {
guard let x = input.next() else { return .emptyInput }
if _fastPath((x >> 11) != 0b1101_1 && x <= 0x10ffff) {
return .scalarValue(UnicodeScalar(x))
} else {
return .error
}
}
/// Encodes a Unicode scalar as a UTF-32 code unit by calling the given
/// closure.
///
/// For example, like every Unicode scalar, the musical fermata symbol ("𝄐")
/// can be represented in UTF-32 as a single code unit. The following code
/// encodes a fermata in UTF-32:
///
/// var codeUnit: UTF32.CodeUnit = 0
/// UTF32.encode("𝄐", sendingOutputTo: { codeUnit = $0 })
/// print(codeUnit)
/// // Prints "119056"
///
/// - Parameters:
/// - input: The Unicode scalar value to encode.
/// - processCodeUnit: A closure that processes one code unit argument at a
/// time.
public static func encode(
_ input: UnicodeScalar,
sendingOutputTo processCodeUnit: @noescape (CodeUnit) -> Void
) {
processCodeUnit(UInt32(input))
}
}
/// Translates the given input from one Unicode encoding to another by calling
/// the given closure.
///
/// The following example transcodes the UTF-8 representation of the string
/// `"Fermata 𝄐"` into UTF-32.
///
/// let fermata = "Fermata 𝄐"
/// let bytes = fermata.utf8
/// print(Array(bytes))
/// // Prints "[70, 101, 114, 109, 97, 116, 97, 32, 240, 157, 132, 144]"
///
/// var codeUnits: [UTF32.CodeUnit] = []
/// let sink = { codeUnits.append($0) }
/// transcode(bytes.makeIterator(), from: UTF8.self, to: UTF32.self,
/// stoppingOnError: false, sendingOutputTo: sink)
/// print(codeUnits)
/// // Prints "[70, 101, 114, 109, 97, 116, 97, 32, 119056]"
///
/// The `sink` closure is called with each resulting UTF-32 code unit as the
/// function iterates over its input.
///
/// - Parameters:
/// - input: An iterator of code units to be translated, encoded as
/// `inputEncoding`. If `stopOnError` is `false`, the entire iterator will
/// be exhausted. Otherwise, iteration will stop if an encoding error is
/// detected.
/// - inputEncoding: The Unicode encoding of `input`.
/// - outputEncoding: The destination Unicode encoding.
/// - stopOnError: Pass `true` to stop translation when an encoding error is
/// detected in `input`. Otherwise, a Unicode replacement character
/// (`"\u{FFFD}"`) is inserted for each detected error.
/// - processCodeUnit: A closure that processes one `outputEncoding` code
/// unit at a time.
/// - Returns: `true` if the translation detected encoding errors in `input`;
/// otherwise, `false`.
public func transcode<Input, InputEncoding, OutputEncoding>(
_ input: Input,
from inputEncoding: InputEncoding.Type,
to outputEncoding: OutputEncoding.Type,
stoppingOnError stopOnError: Bool,
sendingOutputTo processCodeUnit: @noescape (OutputEncoding.CodeUnit) -> Void
) -> Bool
where
Input : IteratorProtocol,
InputEncoding : UnicodeCodec,
OutputEncoding : UnicodeCodec,
InputEncoding.CodeUnit == Input.Element {
var input = input
// NB. It is not possible to optimize this routine to a memcpy if
// InputEncoding == OutputEncoding. The reason is that memcpy will not
// substitute U+FFFD replacement characters for ill-formed sequences.
var inputDecoder = inputEncoding.init()
var hadError = false
loop:
while true {
switch inputDecoder.decode(&input) {
case .scalarValue(let us):
OutputEncoding.encode(us, sendingOutputTo: processCodeUnit)
case .emptyInput:
break loop
case .error:
hadError = true
if stopOnError {
break loop
}
OutputEncoding.encode("\u{fffd}", sendingOutputTo: processCodeUnit)
}
}
return hadError
}
/// Transcode UTF-16 to UTF-8, replacing ill-formed sequences with U+FFFD.
///
/// Returns the index of the first unhandled code unit and the UTF-8 data
/// that was encoded.
internal func _transcodeSomeUTF16AsUTF8<Input>(
_ input: Input, _ startIndex: Input.Index
) -> (Input.Index, _StringCore._UTF8Chunk)
where
Input : Collection,
Input.Iterator.Element == UInt16 {
typealias _UTF8Chunk = _StringCore._UTF8Chunk
let endIndex = input.endIndex
let utf8Max = sizeof(_UTF8Chunk.self)
var result: _UTF8Chunk = 0
var utf8Count = 0
var nextIndex = startIndex
while nextIndex != input.endIndex && utf8Count != utf8Max {
let u = UInt(input[nextIndex])
let shift = _UTF8Chunk(utf8Count * 8)
var utf16Length: Input.IndexDistance = 1
if _fastPath(u <= 0x7f) {
result |= _UTF8Chunk(u) << shift
utf8Count += 1
} else {
var scalarUtf8Length: Int
var r: UInt
if _fastPath((u >> 11) != 0b1101_1) {
// Neither high-surrogate, nor low-surrogate -- well-formed sequence
// of 1 code unit, decoding is trivial.
if u < 0x800 {
r = 0b10__00_0000__110__0_0000
r |= u >> 6
r |= (u & 0b11_1111) << 8
scalarUtf8Length = 2
}
else {
r = 0b10__00_0000__10__00_0000__1110__0000
r |= u >> 12
r |= ((u >> 6) & 0b11_1111) << 8
r |= (u & 0b11_1111) << 16
scalarUtf8Length = 3
}
} else {
let unit0 = u
if _slowPath((unit0 >> 10) == 0b1101_11) {
// `unit0` is a low-surrogate. We have an ill-formed sequence.
// Replace it with U+FFFD.
r = 0xbdbfef
scalarUtf8Length = 3
} else if _slowPath(input.index(nextIndex, offsetBy: 1) == endIndex) {
// We have seen a high-surrogate and EOF, so we have an ill-formed
// sequence. Replace it with U+FFFD.
r = 0xbdbfef
scalarUtf8Length = 3
} else {
let unit1 = UInt(input[input.index(nextIndex, offsetBy: 1)])
if _fastPath((unit1 >> 10) == 0b1101_11) {
// `unit1` is a low-surrogate. We have a well-formed surrogate
// pair.
let v = 0x10000 + (((unit0 & 0x03ff) << 10) | (unit1 & 0x03ff))
r = 0b10__00_0000__10__00_0000__10__00_0000__1111_0__000
r |= v >> 18
r |= ((v >> 12) & 0b11_1111) << 8
r |= ((v >> 6) & 0b11_1111) << 16
r |= (v & 0b11_1111) << 24
scalarUtf8Length = 4
utf16Length = 2
} else {
// Otherwise, we have an ill-formed sequence. Replace it with
// U+FFFD.
r = 0xbdbfef
scalarUtf8Length = 3
}
}
}
// Don't overrun the buffer
if utf8Count + scalarUtf8Length > utf8Max {
break
}
result |= numericCast(r) << shift
utf8Count += scalarUtf8Length
}
nextIndex = input.index(nextIndex, offsetBy: utf16Length)
}
// FIXME: Annoying check, courtesy of <rdar://problem/16740169>
if utf8Count < sizeofValue(result) {
result |= ~0 << numericCast(utf8Count * 8)
}
return (nextIndex, result)
}
/// Instances of conforming types are used in internal `String`
/// representation.
public // @testable
protocol _StringElement {
static func _toUTF16CodeUnit(_: Self) -> UTF16.CodeUnit
static func _fromUTF16CodeUnit(_ utf16: UTF16.CodeUnit) -> Self
}
extension UTF16.CodeUnit : _StringElement {
public // @testable
static func _toUTF16CodeUnit(_ x: UTF16.CodeUnit) -> UTF16.CodeUnit {
return x
}
public // @testable
static func _fromUTF16CodeUnit(
_ utf16: UTF16.CodeUnit
) -> UTF16.CodeUnit {
return utf16
}
}
extension UTF8.CodeUnit : _StringElement {
public // @testable
static func _toUTF16CodeUnit(_ x: UTF8.CodeUnit) -> UTF16.CodeUnit {
_sanityCheck(x <= 0x7f, "should only be doing this with ASCII")
return UTF16.CodeUnit(x)
}
public // @testable
static func _fromUTF16CodeUnit(
_ utf16: UTF16.CodeUnit
) -> UTF8.CodeUnit {
_sanityCheck(utf16 <= 0x7f, "should only be doing this with ASCII")
return UTF8.CodeUnit(utf16)
}
}
extension UTF16 {
/// Returns the number of code units required to encode the given Unicode
/// scalar.
///
/// Because a Unicode scalar value can require up to 21 bits to store its
/// value, some Unicode scalars are represented in UTF-16 by a pair of
/// 16-bit code units. The first and second code units of the pair,
/// designated *leading* and *trailing* surrogates, make up a *surrogate
/// pair*.
///
/// let anA: UnicodeScalar = "A"
/// print(anA.value)
/// // Prints "65"
/// print(UTF16.width(anA))
/// // Prints "1"
///
/// let anApple: UnicodeScalar = "🍎"
/// print(anApple.value)
/// // Prints "127822"
/// print(UTF16.width(anApple))
/// // Prints "2"
///
/// - Parameter x: A Unicode scalar value.
/// - Returns: The width of `x` when encoded in UTF-16, either `1` or `2`.
public static func width(_ x: UnicodeScalar) -> Int {
return x.value <= 0xFFFF ? 1 : 2
}
/// Returns the high-surrogate code unit of the surrogate pair representing
/// the specifed Unicode scalar.
///
/// Because a Unicode scalar value can require up to 21 bits to store its
/// value, some Unicode scalars are represented in UTF-16 by a pair of
/// 16-bit code units. The first and second code units of the pair,
/// designated *leading* and *trailing* surrogates, make up a *surrogate
/// pair*.
///
/// let apple: UnicodeScalar = "🍎"
/// print(UTF16.leadSurrogate(apple)
/// // Prints "55356"
///
/// - Parameter x: A Unicode scalar value. `x` must be represented by a
/// surrogate pair when encoded in UTF-16. To check whether `x` is
/// represented by a surrogate pair, use `UTF16.width(x) == 2`.
/// - Returns: The leading surrogate code unit of `x` when encoded in UTF-16.
///
/// - SeeAlso: `UTF16.width(_:)`, `UTF16.trailSurrogate(_:)`
public static func leadSurrogate(_ x: UnicodeScalar) -> UTF16.CodeUnit {
_precondition(width(x) == 2)
return UTF16.CodeUnit((x.value - 0x1_0000) >> (10 as UInt32)) + 0xD800
}
/// Returns the low-surrogate code unit of the surrogate pair representing
/// the specifed Unicode scalar.
///
/// Because a Unicode scalar value can require up to 21 bits to store its
/// value, some Unicode scalars are represented in UTF-16 by a pair of
/// 16-bit code units. The first and second code units of the pair,
/// designated *leading* and *trailing* surrogates, make up a *surrogate
/// pair*.
///
/// let apple: UnicodeScalar = "🍎"
/// print(UTF16.trailSurrogate(apple)
/// // Prints "57166"
///
/// - Parameter x: A Unicode scalar value. `x` must be represented by a
/// surrogate pair when encoded in UTF-16. To check whether `x` is
/// represented by a surrogate pair, use `UTF16.width(x) == 2`.
/// - Returns: The trailing surrogate code unit of `x` when encoded in UTF-16.
///
/// - SeeAlso: `UTF16.width(_:)`, `UTF16.leadSurrogate(_:)`
public static func trailSurrogate(_ x: UnicodeScalar) -> UTF16.CodeUnit {
_precondition(width(x) == 2)
return UTF16.CodeUnit(
(x.value - 0x1_0000) & (((1 as UInt32) << 10) - 1)
) + 0xDC00
}
/// Returns a Boolean value indicating whether the specified code unit is a
/// high-surrogate code unit.
///
/// Here's an example of checking whether each code unit in a string's
/// `utf16` view is a lead surrogate. The `apple` string contains a single
/// emoji character made up of a surrogate pair when encoded in UTF-16.
///
/// let apple = "🍎"
/// for unit in apple.utf16 {
/// print(UTF16.isLeadSurrogate(unit))
/// }
/// // Prints "true"
/// // Prints "false"
///
/// This method does not validate the encoding of a UTF-16 sequence beyond
/// the specified code unit. Specifically, it does not validate that a
/// low-surrogate code unit follows `x`.
///
/// - Parameter x: A UTF-16 code unit.
/// - Returns: `true` if `x` is a high-surrogate code unit; otherwise,
/// `false`.
///
/// - SeeAlso: `UTF16.width(_:)`, `UTF16.leadSurrogate(_:)`
public static func isLeadSurrogate(_ x: CodeUnit) -> Bool {
return 0xD800...0xDBFF ~= x
}
/// Returns a Boolean value indicating whether the specified code unit is a
/// low-surrogate code unit.
///
/// Here's an example of checking whether each code unit in a string's
/// `utf16` view is a trailing surrogate. The `apple` string contains a
/// single emoji character made up of a surrogate pair when encoded in
/// UTF-16.
///
/// let apple = "🍎"
/// for unit in apple.utf16 {
/// print(UTF16.isTrailSurrogate(unit))
/// }
/// // Prints "false"
/// // Prints "true"
///
/// This method does not validate the encoding of a UTF-16 sequence beyond
/// the specified code unit. Specifically, it does not validate that a
/// high-surrogate code unit precedes `x`.
///
/// - Parameter x: A UTF-16 code unit.
/// - Returns: `true` if `x` is a low-surrogate code unit; otherwise,
/// `false`.
///
/// - SeeAlso: `UTF16.width(_:)`, `UTF16.leadSurrogate(_:)`
public static func isTrailSurrogate(_ x: CodeUnit) -> Bool {
return 0xDC00...0xDFFF ~= x
}
public // @testable
static func _copy<T : _StringElement, U : _StringElement>(
source: UnsafeMutablePointer<T>,
destination: UnsafeMutablePointer<U>,
count: Int
) {
if strideof(T.self) == strideof(U.self) {
_memcpy(
dest: UnsafeMutablePointer(destination),
src: UnsafeMutablePointer(source),
size: UInt(count) * UInt(strideof(U.self)))
}
else {
for i in 0..<count {
let u16 = T._toUTF16CodeUnit((source + i).pointee)
(destination + i).pointee = U._fromUTF16CodeUnit(u16)
}
}
}
/// Returns the number of UTF-16 code units required for the given code unit
/// sequence when transcoded to UTF-16, and a Boolean value indicating
/// whether the sequence was found to contain only ASCII characters.
///
/// The following example finds the length of the UTF-16 encoding of the
/// string `"Fermata 𝄐"`, starting with its UTF-8 representation.
///
/// let fermata = "Fermata 𝄐"
/// let bytes = fermata.utf8
/// print(Array(bytes))
/// // Prints "[70, 101, 114, 109, 97, 116, 97, 32, 240, 157, 132, 144]"
///
/// let result = transcodedLength(of: bytes.makeIterator(),
/// decodedAs: UTF8.self,
/// repairingIllFormedSequences: false)
/// print(result)
/// // Prints "Optional((10, false))"
///
/// - Parameters:
/// - input: An iterator of code units to be translated, encoded as
/// `sourceEncoding`. If `repairingIllFormedSequences` is `true`, the
/// entire iterator will be exhausted. Otherwise, iteration will stop if
/// an ill-formed sequence is detected.
/// - sourceEncoding: The Unicode encoding of `input`.
/// - repairingIllFormedSequences: Pass `true` to measure the length of
/// `input` even when `input` contains ill-formed sequences. Each
/// ill-formed sequence is replaced with a Unicode replacement character
/// (`"\u{FFFD}"`) and is measured as such. Pass `false` to immediately
/// stop measuring `input` when an ill-formed sequence is encountered.
/// - Returns: A tuple containing the number of UTF-16 code units required to
/// encode `input` and a Boolean value that indicates whether the `input`
/// contained only ASCII characters. If `repairingIllFormedSequences` is
/// `false` and an ill-formed sequence is detected, this method returns
/// `nil`.
public static func transcodedLength<Input, Encoding>(
of input: Input,
decodedAs sourceEncoding: Encoding.Type,
repairingIllFormedSequences: Bool
) -> (count: Int, isASCII: Bool)?
where
Input : IteratorProtocol,
Encoding : UnicodeCodec,
Encoding.CodeUnit == Input.Element {
var input = input
var count = 0
var isAscii = true
var inputDecoder = Encoding()
loop:
while true {
switch inputDecoder.decode(&input) {
case .scalarValue(let us):
if us.value > 0x7f {
isAscii = false
}
count += width(us)
case .emptyInput:
break loop
case .error:
if !repairingIllFormedSequences {
return nil
}
isAscii = false
count += width(UnicodeScalar(0xfffd))
}
}
return (count, isAscii)
}
}
// Unchecked init to avoid precondition branches in hot code paths where we
// already know the value is a valid unicode scalar.
extension UnicodeScalar {
/// Create an instance with numeric value `value`, bypassing the regular
/// precondition checks for code point validity.
internal init(_unchecked value: UInt32) {
_sanityCheck(value < 0xD800 || value > 0xDFFF,
"high- and low-surrogate code points are not valid Unicode scalar values")
_sanityCheck(value <= 0x10FFFF, "value is outside of Unicode codespace")
self._value = value
}
}
extension UnicodeCodec where CodeUnit : UnsignedInteger {
public static func _nullCodeUnitOffset(in input: UnsafePointer<CodeUnit>) -> Int {
var length = 0
while input[length] != 0 {
length += 1
}
return length
}
}
extension UnicodeCodec {
public static func _nullCodeUnitOffset(in input: UnsafePointer<CodeUnit>) -> Int {
fatalError("_nullCodeUnitOffset(in:) implementation should be provided")
}
}
@available(*, unavailable, renamed: "UnicodeCodec")
public typealias UnicodeCodecType = UnicodeCodec
@available(*, unavailable, message: "use 'transcode(_:from:to:stoppingOnError:sendingOutputTo:)'")
public func transcode<Input, InputEncoding, OutputEncoding>(
_ inputEncoding: InputEncoding.Type, _ outputEncoding: OutputEncoding.Type,
_ input: Input, _ output: (OutputEncoding.CodeUnit) -> Void,
stoppingOnError stopOnError: Bool
) -> Bool
where
Input : IteratorProtocol,
InputEncoding : UnicodeCodec,
OutputEncoding : UnicodeCodec,
InputEncoding.CodeUnit == Input.Element {
Builtin.unreachable()
}
extension UTF16 {
@available(*, unavailable, message: "use 'transcodedLength(of:decodedAs:repairingIllFormedSequences:)'")
public static func measure<Encoding, Input>(
_: Encoding.Type, input: Input, repairIllFormedSequences: Bool
) -> (Int, Bool)?
where
Encoding : UnicodeCodec,
Input : IteratorProtocol,
Encoding.CodeUnit == Input.Element {
Builtin.unreachable()
}
}
| apache-2.0 | 30f49df2678e8eda742eb3634a0696a0 | 36.344628 | 106 | 0.623321 | 3.864449 | false | false | false | false |
PJayRushton/TeacherTools | TeacherTools/CreateGroup.swift | 1 | 1333 | //
// CreateGroup.swift
// TeacherTools
//
// Created by Parker Rushton on 11/5/16.
// Copyright © 2016 AppsByPJ. All rights reserved.
//
import Foundation
struct CreateGroup: Command {
var name: String
func execute(state: AppState, core: Core<AppState>) {
guard let user = state.currentUser, case let ref = networkAccess.groupsRef(userId: user.id).childByAutoId(), let key = ref.key else { return }
let newGroup = Group(id: key, name: name)
networkAccess.addObject(at: ref, parameters: newGroup.jsonObject()) { result in
switch result {
case .success:
core.fire(event: Selected<Group>(newGroup))
guard let currentUser = state.currentUser else { return }
let fakeStudentRef = self.networkAccess.studentsRef(userId: currentUser.id)
self.networkAccess.updateObject(at: fakeStudentRef, parameters: ["fake": true], completion: { result in
if case .success = result, !state.hasSubscribedToStudents {
core.fire(command: SubscribeToStudents())
}
})
case let .failure(error):
core.fire(event: ErrorEvent(error: error, message: nil))
}
}
}
}
| mit | e14caeaeb55f5abf34d06d5a0e0d1eeb | 35 | 150 | 0.583333 | 4.657343 | false | false | false | false |
mozilla-mobile/firefox-ios | Client/Frontend/Widgets/AutocompleteTextField.swift | 2 | 13979 | // This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0
// This code is loosely based on https://github.com/Antol/APAutocompleteTextField
import UIKit
import Shared
/// Delegate for the text field events. Since AutocompleteTextField owns the UITextFieldDelegate,
/// callers must use this instead.
protocol AutocompleteTextFieldDelegate: AnyObject {
func autocompleteTextField(_ autocompleteTextField: AutocompleteTextField, didEnterText text: String)
func autocompleteTextFieldShouldReturn(_ autocompleteTextField: AutocompleteTextField) -> Bool
func autocompleteTextFieldShouldClear(_ autocompleteTextField: AutocompleteTextField) -> Bool
func autocompleteTextFieldDidCancel(_ autocompleteTextField: AutocompleteTextField)
func autocompletePasteAndGo(_ autocompleteTextField: AutocompleteTextField)
}
class AutocompleteTextField: UITextField, UITextFieldDelegate {
var autocompleteDelegate: AutocompleteTextFieldDelegate?
// AutocompleteTextLabel represents the actual autocomplete text.
// The textfields "text" property only contains the entered text, while this label holds the autocomplete text
// This makes sure that the autocomplete doesnt mess with keyboard suggestions provided by third party keyboards.
private var autocompleteTextLabel: UILabel?
private var hideCursor: Bool = false
private let copyShortcutKey = "c"
var isSelectionActive: Bool {
return autocompleteTextLabel != nil
}
// This variable is a solution to get the right behavior for refocusing
// the AutocompleteTextField. The initial transition into Overlay Mode
// doesn't involve the user interacting with AutocompleteTextField.
// Thus, we update shouldApplyCompletion in touchesBegin() to reflect whether
// the highlight is active and then the text field is updated accordingly
// in touchesEnd() (eg. applyCompletion() is called or not)
fileprivate var notifyTextChanged: (() -> Void)?
private var lastReplacement: String?
static var textSelectionColor = URLBarColor.TextSelectionHighlight(labelMode: UIColor(), textFieldMode: nil)
override var text: String? {
didSet {
super.text = text
self.textDidChange(self)
}
}
override var accessibilityValue: String? {
get {
return (self.text ?? "") + (self.autocompleteTextLabel?.text ?? "")
}
set(value) {
super.accessibilityValue = value
}
}
override init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
fileprivate func commonInit() {
super.delegate = self
super.addTarget(self, action: #selector(AutocompleteTextField.textDidChange), for: .editingChanged)
notifyTextChanged = debounce(0.1, action: {
if self.isEditing {
self.autocompleteDelegate?.autocompleteTextField(self, didEnterText: self.normalizeString(self.text ?? ""))
}
})
}
override var keyCommands: [UIKeyCommand]? {
let commands = [
UIKeyCommand(input: copyShortcutKey, modifierFlags: .command, action: #selector(self.handleKeyCommand(sender:)))
]
let arrowKeysCommands = [
UIKeyCommand(input: UIKeyCommand.inputLeftArrow, modifierFlags: [], action: #selector(self.handleKeyCommand(sender:))),
UIKeyCommand(input: UIKeyCommand.inputRightArrow, modifierFlags: [], action: #selector(self.handleKeyCommand(sender:))),
UIKeyCommand(input: UIKeyCommand.inputEscape, modifierFlags: [], action: #selector(self.handleKeyCommand(sender:))),
]
// In iOS 15+, certain keys events are delivered to the text input or focus systems first, unless specified otherwise
if #available(iOS 15, *) {
arrowKeysCommands.forEach { $0.wantsPriorityOverSystemBehavior = true }
}
return arrowKeysCommands + commands
}
@objc func handleKeyCommand(sender: UIKeyCommand) {
guard let input = sender.input else { return }
switch input {
case UIKeyCommand.inputLeftArrow:
TelemetryWrapper.recordEvent(category: .action, method: .press, object: .keyCommand, extras: ["action": "autocomplete-left-arrow"])
if isSelectionActive {
applyCompletion()
// Set the current position to the beginning of the text.
selectedTextRange = textRange(from: beginningOfDocument, to: beginningOfDocument)
} else if let range = selectedTextRange {
if range.start == beginningOfDocument {
break
}
guard let cursorPosition = position(from: range.start, offset: -1) else {
break
}
selectedTextRange = textRange(from: cursorPosition, to: cursorPosition)
}
case UIKeyCommand.inputRightArrow:
TelemetryWrapper.recordEvent(category: .action, method: .press, object: .keyCommand, extras: ["action": "autocomplete-right-arrow"])
if isSelectionActive {
applyCompletion()
// Set the current position to the end of the text.
selectedTextRange = textRange(from: endOfDocument, to: endOfDocument)
} else if let range = selectedTextRange {
if range.end == endOfDocument {
break
}
guard let cursorPosition = position(from: range.end, offset: 1) else {
break
}
selectedTextRange = textRange(from: cursorPosition, to: cursorPosition)
}
case UIKeyCommand.inputEscape:
TelemetryWrapper.recordEvent(category: .action, method: .press, object: .keyCommand, extras: ["action": "autocomplete-cancel"])
autocompleteDelegate?.autocompleteTextFieldDidCancel(self)
case copyShortcutKey:
if isSelectionActive {
UIPasteboard.general.string = self.autocompleteTextLabel?.text
} else {
if let selectedTextRange = self.selectedTextRange {
UIPasteboard.general.string = self.text(in: selectedTextRange)
}
}
default:
break
}
}
fileprivate func normalizeString(_ string: String) -> String {
return string.lowercased().stringByTrimmingLeadingCharactersInSet(CharacterSet.whitespaces)
}
/// Commits the completion by setting the text and removing the highlight.
fileprivate func applyCompletion() {
// Clear the current completion, then set the text without the attributed style.
let text = (self.text ?? "") + (self.autocompleteTextLabel?.text ?? "")
let didRemoveCompletion = removeCompletion()
self.text = text
hideCursor = false
// Move the cursor to the end of the completion.
if didRemoveCompletion {
selectedTextRange = textRange(from: endOfDocument, to: endOfDocument)
}
}
/// Removes the autocomplete-highlighted. Returns true if a completion was actually removed
@objc @discardableResult fileprivate func removeCompletion() -> Bool {
let hasActiveCompletion = isSelectionActive
autocompleteTextLabel?.removeFromSuperview()
autocompleteTextLabel = nil
return hasActiveCompletion
}
@objc fileprivate func clear() {
text = ""
removeCompletion()
autocompleteDelegate?.autocompleteTextField(self, didEnterText: "")
}
// `shouldChangeCharactersInRange` is called before the text changes, and textDidChange is called after.
// Since the text has changed, remove the completion here, and textDidChange will fire the callback to
// get the new autocompletion.
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
// This happens when you begin typing overtop the old highlighted
// text immediately after focusing the text field. We need to trigger
// a `didEnterText` that looks like a `clear()` so that the SearchLoader
// can reset itself since it will only lookup results if the new text is
// longer than the previous text.
if lastReplacement == nil {
autocompleteDelegate?.autocompleteTextField(self, didEnterText: "")
}
lastReplacement = string
return true
}
func setAutocompleteSuggestion(_ suggestion: String?) {
let text = self.text ?? ""
guard let suggestion = suggestion, isEditing && markedTextRange == nil else {
hideCursor = false
return
}
let normalized = normalizeString(text)
guard suggestion.hasPrefix(normalized) && normalized.count < suggestion.count else {
hideCursor = false
return
}
let suggestionText = String(suggestion[suggestion.index(suggestion.startIndex, offsetBy: normalized.count)...])
let autocompleteText = NSMutableAttributedString(string: suggestionText)
let color = AutocompleteTextField.textSelectionColor.labelMode
autocompleteText.addAttribute(NSAttributedString.Key.backgroundColor, value: color, range: NSRange(location: 0, length: suggestionText.count))
autocompleteTextLabel?.removeFromSuperview() // should be nil. But just in case
autocompleteTextLabel = createAutocompleteLabelWith(autocompleteText)
if let label = autocompleteTextLabel {
addSubview(label)
// Only call forceResetCursor() if `hideCursor` changes.
// Because forceResetCursor() auto accept iOS user's text replacement
// (e.g. mu->μ) which makes user unable to type "mu".
if !hideCursor {
hideCursor = true
forceResetCursor()
}
}
}
override func caretRect(for position: UITextPosition) -> CGRect {
return hideCursor ? CGRect.zero : super.caretRect(for: position)
}
private func createAutocompleteLabelWith(_ autocompleteText: NSAttributedString) -> UILabel {
let label = UILabel()
var frame = self.bounds
label.attributedText = autocompleteText
label.font = self.font
label.accessibilityIdentifier = "autocomplete"
label.backgroundColor = self.backgroundColor
label.textColor = self.textColor
label.textAlignment = .left
let enteredTextSize = self.attributedText?.boundingRect(with: self.frame.size, options: NSStringDrawingOptions.usesLineFragmentOrigin, context: nil)
frame.origin.x = (enteredTextSize?.width.rounded() ?? 0) + textRect(forBounds: bounds).origin.x
frame.size.width = self.frame.size.width - clearButtonRect(forBounds: self.frame).size.width - frame.origin.x
frame.size.height = self.frame.size.height
label.frame = frame
return label
}
func textFieldShouldEndEditing(_ textField: UITextField) -> Bool {
applyCompletion()
return true
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
applyCompletion()
return autocompleteDelegate?.autocompleteTextFieldShouldReturn(self) ?? true
}
func textFieldShouldClear(_ textField: UITextField) -> Bool {
removeCompletion()
return autocompleteDelegate?.autocompleteTextFieldShouldClear(self) ?? true
}
override func setMarkedText(_ markedText: String?, selectedRange: NSRange) {
// Clear the autocompletion if any provisionally inserted text has been
// entered (e.g., a partial composition from a Japanese keyboard).
removeCompletion()
super.setMarkedText(markedText, selectedRange: selectedRange)
}
func setTextWithoutSearching(_ text: String) {
super.text = text
hideCursor = autocompleteTextLabel != nil
removeCompletion()
}
@objc func textDidChange(_ textField: UITextField) {
hideCursor = autocompleteTextLabel != nil
removeCompletion()
let isKeyboardReplacingText = lastReplacement != nil
if isKeyboardReplacingText, markedTextRange == nil {
notifyTextChanged?()
} else {
hideCursor = false
}
}
// Reset the cursor to the end of the text field.
// This forces `caretRect(for position: UITextPosition)` to be called which will decide if we should show the cursor
// This exists because ` caretRect(for position: UITextPosition)` is not called after we apply an autocompletion.
private func forceResetCursor() {
selectedTextRange = nil
selectedTextRange = textRange(from: endOfDocument, to: endOfDocument)
}
override func deleteBackward() {
lastReplacement = ""
hideCursor = false
if isSelectionActive {
removeCompletion()
forceResetCursor()
} else {
super.deleteBackward()
}
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
applyCompletion()
super.touchesBegan(touches, with: event)
}
}
extension AutocompleteTextField: MenuHelperInterface {
override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
if action == MenuHelper.SelectorPasteAndGo {
return UIPasteboard.general.hasStrings
}
return super.canPerformAction(action, withSender: sender)
}
func menuHelperPasteAndGo() {
autocompleteDelegate?.autocompletePasteAndGo(self)
}
}
| mpl-2.0 | 4f507e1ea477dfe62441b3acf72a77fc | 40.477745 | 156 | 0.664401 | 5.438911 | false | false | false | false |
moshbit/Kotlift | test-dest/21_visibility.swift | 2 | 1838 | /* Output:
Nested init
234
Nested init
com.moshbit.kotlift.Outer$Nested@4c5e43ee (or similar)
Nested init
5
78910348910
*/
// Uncommented code will not compile due to visibility modifiers
internal class Outer {
private let a = 1
internal let b = 2
internal let c = 3
let d = 4 // public by default
internal let n = Nested()
internal class Nested {
internal let e: Int32 = 5
init() {
print("Nested init")
}
}
private func o() -> Int32 {
return 6
}
internal func p() -> Int32 {
return 7
}
internal func q() -> Int32 {
return 8
}
func r() -> Int32 {
return 9
}
public func s() -> Int32 {
return 10
}
}
internal class Subclass: Outer {
// a is not visible
// b, c and d are visible
// Nested and e are visible
func printAll() {
// print(a)
print(b)
print(c)
print(d)
print(Outer.Nested())
print(Nested().e)
// print(o())
print(p())
print(q())
print(r())
print(s())
}
override init() {
}
}
public class Unrelated {
let o: Outer
// o.a, o.b are not visible
// o.c and o.d are visible (same module)
// Outer.Nested and Nested::e are not visible. In Swift they are visible, as there is no Protected.
func printAll() {
// print(o.a)
// print(o.b) // This statement runs in Swift, as there is no Protected.
print(o.c)
print(o.d)
/* // It is OK that the following 3 lines run in Swift:
val nested = Outer.Nested()
println(nested)
println(nested.e)*/
// print(o.o())
// print(o.p()) // This statement runs in Swift, as there is no Protected.
print(o.q())
print(o.r())
print(o.s())
}
init(o: Outer) {
self.o = o
}
}
func main(args: [String]) {
let x = Subclass()
x.printAll()
let y = Unrelated(o: x)
y.printAll()
}
main([])
| apache-2.0 | 8ef62291d7d1469f27f906426754a733 | 16.504762 | 101 | 0.584331 | 3.218914 | false | false | false | false |
frootloops/swift | test/IRGen/struct_resilience.swift | 1 | 10471 | // RUN: %empty-directory(%t)
// RUN: %target-swift-frontend -emit-module -enable-resilience -emit-module-path=%t/resilient_struct.swiftmodule -module-name=resilient_struct %S/../Inputs/resilient_struct.swift
// RUN: %target-swift-frontend -emit-module -enable-resilience -emit-module-path=%t/resilient_enum.swiftmodule -module-name=resilient_enum -I %t %S/../Inputs/resilient_enum.swift
// RUN: %target-swift-frontend -I %t -emit-ir -enable-resilience %s | %FileCheck %s
// RUN: %target-swift-frontend -I %t -emit-ir -enable-resilience -O %s
import resilient_struct
import resilient_enum
// CHECK: %TSi = type <{ [[INT:i32|i64]] }>
// CHECK-LABEL: @_T017struct_resilience26StructWithResilientStorageVMf = internal global
// Resilient structs from outside our resilience domain are manipulated via
// value witnesses
// CHECK-LABEL: define{{( protected)?}} swiftcc void @_T017struct_resilience26functionWithResilientTypes010resilient_A04SizeVAE_A2Ec1ftF(%swift.opaque* noalias nocapture sret, %swift.opaque* noalias nocapture, i8*, %swift.refcounted*)
public func functionWithResilientTypes(_ s: Size, f: (Size) -> Size) -> Size {
// CHECK: [[METADATA:%.*]] = call %swift.type* @_T016resilient_struct4SizeVMa()
// CHECK: [[METADATA_ADDR:%.*]] = bitcast %swift.type* [[METADATA]] to i8***
// CHECK: [[VWT_ADDR:%.*]] = getelementptr inbounds i8**, i8*** [[METADATA_ADDR]], [[INT]] -1
// CHECK: [[VWT:%.*]] = load i8**, i8*** [[VWT_ADDR]]
// CHECK: [[WITNESS_ADDR:%.*]] = getelementptr inbounds i8*, i8** [[VWT]], i32 9
// CHECK: [[WITNESS:%.*]] = load i8*, i8** [[WITNESS_ADDR]]
// CHECK: [[WITNESS_FOR_SIZE:%.*]] = ptrtoint i8* [[WITNESS]]
// CHECK: [[ALLOCA:%.*]] = alloca i8, {{.*}} [[WITNESS_FOR_SIZE]], align 16
// CHECK: [[STRUCT_ADDR:%.*]] = bitcast i8* [[ALLOCA]] to %swift.opaque*
// CHECK: [[WITNESS_PTR:%.*]] = getelementptr inbounds i8*, i8** [[VWT]], i32 2
// CHECK: [[WITNESS:%.*]] = load i8*, i8** [[WITNESS_PTR]]
// CHECK: [[initializeWithCopy:%.*]] = bitcast i8* [[WITNESS]]
// CHECK: [[STRUCT_LOC:%.*]] = call %swift.opaque* [[initializeWithCopy]](%swift.opaque* noalias [[STRUCT_ADDR]], %swift.opaque* noalias %1, %swift.type* [[METADATA]])
// CHECK: [[FN:%.*]] = bitcast i8* %2 to void (%swift.opaque*, %swift.opaque*, %swift.refcounted*)*
// CHECK: call swiftcc void [[FN]](%swift.opaque* noalias nocapture sret %0, %swift.opaque* noalias nocapture [[STRUCT_ADDR]], %swift.refcounted* swiftself %3)
// CHECK: [[WITNESS_PTR:%.*]] = getelementptr inbounds i8*, i8** [[VWT]], i32 1
// CHECK: [[WITNESS:%.*]] = load i8*, i8** [[WITNESS_PTR]]
// CHECK: [[destroy:%.*]] = bitcast i8* [[WITNESS]] to void (%swift.opaque*, %swift.type*)*
// CHECK: call void [[destroy]](%swift.opaque* noalias %1, %swift.type* [[METADATA]])
// CHECK: ret void
return f(s)
}
// CHECK-LABEL: declare %swift.type* @_T016resilient_struct4SizeVMa()
// Rectangle has fixed layout inside its resilience domain, and dynamic
// layout on the outside.
//
// Make sure we use a type metadata accessor function, and load indirect
// field offsets from it.
// CHECK-LABEL: define{{( protected)?}} swiftcc void @_T017struct_resilience26functionWithResilientTypesy010resilient_A09RectangleVF(%T16resilient_struct9RectangleV* noalias nocapture)
public func functionWithResilientTypes(_ r: Rectangle) {
// CHECK: [[METADATA:%.*]] = call %swift.type* @_T016resilient_struct9RectangleVMa()
// CHECK-NEXT: [[METADATA_ADDR:%.*]] = bitcast %swift.type* [[METADATA]] to [[INT]]*
// CHECK-NEXT: [[FIELD_OFFSET_VECTOR:%.*]] = getelementptr inbounds [[INT]], [[INT]]* [[METADATA_ADDR]], [[INT]] 2
// CHECK-NEXT: [[FIELD_OFFSET_PTR:%.*]] = getelementptr inbounds [[INT]], [[INT]]* [[FIELD_OFFSET_VECTOR]], i32 2
// CHECK-NEXT: [[FIELD_OFFSET:%.*]] = load [[INT]], [[INT]]* [[FIELD_OFFSET_PTR]]
// CHECK-NEXT: [[STRUCT_ADDR:%.*]] = bitcast %T16resilient_struct9RectangleV* %0 to i8*
// CHECK-NEXT: [[FIELD_ADDR:%.*]] = getelementptr inbounds i8, i8* [[STRUCT_ADDR]], [[INT]] [[FIELD_OFFSET]]
// CHECK-NEXT: [[FIELD_PTR:%.*]] = bitcast i8* [[FIELD_ADDR]] to %TSi*
// CHECK-NEXT: [[FIELD_PAYLOAD_PTR:%.*]] = getelementptr inbounds %TSi, %TSi* [[FIELD_PTR]], i32 0, i32 0
// CHECK-NEXT: [[FIELD_PAYLOAD:%.*]] = load [[INT]], [[INT]]* [[FIELD_PAYLOAD_PTR]]
_ = r.color
// CHECK: ret void
}
// Resilient structs from inside our resilience domain are manipulated
// directly.
public struct MySize {
public let w: Int
public let h: Int
}
// CHECK-LABEL: define{{( protected)?}} swiftcc void @_T017struct_resilience28functionWithMyResilientTypesAA0E4SizeVAD_A2Dc1ftF(%T17struct_resilience6MySizeV* {{.*}}, %T17struct_resilience6MySizeV* {{.*}}, i8*, %swift.refcounted*)
public func functionWithMyResilientTypes(_ s: MySize, f: (MySize) -> MySize) -> MySize {
// CHECK: [[TEMP:%.*]] = alloca %T17struct_resilience6MySizeV
// CHECK: bitcast
// CHECK: llvm.lifetime.start
// CHECK: [[COPY:%.*]] = bitcast %T17struct_resilience6MySizeV* %4 to i8*
// CHECK: [[ARG:%.*]] = bitcast %T17struct_resilience6MySizeV* %1 to i8*
// CHECK: call void @llvm.memcpy{{.*}}(i8* [[COPY]], i8* [[ARG]], {{i32 8|i64 16}}, i32 {{.*}}, i1 false)
// CHECK: [[FN:%.*]] = bitcast i8* %2
// CHECK: call swiftcc void [[FN]](%T17struct_resilience6MySizeV* {{.*}} %0, {{.*}} [[TEMP]], %swift.refcounted* swiftself %3)
// CHECK: ret void
return f(s)
}
// Structs with resilient storage from a different resilience domain require
// runtime metadata instantiation, just like generics.
public struct StructWithResilientStorage {
public let s: Size
public let ss: (Size, Size)
public let n: Int
public let i: ResilientInt
}
// Make sure we call a function to access metadata of structs with
// resilient layout, and go through the field offset vector in the
// metadata when accessing stored properties.
// CHECK-LABEL: define{{( protected)?}} swiftcc {{i32|i64}} @_T017struct_resilience26StructWithResilientStorageV1nSivg(%T17struct_resilience26StructWithResilientStorageV* {{.*}})
// CHECK: [[METADATA:%.*]] = call %swift.type* @_T017struct_resilience26StructWithResilientStorageVMa()
// CHECK-NEXT: [[METADATA_ADDR:%.*]] = bitcast %swift.type* [[METADATA]] to [[INT]]*
// CHECK-NEXT: [[FIELD_OFFSET_VECTOR:%.*]] = getelementptr inbounds [[INT]], [[INT]]* [[METADATA_ADDR]], [[INT]] 2
// CHECK-NEXT: [[FIELD_OFFSET_PTR:%.*]] = getelementptr inbounds [[INT]], [[INT]]* [[FIELD_OFFSET_VECTOR]], i32 2
// CHECK-NEXT: [[FIELD_OFFSET:%.*]] = load [[INT]], [[INT]]* [[FIELD_OFFSET_PTR]]
// CHECK-NEXT: [[STRUCT_ADDR:%.*]] = bitcast %T17struct_resilience26StructWithResilientStorageV* %0 to i8*
// CHECK-NEXT: [[FIELD_ADDR:%.*]] = getelementptr inbounds i8, i8* [[STRUCT_ADDR]], [[INT]] [[FIELD_OFFSET]]
// CHECK-NEXT: [[FIELD_PTR:%.*]] = bitcast i8* [[FIELD_ADDR]] to %TSi*
// CHECK-NEXT: [[FIELD_PAYLOAD_PTR:%.*]] = getelementptr inbounds %TSi, %TSi* [[FIELD_PTR]], i32 0, i32 0
// CHECK-NEXT: [[FIELD_PAYLOAD:%.*]] = load [[INT]], [[INT]]* [[FIELD_PAYLOAD_PTR]]
// CHECK-NEXT: ret [[INT]] [[FIELD_PAYLOAD]]
// Indirect enums with resilient payloads are still fixed-size.
public struct StructWithIndirectResilientEnum {
public let s: FunnyShape
public let n: Int
}
// CHECK-LABEL: define{{( protected)?}} swiftcc {{i32|i64}} @_T017struct_resilience31StructWithIndirectResilientEnumV1nSivg(%T17struct_resilience31StructWithIndirectResilientEnumV* {{.*}})
// CHECK: [[FIELD_PTR:%.*]] = getelementptr inbounds %T17struct_resilience31StructWithIndirectResilientEnumV, %T17struct_resilience31StructWithIndirectResilientEnumV* %0, i32 0, i32 1
// CHECK-NEXT: [[FIELD_PAYLOAD_PTR:%.*]] = getelementptr inbounds %TSi, %TSi* [[FIELD_PTR]], i32 0, i32 0
// CHECK-NEXT: [[FIELD_PAYLOAD:%.*]] = load [[INT]], [[INT]]* [[FIELD_PAYLOAD_PTR]]
// CHECK-NEXT: ret [[INT]] [[FIELD_PAYLOAD]]
// Partial application of methods on resilient value types
public struct ResilientStructWithMethod {
public func method() {}
}
// Corner case -- type is address-only in SIL, but empty in IRGen
// CHECK-LABEL: define{{( protected)?}} swiftcc void @_T017struct_resilience29partialApplyOfResilientMethodyAA0f10StructWithG0V1r_tF(%T17struct_resilience25ResilientStructWithMethodV* noalias nocapture)
public func partialApplyOfResilientMethod(r: ResilientStructWithMethod) {
_ = r.method
}
// Type is address-only in SIL, and resilient in IRGen
// CHECK-LABEL: define{{( protected)?}} swiftcc void @_T017struct_resilience29partialApplyOfResilientMethody010resilient_A04SizeV1s_tF(%swift.opaque* noalias nocapture)
public func partialApplyOfResilientMethod(s: Size) {
_ = s.method
}
// Public metadata accessor for our resilient struct
// CHECK-LABEL: define{{( protected)?}} %swift.type* @_T017struct_resilience6MySizeVMa()
// CHECK: ret %swift.type* bitcast ([[INT]]* getelementptr inbounds {{.*}} @_T017struct_resilience6MySizeVMf, i32 0, i32 1) to %swift.type*)
// CHECK-LABEL: define{{( protected)?}} private void @initialize_metadata_StructWithResilientStorage(i8*)
// CHECK: [[FIELDS:%.*]] = alloca [4 x i8**]
// CHECK: [[VWT:%.*]] = load i8**, i8*** getelementptr inbounds ({{.*}} @_T017struct_resilience26StructWithResilientStorageVMf{{.*}}, [[INT]] -1)
// CHECK: [[FIELDS_ADDR:%.*]] = getelementptr inbounds [4 x i8**], [4 x i8**]* [[FIELDS]], i32 0, i32 0
// public let s: Size
// CHECK: [[FIELD_1:%.*]] = getelementptr inbounds i8**, i8*** [[FIELDS_ADDR]], i32 0
// CHECK: store i8** [[SIZE_AND_ALIGNMENT:%.*]], i8*** [[FIELD_1]]
// public let ss: (Size, Size)
// CHECK: [[FIELD_2:%.*]] = getelementptr inbounds i8**, i8*** [[FIELDS_ADDR]], i32 1
// CHECK: store i8** [[SIZE_AND_ALIGNMENT:%.*]], i8*** [[FIELD_2]]
// Fixed-layout aggregate -- we can reference a static value witness table
// public let n: Int
// CHECK: [[FIELD_3:%.*]] = getelementptr inbounds i8**, i8*** [[FIELDS_ADDR]], i32 2
// CHECK: store i8** getelementptr inbounds (i8*, i8** @_T0Bi{{32|64}}_WV, i32 {{.*}}), i8*** [[FIELD_3]]
// Resilient aggregate with one field -- make sure we don't look inside it
// public let i: ResilientInt
// CHECK: [[FIELD_4:%.*]] = getelementptr inbounds i8**, i8*** [[FIELDS_ADDR]], i32 3
// CHECK: store i8** [[SIZE_AND_ALIGNMENT:%.*]], i8*** [[FIELD_4]]
// CHECK: call void @swift_initStructMetadata_UniversalStrategy([[INT]] 4, i8*** [[FIELDS_ADDR]], [[INT]]* {{.*}}, i8** [[VWT]])
// CHECK: store atomic %swift.type* {{.*}} @_T017struct_resilience26StructWithResilientStorageVMf{{.*}}, %swift.type** @_T017struct_resilience26StructWithResilientStorageVML release,
// CHECK: ret void
| apache-2.0 | 3abcc4f169d64f652c29fa924af6ebc4 | 51.355 | 234 | 0.677013 | 3.623183 | false | false | false | false |
qvik/qvik-swift-ios | QvikSwiftTests/SequenceTypeExtensionsTests.swift | 1 | 676 | //
// SequenceTypeExtensionsTests.swift
// QvikSwift
//
// Created by Matti Dahlbom on 05/05/16.
// Copyright © 2016 Qvik. All rights reserved.
//
import UIKit
import XCTest
class SequenceTypeExtensionsTests: XCTestCase {
func testUnique() {
let ints = [0, 1, 2, 3, 3, 4, 2, 5, 10, 11, 5, 12, 12, 23, 15, 23]
let uniqueInts = [0, 1, 2, 3, 4, 5, 10, 11, 12, 23, 15]
XCTAssert(ints.unique() == uniqueInts)
let strings = ["kalle", "palle", "jarkko", "kerkko", "kalle", "kissa", "palle", "kerkko"]
let uniqueStrings = ["kalle", "palle", "jarkko", "kerkko", "kissa"]
XCTAssert(strings.unique() == uniqueStrings)
}
}
| mit | ddae7e1ebbc19567d8df3b2678219d20 | 28.347826 | 97 | 0.595556 | 2.973568 | false | true | false | false |
JunyiXie/XJYChart | XJYChartDemo/XJYChartDemo-Swift/View/PositiveNegativeBarChartCell.swift | 1 | 4684 | //
// PositiveNegativeBarChartCell.swift
// XJYChartDemo-Swift
//
// Created by Kelly Roach on 8/17/18.
// Copyright © 2018 JunyiXie. All rights reserved.
//
import UIKit
import XJYChart
class PositiveNegativeBarChartCell: UITableViewCell, XJYChartDelegate {
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
var itemArray: [AnyHashable] = []
let item1 = XBarItem(dataNumber: -80.93, color: Constants.XJYDarkBlue, dataDescribe: "test")
itemArray.append(item1!)
let item2 = XBarItem(dataNumber: -107.04, color: Constants.XJYDarkBlue, dataDescribe: "test")
itemArray.append(item2!)
let item3 = XBarItem(dataNumber: 77.99, color: Constants.XJYDarkBlue, dataDescribe: "test")
itemArray.append(item3!)
let item4 = XBarItem(dataNumber: 57.48, color: Constants.XJYDarkBlue, dataDescribe: "test")
itemArray.append(item4!)
let item5 = XBarItem(dataNumber: -89.91, color: Constants.XJYDarkBlue, dataDescribe: "test")
itemArray.append(item5!)
let item6 = XBarItem(dataNumber: 66.93, color: Constants.XJYDarkBlue, dataDescribe: "test")
itemArray.append(item6!)
let item7 = XBarItem(dataNumber: 7.04, color: Constants.XJYDarkBlue, dataDescribe: "test")
itemArray.append(item7!)
let item8 = XBarItem(dataNumber: -77.99, color: Constants.XJYDarkBlue, dataDescribe: "test")
itemArray.append(item8!)
let item9 = XBarItem(dataNumber: -28.48, color: Constants.XJYDarkBlue, dataDescribe: "test")
itemArray.append(item9!)
let item10 = XBarItem(dataNumber: 52.91, color: Constants.XJYDarkBlue, dataDescribe: "test")
itemArray.append(item10!)
//
let item11 = XBarItem(dataNumber: -0.93, color: Constants.XJYDarkBlue, dataDescribe: "test")
itemArray.append(item11!)
let item12 = XBarItem(dataNumber: -7.04, color: Constants.XJYDarkBlue, dataDescribe: "test")
itemArray.append(item12!)
let item13 = XBarItem(dataNumber: 44.99, color: Constants.XJYDarkBlue, dataDescribe: "test")
itemArray.append(item13!)
let item14 = XBarItem(dataNumber: 28.48, color: Constants.XJYDarkBlue, dataDescribe: "test")
itemArray.append(item14!)
let item15 = XBarItem(dataNumber: -52.91, color: Constants.XJYDarkBlue, dataDescribe: "test")
itemArray.append(item15!)
let item16 = XBarItem(dataNumber: 0.93, color: Constants.XJYDarkBlue, dataDescribe: "test")
itemArray.append(item16!)
let item17 = XBarItem(dataNumber: 77.04, color: Constants.XJYDarkBlue, dataDescribe: "test")
itemArray.append(item17!)
let item18 = XBarItem(dataNumber: 4.99, color: Constants.XJYDarkBlue, dataDescribe: "test")
itemArray.append(item18!)
let item19 = XBarItem(dataNumber: -28.48, color: Constants.XJYDarkBlue, dataDescribe: "test")
itemArray.append(item19!)
let item20 = XBarItem(dataNumber: 52.91, color: Constants.XJYDarkBlue, dataDescribe: "test")
itemArray.append(item20!)
let item21 = XBarItem(dataNumber: 0.93, color: Constants.XJYDarkBlue, dataDescribe: "test")
itemArray.append(item21!)
let item22 = XBarItem(dataNumber: 7.04, color: Constants.XJYDarkBlue, dataDescribe: "test")
itemArray.append(item22!)
let item23 = XBarItem(dataNumber: 4.99, color: Constants.XJYDarkBlue, dataDescribe: "test")
itemArray.append(item23!)
let item24 = XBarItem(dataNumber: 44.48, color: Constants.XJYDarkBlue, dataDescribe: "test")
itemArray.append(item24!)
let item25 = XBarItem(dataNumber: 52.91, color: Constants.XJYDarkBlue, dataDescribe: "test")
itemArray.append(item25!)
let barChart = XPositiveNegativeBarChart(frame: CGRect(x: 0, y: 0, width: 375, height: 200), dataItemArray: NSMutableArray(array: itemArray), topNumber: 100, bottomNumber: -170)
barChart!.barChartDelegate = self
contentView.addSubview(barChart!)
selectionStyle = UITableViewCellSelectionStyle.none
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func userClickedOnBar(at idx: Int) {
print("XBarChartDelegate touch Bat At idx \(idx)")
}
}
| mit | 9cbb79666bddef6358ac22b3f54c5e4c | 49.902174 | 185 | 0.681614 | 3.725537 | false | true | false | false |
YOCKOW/SwiftCGIResponder | Sources/CGIResponder/CGIContent.swift | 1 | 3703 | /* *************************************************************************************************
CGIContent.swift
© 2017-2018, 2020 YOCKOW.
Licensed under MIT License.
See "LICENSE.txt" for more information.
************************************************************************************************ */
import Foundation
#if canImport(FoundationXML)
import FoundationXML
#endif
import TemporaryFile
import XHTML
import yExtensions
/// A content to be output via CGI.
public enum CGIContent {
/// No content will be put out.
case none
case data(Data)
public init(data:Data) { self = .data(data) }
case fileHandle(FileHandle)
public init(fileHandle:FileHandle) { self = .fileHandle(fileHandle) }
case temporaryFile(TemporaryFile)
public init(temporaryFile: TemporaryFile) { self = .temporaryFile(temporaryFile) }
case path(String)
public init(fileAtPath path:String) { self = .path(path) }
case string(String, encoding:String.Encoding)
public init(string:String, encoding:String.Encoding = .utf8) { self = .string(string, encoding:encoding) }
case url(URL)
public init(url:URL) { self = .url(url) }
case xhtml(XHTMLDocument)
public init(xhtml document:XHTMLDocument) { self = .xhtml(document) }
case xml(XMLDocument, options: XMLNode.Options)
public init(xml document: XMLDocument, options: XMLNode.Options = []) { self = .xml(document, options: options) }
case lazy(() throws -> CGIContent)
public init(creator: @escaping () throws -> CGIContent) { self = .lazy(creator) }
}
extension CGIContent {
/// Determine the content type
internal var _defaultContentType: ContentType {
let octetStreamContentType = ContentType(type:.application, subtype:"octet-stream")!
func _parameters(encoding: String.Encoding) -> ContentType.Parameters? {
guard let charset = encoding.ianaCharacterSetName else { return nil }
return ["charset": charset]
}
func _contentType(pathExtension: String,
parameters: ContentType.Parameters? = nil) -> ContentType
{
return ContentType.PathExtension(rawValue:pathExtension).flatMap {
ContentType(pathExtension:$0, parameters: parameters)
} ?? octetStreamContentType
}
switch self {
case .path(let path):
guard
let indexAfterDot = path.lastIndex(of: ".").flatMap(path.index(after:)),
indexAfterDot < path.endIndex
else {
return octetStreamContentType
}
return _contentType(pathExtension: String(path[indexAfterDot..<path.endIndex]))
case .string(_, encoding: let encoding):
return ContentType(pathExtension: .txt, parameters: _parameters(encoding: encoding))!
case .url(let url):
return _contentType(pathExtension: url.pathExtension)
case .xhtml(let document):
let encoding = document.prolog.stringEncoding
return ContentType(pathExtension: .xhtml, parameters: _parameters(encoding: encoding))!
case .xml(let document, _):
if let encodingString = document.characterEncoding,
let type = ContentType(pathExtension: .xml, parameters: ["charset": encodingString]) {
return type
}
return ContentType(pathExtension: .xml)!
default:
return octetStreamContentType
}
}
internal var _stringEncoding: String.Encoding? {
switch self {
case .string(_, encoding: let encoding):
return encoding
case .xhtml(let document):
return document.prolog.stringEncoding
case .xml(let document, _):
return document.characterEncoding.flatMap({ String.Encoding(ianaCharacterSetName: $0) })
default:
return nil
}
}
}
| mit | 000e71803a316a51e27c69389da3b0eb | 33.924528 | 115 | 0.650999 | 4.61596 | false | false | false | false |
ishkawa/APIKit | Sources/APIKit/SessionAdapter/URLSessionAdapter.swift | 1 | 3275 | import Foundation
extension URLSessionTask: SessionTask {
}
private var dataTaskResponseBufferKey = 0
private var taskAssociatedObjectCompletionHandlerKey = 0
/// `URLSessionAdapter` connects `URLSession` with `Session`.
///
/// If you want to add custom behavior of `URLSession` by implementing delegate methods defined in
/// `URLSessionDelegate` and related protocols, define a subclass of `URLSessionAdapter` and implement
/// delegate methods that you want to implement. Since `URLSessionAdapter` also implements delegate methods
/// `URLSession(_:task: didCompleteWithError:)` and `URLSession(_:dataTask:didReceiveData:)`, you have to call
/// `super` in these methods if you implement them.
open class URLSessionAdapter: NSObject, SessionAdapter, URLSessionDelegate, URLSessionTaskDelegate, URLSessionDataDelegate {
/// The underlying `URLSession` instance.
open var urlSession: URLSession!
/// Returns `URLSessionAdapter` initialized with `URLSessionConfiguration`.
public init(configuration: URLSessionConfiguration) {
super.init()
self.urlSession = URLSession(configuration: configuration, delegate: self, delegateQueue: nil)
}
/// Creates `URLSessionDataTask` instance using `dataTaskWithRequest(_:completionHandler:)`.
open func createTask(with URLRequest: URLRequest, handler: @escaping (Data?, URLResponse?, Error?) -> Void) -> SessionTask {
let task = urlSession.dataTask(with: URLRequest)
setBuffer(NSMutableData(), forTask: task)
setHandler(handler, forTask: task)
return task
}
/// Aggregates `URLSessionTask` instances in `URLSession` using `getTasksWithCompletionHandler(_:)`.
open func getTasks(with handler: @escaping ([SessionTask]) -> Void) {
urlSession.getTasksWithCompletionHandler { dataTasks, uploadTasks, downloadTasks in
let allTasks: [URLSessionTask] = dataTasks + uploadTasks + downloadTasks
handler(allTasks)
}
}
private func setBuffer(_ buffer: NSMutableData, forTask task: URLSessionTask) {
objc_setAssociatedObject(task, &dataTaskResponseBufferKey, buffer, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
private func buffer(for task: URLSessionTask) -> NSMutableData? {
return objc_getAssociatedObject(task, &dataTaskResponseBufferKey) as? NSMutableData
}
private func setHandler(_ handler: @escaping (Data?, URLResponse?, Error?) -> Void, forTask task: URLSessionTask) {
objc_setAssociatedObject(task, &taskAssociatedObjectCompletionHandlerKey, handler as Any, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
private func handler(for task: URLSessionTask) -> ((Data?, URLResponse?, Error?) -> Void)? {
return objc_getAssociatedObject(task, &taskAssociatedObjectCompletionHandlerKey) as? (Data?, URLResponse?, Error?) -> Void
}
// MARK: URLSessionTaskDelegate
open func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
handler(for: task)?(buffer(for: task) as Data?, task.response, error)
}
// MARK: URLSessionDataDelegate
open func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) {
buffer(for: dataTask)?.append(data)
}
}
| mit | 1fe44bfc1b0a61118ead64440778e6d1 | 45.785714 | 133 | 0.729466 | 5.141287 | false | true | false | false |
tbaranes/SwiftyUtils | Sources/Others/macOS/SystemUtility.swift | 1 | 3191 | //
// SystemUtility.swift
// SwiftyUtils
//
// Created by Michael Redig on 2/11/19.
// Copyright © 2019 Tom Baranes. All rights reserved.
//
import Foundation
#if os(macOS)
public typealias ShellOutput = (returnCode: Int32, stdOut: String, stdError: String)
public typealias ShellArrayOutput = (returnCode: Int32, stdOut: [String], stdError: [String])
public enum SystemUtility {
/// Runs a command on a system shell and provides the return code for success, STDOUT, and STDERR.
/// - Parameters:
/// - args: An array starting with the command and any following arguments as separate `Strings` in the array.
/// - launchPath: path the base executable. Defaults value is `"/usr/bin/env"` and can be ignored in most cases.
/// - Returns: Tuple with the following structure: `(returnCode: Int32, stdOut: String, stdError: String)`
///
/// Usage example:
/// ```
/// let (rCode, stdOut, stdErr) = SystemUtility.shell(["ls", "-l", "/"])
/// // rCode = 0 (which is "true" in shell)
/// // stdOut = "total 13\ndrwxrwxr-x+ 91 root admin 2912 Feb 11 01:24 Applications" ... etc
/// // stdErr = ""
/// ```
public static func shell(_ args: [String], _ launchPath: String = "/usr/bin/env") -> ShellOutput {
let task = Process()
task.launchPath = launchPath
task.arguments = args
let pipeOut = Pipe()
let pipeError = Pipe()
task.standardOutput = pipeOut
task.standardError = pipeError
task.launch()
task.waitUntilExit()
let dataOut = pipeOut.fileHandleForReading.readDataToEndOfFile()
let stdOut = String(data: dataOut, encoding: .utf8) ?? ""
let dataError = pipeError.fileHandleForReading.readDataToEndOfFile()
let stdError = String(data: dataError, encoding: .utf8) ?? ""
let rCode = task.terminationStatus
return (rCode, stdOut, stdError)
}
/// Runs a command on a system shell and provides the return code for success, STDOUT, and STDERR.
/// The returned information is separated into an array of Strings separated by newlines.
/// - Parameters:
/// - args: An array starting with the command and any following arguments as separate Strings in the array.
/// - launchPath: path the base executable. Default value is `"/usr/bin/env"` and can be ignored in most cases.
/// - Returns: tuple with the following structure: `(returnCode: Int32, stdOut: [String], stdError: [String])`
///
/// Usage example:
/// ```
/// let (rCode, stdOut, stdErr) = SystemUtility.shellArrayOut(["ls", "-l", "/"])
/// // rCode = 0 (which is "true" in shell)
/// // stdOut = ["total 13", "drwxrwxr-x+ 91 root admin 2912 Feb 11 01:24 Applications" ... etc]
/// // stdErr = [""]
/// ```
public static func shellArrayOut(_ args: [String], _ launchPath: String = "/usr/bin/env") -> ShellArrayOutput {
let (rCode, stdOut, stdErr) = shell(args, launchPath)
let output = stdOut.split(separator: "\n").map { String($0) }
let error = stdErr.split(separator: "\n").map { String($0) }
return (rCode, output, error)
}
}
#endif
| mit | 5f8538737995a9a0a4eb34f04558103b | 42.108108 | 119 | 0.631034 | 3.871359 | false | false | false | false |
ztmdsbt/tw-ios-training | storyboard-and-autolayout/json-data/Pods/Kingfisher/Kingfisher/UIImageView+Kingfisher.swift | 2 | 7991 | //
// UIImageView+Kingfisher.swift
// Kingfisher
//
// Created by Wei Wang on 15/4/6.
//
// Copyright (c) 2015 Wei Wang <[email protected]>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
// MARK: - Set Images
/**
* Set image to use from web.
*/
public extension UIImageView {
/**
Set an image with a URL.
It will ask for Kingfisher's manager to get the image for the URL.
The memory and disk will be searched first. If the manager does not find it, it will try to download the image at this URL and store it for next use.
:param: URL The URL of image.
:returns: A task represents the retriving process.
*/
public func kf_setImageWithURL(URL: NSURL) -> RetrieveImageTask
{
return kf_setImageWithURL(URL, placeholderImage: nil, optionsInfo: nil, progressBlock: nil, completionHandler: nil)
}
/**
Set an image with a URL and a placeholder image.
:param: URL The URL of image.
:param: placeholderImage A placeholder image when retrieving the image at URL.
:returns: A task represents the retriving process.
*/
public func kf_setImageWithURL(URL: NSURL,
placeholderImage: UIImage?) -> RetrieveImageTask
{
return kf_setImageWithURL(URL, placeholderImage: placeholderImage, optionsInfo: nil, progressBlock: nil, completionHandler: nil)
}
/**
Set an image with a URL, a placaholder image and options.
:param: URL The URL of image.
:param: placeholderImage A placeholder image when retrieving the image at URL.
:param: optionsInfo A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more.
:returns: A task represents the retriving process.
*/
public func kf_setImageWithURL(URL: NSURL,
placeholderImage: UIImage?,
optionsInfo: KingfisherOptionsInfo?) -> RetrieveImageTask
{
return kf_setImageWithURL(URL, placeholderImage: placeholderImage, optionsInfo: optionsInfo, progressBlock: nil, completionHandler: nil)
}
/**
Set an image with a URL, a placeholder image, options and completion handler.
:param: URL The URL of image.
:param: placeholderImage A placeholder image when retrieving the image at URL.
:param: optionsInfo A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more.
:param: completionHandler Called when the image retrieved and set.
:returns: A task represents the retriving process.
*/
public func kf_setImageWithURL(URL: NSURL,
placeholderImage: UIImage?,
optionsInfo: KingfisherOptionsInfo?,
completionHandler: CompletionHandler?) -> RetrieveImageTask
{
return kf_setImageWithURL(URL, placeholderImage: placeholderImage, optionsInfo: optionsInfo, progressBlock: nil, completionHandler: completionHandler)
}
/**
Set an image with a URL, a placeholder image, options, progress handler and completion handler.
:param: URL The URL of image.
:param: placeholderImage A placeholder image when retrieving the image at URL.
:param: optionsInfo A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more.
:param: progressBlock Called when the image downloading progress gets updated.
:param: completionHandler Called when the image retrieved and set.
:returns: A task represents the retriving process.
*/
public func kf_setImageWithURL(URL: NSURL,
placeholderImage: UIImage?,
optionsInfo: KingfisherOptionsInfo?,
progressBlock: DownloadProgressBlock?,
completionHandler: CompletionHandler?) -> RetrieveImageTask
{
image = placeholderImage
kf_setWebURL(URL)
let task = KingfisherManager.sharedManager.retrieveImageWithURL(URL, optionsInfo: optionsInfo, progressBlock: { (receivedSize, totalSize) -> () in
if let progressBlock = progressBlock {
dispatch_async(dispatch_get_main_queue(), { () -> Void in
progressBlock(receivedSize: receivedSize, totalSize: totalSize)
})
}
}) { (image, error, cacheType, imageURL) -> () in
dispatch_async(dispatch_get_main_queue(), { () -> Void in
if (imageURL == self.kf_webURL && image != nil) {
self.image = image;
}
completionHandler?(image: image, error: error, cacheType:cacheType, imageURL: imageURL)
})
}
return task
}
}
// MARK: - Associated Object
private var lastURLkey: Void?
public extension UIImageView {
/// Get the image URL binded to this image view.
public var kf_webURL: NSURL? {
get {
return objc_getAssociatedObject(self, &lastURLkey) as? NSURL
}
}
private func kf_setWebURL(URL: NSURL) {
objc_setAssociatedObject(self, &lastURLkey, URL, UInt(OBJC_ASSOCIATION_RETAIN_NONATOMIC))
}
}
// MARK: - Deprecated
public extension UIImageView {
@availability(*, deprecated=1.2, message="Use -kf_setImageWithURL:placeholderImage:optionsInfo: instead.")
public func kf_setImageWithURL(URL: NSURL,
placeholderImage: UIImage?,
options: KingfisherOptions) -> RetrieveImageTask
{
return kf_setImageWithURL(URL, placeholderImage: placeholderImage, optionsInfo: [.Options: options], progressBlock: nil, completionHandler: nil)
}
@availability(*, deprecated=1.2, message="Use -kf_setImageWithURL:placeholderImage:optionsInfo:completionHandler: instead.")
public func kf_setImageWithURL(URL: NSURL,
placeholderImage: UIImage?,
options: KingfisherOptions,
completionHandler: CompletionHandler?) -> RetrieveImageTask
{
return kf_setImageWithURL(URL, placeholderImage: placeholderImage, optionsInfo: [.Options: options], progressBlock: nil, completionHandler: completionHandler)
}
@availability(*, deprecated=1.2, message="Use -kf_setImageWithURL:placeholderImage:optionsInfo:progressBlock:completionHandler: instead.")
public func kf_setImageWithURL(URL: NSURL,
placeholderImage: UIImage?,
options: KingfisherOptions,
progressBlock: DownloadProgressBlock?,
completionHandler: CompletionHandler?) -> RetrieveImageTask
{
return kf_setImageWithURL(URL, placeholderImage: placeholderImage, optionsInfo: [.Options: options], progressBlock: progressBlock, completionHandler: completionHandler)
}
}
| gpl-2.0 | 3cab1e86cdc2760a36aaf1878c93ebc6 | 43.394444 | 176 | 0.661744 | 5.288551 | false | false | false | false |
Zewo/Core | Tests/AxisTests/Map/MapTests.swift | 2 | 36858 | import XCTest
@testable import Axis
public class MapTests : XCTestCase {
func testCreation() {
let nullValue: Bool? = nil
let null = Map(nullValue)
XCTAssertEqual(null, nil)
XCTAssertEqual(null, .null)
XCTAssert(null.isNull)
XCTAssertFalse(null.isBool)
XCTAssertFalse(null.isDouble)
XCTAssertFalse(null.isInt)
XCTAssertFalse(null.isString)
XCTAssertFalse(null.isBuffer)
XCTAssertFalse(null.isArray)
XCTAssertFalse(null.isDictionary)
XCTAssertNil(null.bool)
XCTAssertNil(null.double)
XCTAssertNil(null.int)
XCTAssertNil(null.string)
XCTAssertNil(null.buffer)
XCTAssertNil(null.array)
XCTAssertNil(null.dictionary)
XCTAssertThrowsError(try null.asBool())
XCTAssertThrowsError(try null.asDouble())
XCTAssertThrowsError(try null.asInt())
XCTAssertThrowsError(try null.asString())
XCTAssertThrowsError(try null.asBuffer())
XCTAssertThrowsError(try null.asArray(converting: false))
XCTAssertThrowsError(try null.asDictionary())
let nullArrayValue: [Bool]? = nil
let nullArray = Map(nullArrayValue)
XCTAssertEqual(nullArray, nil)
XCTAssertEqual(nullArray, .null)
XCTAssert(nullArray.isNull)
XCTAssertFalse(nullArray.isBool)
XCTAssertFalse(nullArray.isDouble)
XCTAssertFalse(nullArray.isInt)
XCTAssertFalse(nullArray.isString)
XCTAssertFalse(nullArray.isBuffer)
XCTAssertFalse(nullArray.isArray)
XCTAssertFalse(nullArray.isDictionary)
XCTAssertNil(nullArray.bool)
XCTAssertNil(nullArray.double)
XCTAssertNil(nullArray.int)
XCTAssertNil(nullArray.string)
XCTAssertNil(nullArray.buffer)
XCTAssertNil(nullArray.array)
XCTAssertNil(nullArray.dictionary)
XCTAssertThrowsError(try null.asBool())
XCTAssertThrowsError(try null.asDouble())
XCTAssertThrowsError(try null.asInt())
XCTAssertThrowsError(try null.asString())
XCTAssertThrowsError(try null.asBuffer())
XCTAssertThrowsError(try null.asArray(converting: false))
XCTAssertThrowsError(try null.asDictionary())
let nullArrayOfNullValue: [Bool?]? = nil
let nullArrayOfNull = Map(nullArrayOfNullValue)
XCTAssertEqual(nullArrayOfNull, nil)
XCTAssertEqual(nullArrayOfNull, .null)
XCTAssert(nullArrayOfNull.isNull)
XCTAssertFalse(nullArrayOfNull.isBool)
XCTAssertFalse(nullArrayOfNull.isDouble)
XCTAssertFalse(nullArrayOfNull.isInt)
XCTAssertFalse(nullArrayOfNull.isString)
XCTAssertFalse(nullArrayOfNull.isBuffer)
XCTAssertFalse(nullArrayOfNull.isArray)
XCTAssertFalse(nullArrayOfNull.isDictionary)
XCTAssertNil(nullArrayOfNull.bool)
XCTAssertNil(nullArrayOfNull.double)
XCTAssertNil(nullArrayOfNull.int)
XCTAssertNil(nullArrayOfNull.string)
XCTAssertNil(nullArrayOfNull.buffer)
XCTAssertNil(nullArrayOfNull.array)
XCTAssertNil(nullArrayOfNull.dictionary)
XCTAssertThrowsError(try null.asBool())
XCTAssertThrowsError(try null.asDouble())
XCTAssertThrowsError(try null.asInt())
XCTAssertThrowsError(try null.asString())
XCTAssertThrowsError(try null.asBuffer())
XCTAssertThrowsError(try null.asArray(converting: false))
XCTAssertThrowsError(try null.asDictionary())
let nullDictionaryValue: [String: Bool]? = nil
let nullDictionary = Map(nullDictionaryValue)
XCTAssertEqual(nullDictionary, nil)
XCTAssertEqual(nullDictionary, .null)
XCTAssert(nullDictionary.isNull)
XCTAssertFalse(nullDictionary.isBool)
XCTAssertFalse(nullDictionary.isDouble)
XCTAssertFalse(nullDictionary.isInt)
XCTAssertFalse(nullDictionary.isString)
XCTAssertFalse(nullDictionary.isBuffer)
XCTAssertFalse(nullDictionary.isArray)
XCTAssertFalse(nullDictionary.isDictionary)
XCTAssertNil(nullDictionary.bool)
XCTAssertNil(nullDictionary.double)
XCTAssertNil(nullDictionary.int)
XCTAssertNil(nullDictionary.string)
XCTAssertNil(nullDictionary.buffer)
XCTAssertNil(nullDictionary.array)
XCTAssertNil(nullDictionary.dictionary)
XCTAssertThrowsError(try null.asBool())
XCTAssertThrowsError(try null.asDouble())
XCTAssertThrowsError(try null.asInt())
XCTAssertThrowsError(try null.asString())
XCTAssertThrowsError(try null.asBuffer())
XCTAssertThrowsError(try null.asArray(converting: false))
XCTAssertThrowsError(try null.asDictionary())
let nullDictionaryOfNullValue: [String: Bool?]? = nil
let nullDictionaryOfNull = Map(nullDictionaryOfNullValue)
XCTAssertEqual(nullDictionaryOfNull, nil)
XCTAssertEqual(nullDictionaryOfNull, .null)
XCTAssert(nullDictionaryOfNull.isNull)
XCTAssertFalse(nullDictionaryOfNull.isBool)
XCTAssertFalse(nullDictionaryOfNull.isDouble)
XCTAssertFalse(nullDictionaryOfNull.isInt)
XCTAssertFalse(nullDictionaryOfNull.isString)
XCTAssertFalse(nullDictionaryOfNull.isBuffer)
XCTAssertFalse(nullDictionaryOfNull.isArray)
XCTAssertFalse(nullDictionaryOfNull.isDictionary)
XCTAssertNil(nullDictionaryOfNull.bool)
XCTAssertNil(nullDictionaryOfNull.double)
XCTAssertNil(nullDictionaryOfNull.int)
XCTAssertNil(nullDictionaryOfNull.string)
XCTAssertNil(nullDictionaryOfNull.buffer)
XCTAssertNil(nullDictionaryOfNull.array)
XCTAssertNil(nullDictionaryOfNull.dictionary)
XCTAssertThrowsError(try null.asBool())
XCTAssertThrowsError(try null.asDouble())
XCTAssertThrowsError(try null.asInt())
XCTAssertThrowsError(try null.asString())
XCTAssertThrowsError(try null.asBuffer())
XCTAssertThrowsError(try null.asArray(converting: false))
XCTAssertThrowsError(try null.asDictionary())
let boolValue = true
let bool = Map(boolValue)
XCTAssertEqual(bool, true)
XCTAssertEqual(bool, .bool(boolValue))
XCTAssertFalse(bool.isNull)
XCTAssert(bool.isBool)
XCTAssertFalse(bool.isDouble)
XCTAssertFalse(bool.isInt)
XCTAssertFalse(bool.isString)
XCTAssertFalse(bool.isBuffer)
XCTAssertFalse(bool.isArray)
XCTAssertFalse(bool.isDictionary)
XCTAssertEqual(bool.bool, boolValue)
XCTAssertNil(bool.double)
XCTAssertNil(bool.int)
XCTAssertNil(bool.string)
XCTAssertNil(bool.buffer)
XCTAssertNil(bool.array)
XCTAssertNil(bool.dictionary)
XCTAssertEqual(try bool.asBool(), boolValue)
XCTAssertThrowsError(try bool.asDouble())
XCTAssertThrowsError(try bool.asInt())
XCTAssertThrowsError(try bool.asString())
XCTAssertThrowsError(try bool.asBuffer())
XCTAssertThrowsError(try bool.asArray(converting: false))
XCTAssertThrowsError(try bool.asDictionary())
let doubleValue = 4.20
let double = Map(doubleValue)
XCTAssertEqual(double, 4.20)
XCTAssertEqual(double, .double(doubleValue))
XCTAssertFalse(double.isNull)
XCTAssertFalse(double.isBool)
XCTAssert(double.isDouble)
XCTAssertFalse(double.isInt)
XCTAssertFalse(double.isString)
XCTAssertFalse(double.isBuffer)
XCTAssertFalse(double.isArray)
XCTAssertFalse(double.isDictionary)
XCTAssertNil(double.bool)
XCTAssertEqual(double.double, doubleValue)
XCTAssertNil(double.int)
XCTAssertNil(double.string)
XCTAssertNil(double.buffer)
XCTAssertNil(double.array)
XCTAssertNil(double.dictionary)
XCTAssertThrowsError(try double.asBool())
XCTAssertEqual(try double.asDouble(), doubleValue)
XCTAssertThrowsError(try double.asInt())
XCTAssertThrowsError(try double.asString())
XCTAssertThrowsError(try double.asBuffer())
XCTAssertThrowsError(try double.asArray(converting: false))
XCTAssertThrowsError(try double.asDictionary())
let intValue = 1969
let int = Map(intValue)
XCTAssertEqual(int, 1969)
XCTAssertEqual(int, .int(intValue))
XCTAssertFalse(int.isNull)
XCTAssertFalse(int.isBool)
XCTAssertFalse(int.isDouble)
XCTAssert(int.isInt)
XCTAssertFalse(int.isString)
XCTAssertFalse(int.isBuffer)
XCTAssertFalse(int.isArray)
XCTAssertFalse(int.isDictionary)
XCTAssertNil(int.bool)
XCTAssertNil(int.double)
XCTAssertEqual(int.int, intValue)
XCTAssertNil(int.string)
XCTAssertNil(int.buffer)
XCTAssertNil(int.array)
XCTAssertNil(int.dictionary)
XCTAssertThrowsError(try null.asBool())
XCTAssertThrowsError(try null.asDouble())
XCTAssertEqual(try int.asInt(), intValue)
XCTAssertThrowsError(try null.asString())
XCTAssertThrowsError(try null.asBuffer())
XCTAssertThrowsError(try null.asArray(converting: false))
XCTAssertThrowsError(try null.asDictionary())
let stringValue = "foo"
let string = Map(stringValue)
XCTAssertEqual(string, "foo")
XCTAssertEqual(string, .string(stringValue))
XCTAssertFalse(string.isNull)
XCTAssertFalse(string.isBool)
XCTAssertFalse(string.isDouble)
XCTAssertFalse(string.isInt)
XCTAssert(string.isString)
XCTAssertFalse(string.isBuffer)
XCTAssertFalse(string.isArray)
XCTAssertFalse(string.isDictionary)
XCTAssertNil(string.bool)
XCTAssertNil(string.double)
XCTAssertNil(string.int)
XCTAssertEqual(string.string, stringValue)
XCTAssertNil(string.buffer)
XCTAssertNil(string.array)
XCTAssertNil(string.dictionary)
XCTAssertThrowsError(try string.asBool())
XCTAssertThrowsError(try string.asDouble())
XCTAssertThrowsError(try string.asInt())
XCTAssertEqual(try string.asString(), stringValue)
XCTAssertThrowsError(try string.asBuffer())
XCTAssertThrowsError(try string.asArray(converting: false))
XCTAssertThrowsError(try string.asDictionary())
let bufferValue = Buffer("foo")
let buffer = Map(bufferValue)
XCTAssertEqual(buffer, .buffer(bufferValue))
XCTAssertFalse(buffer.isNull)
XCTAssertFalse(buffer.isBool)
XCTAssertFalse(buffer.isDouble)
XCTAssertFalse(buffer.isInt)
XCTAssertFalse(buffer.isString)
XCTAssert(buffer.isBuffer)
XCTAssertFalse(buffer.isArray)
XCTAssertFalse(buffer.isDictionary)
XCTAssertNil(buffer.bool)
XCTAssertNil(buffer.double)
XCTAssertNil(buffer.int)
XCTAssertNil(buffer.string)
XCTAssertEqual(buffer.buffer, bufferValue)
XCTAssertNil(buffer.array)
XCTAssertNil(buffer.dictionary)
XCTAssertThrowsError(try buffer.asBool())
XCTAssertThrowsError(try buffer.asDouble())
XCTAssertThrowsError(try buffer.asInt())
XCTAssertThrowsError(try buffer.asString())
XCTAssertEqual(try buffer.asBuffer(), bufferValue)
XCTAssertThrowsError(try buffer.asArray(converting: false))
XCTAssertThrowsError(try buffer.asDictionary())
let arrayValue = 1969
let array = Map([arrayValue])
XCTAssertEqual(array, [1969])
XCTAssertEqual(array, .array([.int(arrayValue)]))
XCTAssertFalse(array.isNull)
XCTAssertFalse(array.isBool)
XCTAssertFalse(array.isDouble)
XCTAssertFalse(array.isInt)
XCTAssertFalse(array.isString)
XCTAssertFalse(array.isBuffer)
XCTAssert(array.isArray)
XCTAssertFalse(array.isDictionary)
XCTAssertNil(array.bool)
XCTAssertNil(array.double)
XCTAssertNil(array.int)
XCTAssertNil(array.string)
XCTAssertNil(array.buffer)
if let a = array.array {
XCTAssertEqual(a, [.int(arrayValue)])
} else {
XCTAssertNotNil(array.array)
}
XCTAssertNil(array.dictionary)
XCTAssertThrowsError(try array.asBool())
XCTAssertThrowsError(try array.asDouble())
XCTAssertThrowsError(try array.asInt())
XCTAssertThrowsError(try array.asString())
XCTAssertThrowsError(try array.asBuffer())
XCTAssertEqual(try array.asArray(), [.int(arrayValue)])
XCTAssertThrowsError(try array.asDictionary())
let arrayOfOptionalValue: Int? = arrayValue
let arrayOfOptional = Map([arrayOfOptionalValue])
XCTAssertEqual(arrayOfOptional, [1969])
XCTAssertEqual(arrayOfOptional, .array([.int(arrayValue)]))
XCTAssertFalse(arrayOfOptional.isNull)
XCTAssertFalse(arrayOfOptional.isBool)
XCTAssertFalse(arrayOfOptional.isDouble)
XCTAssertFalse(arrayOfOptional.isInt)
XCTAssertFalse(arrayOfOptional.isString)
XCTAssertFalse(arrayOfOptional.isBuffer)
XCTAssert(arrayOfOptional.isArray)
XCTAssertFalse(arrayOfOptional.isDictionary)
XCTAssertNil(arrayOfOptional.bool)
XCTAssertNil(arrayOfOptional.double)
XCTAssertNil(arrayOfOptional.int)
XCTAssertNil(arrayOfOptional.string)
XCTAssertNil(arrayOfOptional.buffer)
if let a = arrayOfOptional.array {
XCTAssertEqual(a, [.int(arrayValue)])
} else {
XCTAssertNotNil(arrayOfOptional.array)
}
XCTAssertNil(arrayOfOptional.dictionary)
XCTAssertThrowsError(try arrayOfOptional.asBool())
XCTAssertThrowsError(try arrayOfOptional.asDouble())
XCTAssertThrowsError(try arrayOfOptional.asInt())
XCTAssertThrowsError(try arrayOfOptional.asString())
XCTAssertThrowsError(try arrayOfOptional.asBuffer())
XCTAssertEqual(try arrayOfOptional.asArray(), [.int(arrayValue)])
XCTAssertThrowsError(try arrayOfOptional.asDictionary())
let arrayOfNullValue: Int? = nil
let arrayOfNull = Map([arrayOfNullValue])
XCTAssertEqual(arrayOfNull, [nil])
XCTAssertEqual(arrayOfNull, .array([.null]))
XCTAssertFalse(arrayOfNull.isNull)
XCTAssertFalse(arrayOfNull.isBool)
XCTAssertFalse(arrayOfNull.isDouble)
XCTAssertFalse(arrayOfNull.isInt)
XCTAssertFalse(arrayOfNull.isString)
XCTAssertFalse(arrayOfNull.isBuffer)
XCTAssert(arrayOfNull.isArray)
XCTAssertFalse(arrayOfNull.isDictionary)
XCTAssertNil(arrayOfNull.bool)
XCTAssertNil(arrayOfNull.double)
XCTAssertNil(arrayOfNull.int)
XCTAssertNil(arrayOfNull.string)
XCTAssertNil(arrayOfNull.buffer)
if let a = arrayOfNull.array {
XCTAssertEqual(a, [.null])
} else {
XCTAssertNotNil(arrayOfNull.array)
}
XCTAssertNil(arrayOfNull.dictionary)
XCTAssertThrowsError(try arrayOfNull.asBool())
XCTAssertThrowsError(try arrayOfNull.asDouble())
XCTAssertThrowsError(try arrayOfNull.asInt())
XCTAssertThrowsError(try arrayOfNull.asString())
XCTAssertThrowsError(try arrayOfNull.asBuffer())
XCTAssertEqual(try arrayOfNull.asArray(), [.null])
XCTAssertThrowsError(try arrayOfNull.asDictionary())
let dictionaryValue = 1969
let dictionary = Map(["foo": dictionaryValue])
XCTAssertEqual(dictionary, ["foo": 1969])
XCTAssertEqual(dictionary, .dictionary(["foo": .int(dictionaryValue)]))
XCTAssertFalse(dictionary.isNull)
XCTAssertFalse(dictionary.isBool)
XCTAssertFalse(dictionary.isDouble)
XCTAssertFalse(dictionary.isInt)
XCTAssertFalse(dictionary.isString)
XCTAssertFalse(dictionary.isBuffer)
XCTAssertFalse(dictionary.isArray)
XCTAssert(dictionary.isDictionary)
XCTAssertNil(dictionary.bool)
XCTAssertNil(dictionary.double)
XCTAssertNil(dictionary.int)
XCTAssertNil(dictionary.string)
XCTAssertNil(dictionary.buffer)
XCTAssertNil(dictionary.array)
if let d = dictionary.dictionary {
XCTAssertEqual(d, ["foo": .int(dictionaryValue)])
} else {
XCTAssertNotNil(dictionary.dictionary)
}
XCTAssertThrowsError(try dictionary.asBool())
XCTAssertThrowsError(try dictionary.asDouble())
XCTAssertThrowsError(try dictionary.asInt())
XCTAssertThrowsError(try dictionary.asString())
XCTAssertThrowsError(try dictionary.asBuffer())
XCTAssertThrowsError(try dictionary.asArray(converting: false))
XCTAssertEqual(try dictionary.asDictionary(), ["foo": .int(dictionaryValue)])
let dictionaryOfOptionalValue: Int? = dictionaryValue
let dictionaryOfOptional = Map(["foo": dictionaryOfOptionalValue])
XCTAssertEqual(dictionaryOfOptional, ["foo": 1969])
XCTAssertEqual(dictionaryOfOptional, .dictionary(["foo": .int(dictionaryValue)]))
XCTAssertFalse(dictionaryOfOptional.isNull)
XCTAssertFalse(dictionaryOfOptional.isBool)
XCTAssertFalse(dictionaryOfOptional.isDouble)
XCTAssertFalse(dictionaryOfOptional.isInt)
XCTAssertFalse(dictionaryOfOptional.isString)
XCTAssertFalse(dictionaryOfOptional.isBuffer)
XCTAssertFalse(dictionaryOfOptional.isArray)
XCTAssert(dictionaryOfOptional.isDictionary)
XCTAssertNil(dictionaryOfOptional.bool)
XCTAssertNil(dictionaryOfOptional.double)
XCTAssertNil(dictionaryOfOptional.int)
XCTAssertNil(dictionaryOfOptional.string)
XCTAssertNil(dictionaryOfOptional.buffer)
XCTAssertNil(dictionaryOfOptional.array)
if let d = dictionaryOfOptional.dictionary {
XCTAssertEqual(d, ["foo": .int(dictionaryValue)])
} else {
XCTAssertNotNil(dictionaryOfOptional.dictionary)
}
XCTAssertThrowsError(try dictionaryOfOptional.asBool())
XCTAssertThrowsError(try dictionaryOfOptional.asDouble())
XCTAssertThrowsError(try dictionaryOfOptional.asInt())
XCTAssertThrowsError(try dictionaryOfOptional.asString())
XCTAssertThrowsError(try dictionaryOfOptional.asBuffer())
XCTAssertThrowsError(try dictionaryOfOptional.asArray(converting: false))
XCTAssertEqual(try dictionaryOfOptional.asDictionary(), ["foo": .int(dictionaryValue)])
let dictionaryOfNullValue: Int? = nil
let dictionaryOfNull = Map(["foo": dictionaryOfNullValue])
XCTAssertEqual(dictionaryOfNull, ["foo": nil])
XCTAssertEqual(dictionaryOfNull, .dictionary(["foo": .null]))
XCTAssertFalse(dictionaryOfNull.isNull)
XCTAssertFalse(dictionaryOfNull.isBool)
XCTAssertFalse(dictionaryOfNull.isDouble)
XCTAssertFalse(dictionaryOfNull.isInt)
XCTAssertFalse(dictionaryOfNull.isString)
XCTAssertFalse(dictionaryOfNull.isBuffer)
XCTAssertFalse(dictionaryOfNull.isArray)
XCTAssert(dictionaryOfNull.isDictionary)
XCTAssertNil(dictionaryOfNull.bool)
XCTAssertNil(dictionaryOfNull.double)
XCTAssertNil(dictionaryOfNull.int)
XCTAssertNil(dictionaryOfNull.string)
XCTAssertNil(dictionaryOfNull.buffer)
XCTAssertNil(dictionaryOfNull.array)
if let d = dictionaryOfNull.dictionary {
XCTAssertEqual(d, ["foo": .null])
} else {
XCTAssertNotNil(dictionaryOfNull.dictionary)
}
XCTAssertThrowsError(try dictionaryOfNull.asBool())
XCTAssertThrowsError(try dictionaryOfNull.asDouble())
XCTAssertThrowsError(try dictionaryOfNull.asInt())
XCTAssertThrowsError(try dictionaryOfNull.asString())
XCTAssertThrowsError(try dictionaryOfNull.asBuffer())
XCTAssertThrowsError(try dictionaryOfNull.asArray(converting: false))
XCTAssertEqual(try dictionaryOfNull.asDictionary(), ["foo": .null])
}
func testConversion() {
let null: Map = nil
XCTAssertEqual(try null.asBool(converting: true), false)
XCTAssertEqual(try null.asDouble(converting: true), 0)
XCTAssertEqual(try null.asInt(converting: true), 0)
XCTAssertEqual(try null.asString(converting: true), "null")
XCTAssertEqual(try null.asBuffer(converting: true), Buffer())
XCTAssertEqual(try null.asArray(converting: true), [])
XCTAssertEqual(try null.asDictionary(converting: true), [:])
let `true`: Map = true
XCTAssertEqual(try `true`.asBool(converting: true), true)
XCTAssertEqual(try `true`.asDouble(converting: true), 1.0)
XCTAssertEqual(try `true`.asInt(converting: true), 1)
XCTAssertEqual(try `true`.asString(converting: true), "true")
XCTAssertEqual(try `true`.asBuffer(converting: true), Buffer([0xff]))
XCTAssertThrowsError(try `true`.asArray(converting: true))
XCTAssertThrowsError(try `true`.asDictionary(converting: true))
let `false`: Map = false
XCTAssertEqual(try `false`.asBool(converting: true), false)
XCTAssertEqual(try `false`.asDouble(converting: true), 0.0)
XCTAssertEqual(try `false`.asInt(converting: true), 0)
XCTAssertEqual(try `false`.asString(converting: true), "false")
XCTAssertEqual(try `false`.asBuffer(converting: true), Buffer([0x00]))
XCTAssertThrowsError(try `false`.asArray(converting: true))
XCTAssertThrowsError(try `false`.asDictionary(converting: true))
let double: Map = 4.20
XCTAssertEqual(try double.asBool(converting: true), true)
XCTAssertEqual(try double.asDouble(converting: true), 4.20)
XCTAssertEqual(try double.asInt(converting: true), 4)
XCTAssertEqual(try double.asString(converting: true), "4.2")
XCTAssertThrowsError(try double.asBuffer(converting: true))
XCTAssertThrowsError(try double.asArray(converting: true))
XCTAssertThrowsError(try double.asDictionary(converting: true))
let doubleZero: Map = 0.0
XCTAssertEqual(try doubleZero.asBool(converting: true), false)
XCTAssertEqual(try doubleZero.asDouble(converting: true), 0.0)
XCTAssertEqual(try doubleZero.asInt(converting: true), 0)
XCTAssertEqual(try doubleZero.asString(converting: true), "0.0")
XCTAssertThrowsError(try doubleZero.asBuffer(converting: true))
XCTAssertThrowsError(try doubleZero.asArray(converting: true))
XCTAssertThrowsError(try doubleZero.asDictionary(converting: true))
let int: Map = 1969
XCTAssertEqual(try int.asBool(converting: true), true)
XCTAssertEqual(try int.asDouble(converting: true), 1969.0)
XCTAssertEqual(try int.asInt(converting: true), 1969)
XCTAssertEqual(try int.asString(converting: true), "1969")
XCTAssertThrowsError(try int.asBuffer(converting: true))
XCTAssertThrowsError(try int.asArray(converting: true))
XCTAssertThrowsError(try int.asDictionary(converting: true))
let intZero: Map = 0
XCTAssertEqual(try intZero.asBool(converting: true), false)
XCTAssertEqual(try intZero.asDouble(converting: true), 0.0)
XCTAssertEqual(try intZero.asInt(converting: true), 0)
XCTAssertEqual(try intZero.asString(converting: true), "0")
XCTAssertThrowsError(try intZero.asBuffer(converting: true))
XCTAssertThrowsError(try intZero.asArray(converting: true))
XCTAssertThrowsError(try intZero.asDictionary(converting: true))
let string: Map = "foo"
XCTAssertThrowsError(try string.asBool(converting: true))
XCTAssertThrowsError(try string.asDouble(converting: true))
XCTAssertThrowsError(try string.asInt(converting: true))
XCTAssertEqual(try string.asString(converting: true), "foo")
XCTAssertEqual(try string.asBuffer(converting: true), Buffer("foo"))
XCTAssertThrowsError(try string.asArray(converting: true))
XCTAssertThrowsError(try string.asDictionary(converting: true))
let stringTrue: Map = "TRUE"
XCTAssertEqual(try stringTrue.asBool(converting: true), true)
XCTAssertThrowsError(try stringTrue.asDouble(converting: true))
XCTAssertThrowsError(try stringTrue.asInt(converting: true))
XCTAssertEqual(try stringTrue.asString(converting: true), "TRUE")
XCTAssertEqual(try stringTrue.asBuffer(converting: true), Buffer("TRUE"))
XCTAssertThrowsError(try stringTrue.asArray(converting: true))
XCTAssertThrowsError(try stringTrue.asDictionary(converting: true))
let stringFalse: Map = "FALSE"
XCTAssertEqual(try stringFalse.asBool(converting: true), false)
XCTAssertThrowsError(try stringFalse.asDouble(converting: true))
XCTAssertThrowsError(try stringFalse.asInt(converting: true))
XCTAssertEqual(try stringFalse.asString(converting: true), "FALSE")
XCTAssertEqual(try stringFalse.asBuffer(converting: true), Buffer("FALSE"))
XCTAssertThrowsError(try stringFalse.asArray(converting: true))
XCTAssertThrowsError(try stringFalse.asDictionary(converting: true))
let stringDouble: Map = "4.20"
XCTAssertThrowsError(try stringDouble.asBool(converting: true))
XCTAssertEqual(try stringDouble.asDouble(converting: true), 4.20)
XCTAssertThrowsError(try stringDouble.asInt(converting: true))
XCTAssertEqual(try stringDouble.asString(converting: true), "4.20")
XCTAssertEqual(try stringDouble.asBuffer(converting: true), Buffer("4.20"))
XCTAssertThrowsError(try stringDouble.asArray(converting: true))
XCTAssertThrowsError(try stringDouble.asDictionary(converting: true))
let stringInt: Map = "1969"
XCTAssertThrowsError(try stringInt.asBool(converting: true))
XCTAssertEqual(try stringInt.asDouble(converting: true), 1969.0)
XCTAssertEqual(try stringInt.asInt(converting: true), 1969)
XCTAssertEqual(try stringInt.asString(converting: true), "1969")
XCTAssertEqual(try stringInt.asBuffer(converting: true), Buffer("1969"))
XCTAssertThrowsError(try stringInt.asArray(converting: true))
XCTAssertThrowsError(try stringInt.asDictionary(converting: true))
let buffer: Map = .buffer(Buffer("foo"))
XCTAssertEqual(try buffer.asBool(converting: true), true)
XCTAssertThrowsError(try buffer.asDouble(converting: true))
XCTAssertThrowsError(try buffer.asInt(converting: true))
XCTAssertEqual(try buffer.asString(converting: true), "foo")
XCTAssertEqual(try buffer.asBuffer(converting: true), Buffer("foo"))
XCTAssertThrowsError(try buffer.asArray(converting: true))
XCTAssertThrowsError(try buffer.asDictionary(converting: true))
let bufferEmpty: Map = .buffer(Buffer())
XCTAssertEqual(try bufferEmpty.asBool(converting: true), false)
XCTAssertThrowsError(try bufferEmpty.asDouble(converting: true))
XCTAssertThrowsError(try bufferEmpty.asInt(converting: true))
XCTAssertEqual(try bufferEmpty.asString(converting: true), "")
XCTAssertEqual(try bufferEmpty.asBuffer(converting: true), Buffer())
XCTAssertThrowsError(try bufferEmpty.asArray(converting: true))
XCTAssertThrowsError(try bufferEmpty.asDictionary(converting: true))
let array: Map = [1969]
XCTAssertEqual(try array.asBool(converting: true), true)
XCTAssertThrowsError(try array.asDouble(converting: true))
XCTAssertThrowsError(try array.asInt(converting: true))
XCTAssertThrowsError(try array.asString(converting: true))
XCTAssertThrowsError(try array.asBuffer(converting: true))
XCTAssertEqual(try array.asArray(converting: true), [1969])
XCTAssertThrowsError(try array.asDictionary(converting: true))
let arrayEmpty: Map = []
XCTAssertEqual(try arrayEmpty.asBool(converting: true), false)
XCTAssertThrowsError(try arrayEmpty.asDouble(converting: true))
XCTAssertThrowsError(try arrayEmpty.asInt(converting: true))
XCTAssertThrowsError(try arrayEmpty.asString(converting: true))
XCTAssertThrowsError(try arrayEmpty.asBuffer(converting: true))
XCTAssertEqual(try arrayEmpty.asArray(converting: true), [])
XCTAssertThrowsError(try arrayEmpty.asDictionary(converting: true))
let dictionary: Map = ["foo": "bar"]
XCTAssertEqual(try dictionary.asBool(converting: true), true)
XCTAssertThrowsError(try dictionary.asDouble(converting: true))
XCTAssertThrowsError(try dictionary.asInt(converting: true))
XCTAssertThrowsError(try dictionary.asString(converting: true))
XCTAssertThrowsError(try dictionary.asBuffer(converting: true))
XCTAssertThrowsError(try dictionary.asArray(converting: true))
XCTAssertEqual(try dictionary.asDictionary(converting: true), ["foo": "bar"])
let dictionaryEmpty: Map = [:]
XCTAssertEqual(try dictionaryEmpty.asBool(converting: true), false)
XCTAssertThrowsError(try dictionaryEmpty.asDouble(converting: true))
XCTAssertThrowsError(try dictionaryEmpty.asInt(converting: true))
XCTAssertThrowsError(try dictionaryEmpty.asString(converting: true))
XCTAssertThrowsError(try dictionaryEmpty.asBuffer(converting: true))
XCTAssertThrowsError(try dictionaryEmpty.asArray(converting: true))
XCTAssertEqual(try dictionaryEmpty.asDictionary(converting: true), [:])
}
func testDescription() {
let buffer: Map = [
"array": [
[],
true,
.buffer(Buffer("bar")),
[:],
4.20,
1969,
nil,
"foo\nbar",
],
"bool": true,
"buffer": .buffer(Buffer("bar")),
"dictionary": [
"array": [],
"bool": true,
"buffer": .buffer(Buffer("bar")),
"dictionary": [:],
"double": 4.20,
"int": 1969,
"null": nil,
"string": "foo\nbar",
],
"double": 4.20,
"int": 1969,
"null": nil,
"string": "foo\nbar",
]
let description = "{\"array\":[[],true,0x626172,{},4.2,1969,null,\"foo\\nbar\"],\"bool\":true,\"buffer\":0x626172,\"dictionary\":{\"array\":[],\"bool\":true,\"buffer\":0x626172,\"dictionary\":{},\"double\":4.2,\"int\":1969,\"null\":null,\"string\":\"foo\\nbar\"},\"double\":4.2,\"int\":1969,\"null\":null,\"string\":\"foo\\nbar\"}"
XCTAssertEqual(buffer.description, description)
}
func testEquality() {
let a: Map = "foo"
let b: Map = 1968
XCTAssertNotEqual(a, b)
}
func testIndexPath() throws {
var buffer: Map
buffer = [["foo"]]
XCTAssertEqual(try buffer.get(0, 0), "foo")
try buffer.set("bar", for: 0, 0)
XCTAssertEqual(try buffer.get(0, 0), "bar")
buffer = [["foo": "bar"]]
XCTAssertEqual(try buffer.get(0, "foo"), "bar")
try buffer.set("baz", for: 0, "foo")
XCTAssertEqual(try buffer.get(0, "foo"), "baz")
buffer = ["foo": ["bar"]]
XCTAssertEqual(try buffer.get("foo", 0), "bar")
try buffer.set("baz", for: "foo", 0)
XCTAssertEqual(try buffer.get("foo", 0), "baz")
buffer = ["foo": ["bar": "baz"]]
XCTAssertEqual(try buffer.get("foo", "bar"), "baz")
try buffer.set("buh", for: "foo", "bar")
XCTAssertEqual(try buffer.get("foo", "bar"), "buh")
try buffer.set("uhu", for: "foo", "yoo")
XCTAssertEqual(try buffer.get("foo", "bar"), "buh")
XCTAssertEqual(try buffer.get("foo", "yoo"), "uhu")
try buffer.remove("foo", "bar")
XCTAssertEqual(buffer, ["foo": ["yoo": "uhu"]])
}
func testMapInitializable() throws {
struct Bar : MapInitializable {
let bar: String
}
struct Foo : MapInitializable {
let foo: Bar
}
struct Baz {
let baz: String
}
struct Fuu : MapInitializable {
let fuu: Baz
}
struct Fou : MapInitializable {
let fou: String?
}
XCTAssertEqual(try Bar(map: ["bar": "bar"]).bar, "bar")
XCTAssertThrowsError(try Bar(map: "bar"))
XCTAssertThrowsError(try Bar(map: ["bar": nil]))
XCTAssertEqual(try Foo(map: ["foo": ["bar": "bar"]]).foo.bar, "bar")
XCTAssertThrowsError(try Fuu(map: ["fuu": ["baz": "baz"]]))
XCTAssertEqual(try Fou(map: [:]).fou, nil)
XCTAssertEqual(try Map(map: nil), nil)
XCTAssertEqual(try Bool(map: true), true)
XCTAssertThrowsError(try Bool(map: nil))
XCTAssertEqual(try Double(map: 4.2), 4.2)
XCTAssertThrowsError(try Double(map: nil))
XCTAssertEqual(try Int(map: 4), 4)
XCTAssertThrowsError(try Int(map: nil))
XCTAssertEqual(try String(map: "foo"), "foo")
XCTAssertThrowsError(try String(map: nil))
XCTAssertEqual(try Buffer(map: .buffer(Buffer("foo"))), Buffer("foo"))
XCTAssertThrowsError(try Buffer(map: nil))
XCTAssertEqual(try Optional<Int>(map: nil), nil)
XCTAssertEqual(try Optional<Int>(map: 1969), 1969)
XCTAssertThrowsError(try Optional<Baz>(map: nil))
XCTAssertEqual(try Array<Int>(map: [1969]), [1969])
XCTAssertThrowsError(try Array<Int>(map: nil))
XCTAssertThrowsError(try Array<Baz>(map: []))
XCTAssertEqual(try Dictionary<String, Int>(map: ["foo": 1969]), ["foo": 1969])
XCTAssertThrowsError(try Dictionary<String, Int>(map: nil))
XCTAssertThrowsError(try Dictionary<Int, Int>(map: [:]))
XCTAssertThrowsError(try Dictionary<String, Baz>(map: [:]))
let map: Map = [
"fey": [
"foo": "bar",
"fuu": "baz"
]
]
struct Fey : MapInitializable {
let foo: String
let fuu: String
}
let fey: Fey = try map.get("fey")
XCTAssertEqual(fey.foo, "bar")
XCTAssertEqual(fey.fuu, "baz")
}
func testMapRepresentable() throws {
struct Bar : MapFallibleRepresentable {
let bar: String
}
struct Foo : MapFallibleRepresentable {
let foo: Bar
}
struct Baz {
let baz: String
}
struct Fuu : MapFallibleRepresentable {
let fuu: Baz
}
XCTAssertEqual(try Foo(foo: Bar(bar: "bar")).asMap(), ["foo": ["bar": "bar"]])
XCTAssertThrowsError(try Fuu(fuu: Baz(baz: "baz")).asMap())
XCTAssertEqual(Map(1969).map, 1969)
XCTAssertEqual(true.map, true)
XCTAssertEqual(4.2.map, 4.2)
XCTAssertEqual(1969.map, 1969)
XCTAssertEqual("foo".map, "foo")
XCTAssertEqual(Buffer("foo").map, .buffer(Buffer("foo")))
let optional: Int? = nil
XCTAssertEqual(optional.map, nil)
XCTAssertEqual(Int?(1969).map, 1969)
XCTAssertEqual([1969].map, [1969])
XCTAssertEqual([1969].mapArray, [.int(1969)])
XCTAssertEqual(["foo": 1969].map, ["foo": 1969])
XCTAssertEqual(["foo": 1969].mapDictionary, ["foo": .int(1969)])
XCTAssertEqual(try optional.asMap(), nil)
XCTAssertEqual(try Int?(1969).asMap(), 1969)
let fuuOptional: Baz? = nil
XCTAssertThrowsError(try fuuOptional.asMap())
XCTAssertEqual(try [1969].asMap(), [1969])
let fuuArray: [Baz] = []
XCTAssertEqual(try fuuArray.asMap(), [])
XCTAssertEqual(try ["foo": 1969].asMap(), ["foo": 1969])
let fuuDictionaryA: [Int: Foo] = [:]
XCTAssertThrowsError(try fuuDictionaryA.asMap())
let fuuDictionaryB: [String: Baz] = [:]
XCTAssertEqual(try fuuDictionaryB.asMap(), [:])
}
}
extension MapTests {
public static var allTests: [(String, (MapTests) -> () throws -> Void)] {
return [
("testCreation", testCreation),
("testConversion", testConversion),
("testDescription", testDescription),
("testEquality", testEquality),
("testIndexPath", testIndexPath),
("testMapInitializable", testMapInitializable),
("testMapRepresentable", testMapRepresentable),
]
}
}
| mit | 1f643fc85cb51fcdb42e815877e423f6 | 44.05868 | 339 | 0.670275 | 5.014012 | false | false | false | false |
TouchInstinct/LeadKit | Sources/Classes/DataLoading/PaginationDataLoading/PaginationWrapper.swift | 1 | 12855 | //
// Copyright (c) 2018 Touch Instinct
//
// 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 RxSwift
import RxCocoa
import UIScrollView_InfiniteScroll
/// Class that connects PaginationDataLoadingModel with UIScrollView. It handles all non-visual and visual states.
final public class PaginationWrapper<Cursor: ResettableRxDataSourceCursor, Delegate: PaginationWrapperDelegate>
where Cursor == Delegate.DataSourceType, Cursor.ResultType == [Cursor.Element] {
private typealias DataLoadingModel = PaginationDataLoadingModel<Cursor>
private typealias LoadingState = DataLoadingModel.NetworkOperationStateType
private typealias FinishInfiniteScrollCompletion = ((UIScrollView) -> Void)
private var wrappedView: AnyPaginationWrappable
private let paginationViewModel: DataLoadingModel
private weak var delegate: Delegate?
private weak var uiDelegate: PaginationWrapperUIDelegate?
/// Sets the offset between the real end of the scroll view content and the scroll position,
/// so the handler can be triggered before reaching end. Defaults to 0.0;
public var infiniteScrollTriggerOffset: CGFloat {
get {
wrappedView.scrollView.infiniteScrollTriggerOffset
}
set {
wrappedView.scrollView.infiniteScrollTriggerOffset = newValue
}
}
public var pullToRefreshEnabled: Bool = true {
didSet {
if pullToRefreshEnabled {
createRefreshControl()
} else {
removeRefreshControl()
}
}
}
private var bottom: CGFloat {
wrappedView.scrollView.contentSize.height - wrappedView.scrollView.frame.size.height
}
private let disposeBag = DisposeBag()
private var currentPlaceholderView: UIView?
private var currentPlaceholderViewTopConstraint: NSLayoutConstraint?
/// Initializer with table view, placeholders container view, cusor and delegate parameters.
///
/// - Parameters:
/// - wrappedView: UIScrollView instance to work with.
/// - cursor: Cursor object that acts as data source.
/// - delegate: Delegate object for data loading events handling.
/// - uiDelegate: Delegate object for UI customization.
public init(wrappedView: AnyPaginationWrappable,
cursor: Cursor,
delegate: Delegate,
uiDelegate: PaginationWrapperUIDelegate? = nil) {
self.wrappedView = wrappedView
self.delegate = delegate
self.uiDelegate = uiDelegate
self.paginationViewModel = PaginationDataLoadingModel(dataSource: cursor) { $0.isEmpty }
bindViewModelStates()
createRefreshControl()
}
/// Method that reload all data in internal view model.
public func reload() {
paginationViewModel.reload()
}
/// Method acts like reload, but shows initial loading view after being invoked.
public func retry() {
paginationViewModel.retry()
}
/// Method that enables placeholders animation due pull-to-refresh interaction.
///
/// - Parameter scrollObservable: Observable that emits content offset as CGPoint.
public func setScrollObservable(_ scrollObservable: Observable<CGPoint>) {
scrollObservable
.asDriver(onErrorJustReturn: .zero)
.drive(scrollOffsetChanged)
.disposed(by: disposeBag)
}
// MARK: - States handling
private func onInitialState() {
//
}
private func onLoadingState(afterState: LoadingState) {
if case .initial = afterState {
wrappedView.scrollView.isUserInteractionEnabled = false
removeAllPlaceholderView()
guard let loadingIndicator = uiDelegate?.initialLoadingIndicator() else {
return
}
let loadingIndicatorView = loadingIndicator.view
loadingIndicatorView.translatesAutoresizingMaskIntoConstraints = true
wrappedView.backgroundView = loadingIndicatorView
loadingIndicator.startAnimating()
currentPlaceholderView = loadingIndicatorView
} else {
removeInfiniteScroll()
wrappedView.footerView = nil
}
}
private func onLoadingMoreState(afterState: LoadingState) {
if case .error = afterState { // user tap retry button in table footer
uiDelegate?.footerRetryViewWillDisappear()
wrappedView.footerView = nil
addInfiniteScroll(withHandler: false)
wrappedView.scrollView.beginInfiniteScroll(true)
}
}
private func onResultsState(newItems: DataLoadingModel.ResultType,
from cursor: Cursor,
afterState: LoadingState) {
wrappedView.scrollView.isUserInteractionEnabled = true
if case .initialLoading = afterState {
delegate?.paginationWrapper(didReload: newItems, using: cursor)
removeAllPlaceholderView()
wrappedView.scrollView.refreshControl?.endRefreshing()
addInfiniteScroll(withHandler: true)
} else if case .loadingMore = afterState {
delegate?.paginationWrapper(didLoad: newItems, using: cursor)
removeAllPlaceholderView()
addInfiniteScrollWithHandler()
}
}
private func onErrorState(error: Error, afterState: LoadingState) {
if case .initialLoading = afterState {
defer {
wrappedView.scrollView.refreshControl?.endRefreshing()
}
delegate?.clearData()
let customErrorHandling = uiDelegate?.customInitialLoadingErrorHandling(for: error) ?? false
guard !customErrorHandling, let errorView = uiDelegate?.errorPlaceholder(for: error) else {
return
}
replacePlaceholderViewIfNeeded(with: errorView)
} else {
guard let retryView = uiDelegate?.footerRetryView(),
let retryViewHeight = uiDelegate?.footerRetryViewHeight() else {
removeInfiniteScroll()
return
}
retryView.frame = CGRect(x: 0, y: 0, width: wrappedView.scrollView.bounds.width, height: retryViewHeight)
retryView.button.addTarget(self, action: #selector(retryEvent), for: .touchUpInside)
uiDelegate?.footerRetryViewWillAppear()
removeInfiniteScroll { scrollView in
self.wrappedView.footerView = retryView
let shouldUpdateContentOffset = Int(scrollView.contentOffset.y + retryViewHeight) >= Int(self.bottom)
if shouldUpdateContentOffset {
let newContentOffset = CGPoint(x: 0, y: scrollView.contentOffset.y + retryViewHeight)
scrollView.setContentOffset(newContentOffset, animated: true)
if #available(iOS 13, *) {
scrollView.setContentOffset(newContentOffset, animated: true)
}
}
}
}
}
@objc private func retryEvent() {
paginationViewModel.loadMore()
}
private func onEmptyState() {
defer {
wrappedView.scrollView.refreshControl?.endRefreshing()
}
delegate?.clearData()
guard let emptyView = uiDelegate?.emptyPlaceholder() else {
return
}
replacePlaceholderViewIfNeeded(with: emptyView)
}
private func replacePlaceholderViewIfNeeded(with placeholderView: UIView) {
wrappedView.scrollView.isUserInteractionEnabled = true
removeAllPlaceholderView()
placeholderView.translatesAutoresizingMaskIntoConstraints = false
placeholderView.isHidden = false
// I was unable to add pull-to-refresh placeholder scroll behaviour without this trick
let placeholderWrapperView = UIView()
placeholderWrapperView.addSubview(placeholderView)
let leadingConstraint = placeholderView.leadingAnchor.constraint(equalTo: placeholderWrapperView.leadingAnchor)
let trailingConstraint = placeholderView.trailingAnchor.constraint(equalTo: placeholderWrapperView.trailingAnchor)
let topConstraint = placeholderView.topAnchor.constraint(equalTo: placeholderWrapperView.topAnchor)
let bottomConstraint = placeholderView.bottomAnchor.constraint(equalTo: placeholderWrapperView.bottomAnchor)
NSLayoutConstraint.activate([
leadingConstraint,
trailingConstraint,
topConstraint,
bottomConstraint
])
currentPlaceholderViewTopConstraint = topConstraint
wrappedView.backgroundView = placeholderWrapperView
currentPlaceholderView = placeholderView
}
// MARK: - private stuff
private func onExhaustedState() {
removeInfiniteScroll()
removeAllPlaceholderView()
}
private func addInfiniteScrollWithHandler() {
removeInfiniteScroll()
addInfiniteScroll(withHandler: true)
}
private func addInfiniteScroll(withHandler: Bool) {
if withHandler {
wrappedView.scrollView.addInfiniteScroll { [weak paginationViewModel] _ in
paginationViewModel?.loadMore()
}
} else {
wrappedView.scrollView.addInfiniteScroll { _ in }
}
wrappedView.scrollView.infiniteScrollIndicatorView = uiDelegate?.loadingMoreIndicator()?.view
}
private func removeInfiniteScroll(with completion: FinishInfiniteScrollCompletion? = nil) {
wrappedView.scrollView.finishInfiniteScroll(completion: completion)
wrappedView.scrollView.removeInfiniteScroll()
}
private func createRefreshControl() {
let refreshControl = UIRefreshControl()
refreshControl.addTarget(self, action: #selector(refreshAction), for: .valueChanged)
wrappedView.scrollView.refreshControl = refreshControl
}
@objc private func refreshAction() {
// it is implemented the combined behavior of `touchUpInside` and `touchUpOutside` using `CFRunLoopPerformBlock`,
// which `UIRefreshControl` does not support
CFRunLoopPerformBlock(CFRunLoopGetMain(), CFRunLoopMode.defaultMode.rawValue) { [weak self] in
self?.reload()
}
}
private func removeRefreshControl() {
wrappedView.scrollView.refreshControl = nil
}
private func bindViewModelStates() {
paginationViewModel.stateDriver
.drive(stateChanged)
.disposed(by: disposeBag)
}
private func removeAllPlaceholderView() {
wrappedView.backgroundView = nil
wrappedView.footerView = nil
}
}
private extension PaginationWrapper {
private var stateChanged: Binder<LoadingState> {
Binder(self) { base, value in
switch value {
case .initial:
base.onInitialState()
case let .initialLoading(after):
base.onLoadingState(afterState: after)
case let .loadingMore(after):
base.onLoadingMoreState(afterState: after)
case let .results(newItems, from, after):
base.onResultsState(newItems: newItems, from: from, afterState: after)
case let .error(error, after):
base.onErrorState(error: error, afterState: after)
case .empty:
base.onEmptyState()
case .exhausted:
base.onExhaustedState()
}
}
}
var scrollOffsetChanged: Binder<CGPoint> {
Binder(self) { base, value in
base.currentPlaceholderViewTopConstraint?.constant = -value.y
}
}
}
| apache-2.0 | dccb2bc916a297309ba815cf56273415 | 34.609418 | 122 | 0.664489 | 5.662996 | false | false | false | false |
kylef/fd | Sources/FileDescriptor.swift | 1 | 674 | #if os(Linux)
import Glibc
private let system_close = Glibc.close
#else
import Darwin
private let system_close = Darwin.close
#endif
public typealias Byte = Int8
public typealias FileNumber = Int32
public protocol FileDescriptor {
var fileNumber: FileNumber { get }
}
struct FileDescriptorError : Error {
}
extension FileDescriptor {
/// Close deletes the file descriptor from the per-process object reference table
public func close() throws {
if system_close(fileNumber) == -1 {
throw FileDescriptorError()
}
}
public var isClosed: Bool {
if fcntl(fileNumber, F_GETFL) == -1 {
return errno == EBADF
}
return false
}
}
| bsd-2-clause | d6382c1641e1cef49206693fa5b11345 | 16.736842 | 83 | 0.698813 | 4.035928 | false | false | false | false |
benlangmuir/swift | stdlib/public/core/Unicode.swift | 13 | 24891 | //===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
import SwiftShims
// Conversions between different Unicode encodings. Note that UTF-16 and
// UTF-32 decoding are *not* currently resilient to erroneous data.
/// The result of one Unicode decoding step.
///
/// Each `UnicodeDecodingResult` instance can represent a Unicode scalar value,
/// an indication that no more Unicode scalars are available, or an indication
/// of a decoding error.
@frozen
public enum UnicodeDecodingResult: Equatable, Sendable {
/// A decoded Unicode scalar value.
case scalarValue(Unicode.Scalar)
/// An indication that no more Unicode scalars are available in the input.
case emptyInput
/// An indication of a decoding error.
case error
@inlinable
public static func == (
lhs: UnicodeDecodingResult,
rhs: UnicodeDecodingResult
) -> Bool {
switch (lhs, rhs) {
case (.scalarValue(let lhsScalar), .scalarValue(let rhsScalar)):
return lhsScalar == rhsScalar
case (.emptyInput, .emptyInput):
return true
case (.error, .error):
return true
default:
return false
}
}
}
/// A Unicode encoding form that translates between Unicode scalar values and
/// form-specific code units.
///
/// The `UnicodeCodec` protocol declares methods that decode code unit
/// sequences into Unicode scalar values and encode Unicode scalar values
/// into code unit sequences. The standard library implements codecs for the
/// UTF-8, UTF-16, and UTF-32 encoding schemes as the `UTF8`, `UTF16`, and
/// `UTF32` types, respectively. Use the `Unicode.Scalar` type to work with
/// decoded Unicode scalar values.
public protocol UnicodeCodec: Unicode.Encoding {
/// Creates an instance of the codec.
init()
/// Starts or continues decoding a code unit sequence into Unicode scalar
/// values.
///
/// To decode a code unit sequence completely, call this method repeatedly
/// until it returns `UnicodeDecodingResult.emptyInput`. Checking that the
/// iterator was exhausted is not sufficient, because the decoder can store
/// buffered data from the input iterator.
///
/// Because of buffering, it is impossible to find the corresponding position
/// in the iterator for a given returned `Unicode.Scalar` or an error.
///
/// The following example decodes the UTF-8 encoded bytes of a string into an
/// array of `Unicode.Scalar` instances:
///
/// let str = "✨Unicode✨"
/// print(Array(str.utf8))
/// // Prints "[226, 156, 168, 85, 110, 105, 99, 111, 100, 101, 226, 156, 168]"
///
/// var bytesIterator = str.utf8.makeIterator()
/// var scalars: [Unicode.Scalar] = []
/// var utf8Decoder = UTF8()
/// Decode: while true {
/// switch utf8Decoder.decode(&bytesIterator) {
/// case .scalarValue(let v): scalars.append(v)
/// case .emptyInput: break Decode
/// case .error:
/// print("Decoding error")
/// break Decode
/// }
/// }
/// print(scalars)
/// // Prints "["\u{2728}", "U", "n", "i", "c", "o", "d", "e", "\u{2728}"]"
///
/// - Parameter input: An iterator of code units to be decoded. `input` must be
/// the same iterator instance in repeated calls to this method. Do not
/// advance the iterator or any copies of the iterator outside this
/// method.
/// - Returns: A `UnicodeDecodingResult` instance, representing the next
/// Unicode scalar, an indication of an error, or an indication that the
/// UTF sequence has been fully decoded.
mutating func decode<I: IteratorProtocol>(
_ input: inout I
) -> UnicodeDecodingResult where I.Element == CodeUnit
/// Encodes a Unicode scalar as a series of code units by calling the given
/// closure on each code unit.
///
/// For example, the musical fermata symbol ("𝄐") is a single Unicode scalar
/// value (`\u{1D110}`) but requires four code units for its UTF-8
/// representation. The following code uses the `UTF8` codec to encode a
/// fermata in UTF-8:
///
/// var bytes: [UTF8.CodeUnit] = []
/// UTF8.encode("𝄐", into: { bytes.append($0) })
/// print(bytes)
/// // Prints "[240, 157, 132, 144]"
///
/// - Parameters:
/// - input: The Unicode scalar value to encode.
/// - processCodeUnit: A closure that processes one code unit argument at a
/// time.
static func encode(
_ input: Unicode.Scalar,
into processCodeUnit: (CodeUnit) -> Void
)
/// Searches for the first occurrence of a `CodeUnit` that is equal to 0.
///
/// Is an equivalent of `strlen` for C-strings.
///
/// - Complexity: O(*n*)
static func _nullCodeUnitOffset(in input: UnsafePointer<CodeUnit>) -> Int
}
/// A codec for translating between Unicode scalar values and UTF-8 code
/// units.
extension Unicode.UTF8: UnicodeCodec {
/// Creates an instance of the UTF-8 codec.
@inlinable
public init() { self = ._swift3Buffer(ForwardParser()) }
/// Starts or continues decoding a UTF-8 sequence.
///
/// To decode a code unit sequence completely, call this method repeatedly
/// until it returns `UnicodeDecodingResult.emptyInput`. Checking that the
/// iterator was exhausted is not sufficient, because the decoder can store
/// buffered data from the input iterator.
///
/// Because of buffering, it is impossible to find the corresponding position
/// in the iterator for a given returned `Unicode.Scalar` or an error.
///
/// The following example decodes the UTF-8 encoded bytes of a string into an
/// array of `Unicode.Scalar` instances. This is a demonstration only---if
/// you need the Unicode scalar representation of a string, use its
/// `unicodeScalars` view.
///
/// let str = "✨Unicode✨"
/// print(Array(str.utf8))
/// // Prints "[226, 156, 168, 85, 110, 105, 99, 111, 100, 101, 226, 156, 168]"
///
/// var bytesIterator = str.utf8.makeIterator()
/// var scalars: [Unicode.Scalar] = []
/// var utf8Decoder = UTF8()
/// Decode: while true {
/// switch utf8Decoder.decode(&bytesIterator) {
/// case .scalarValue(let v): scalars.append(v)
/// case .emptyInput: break Decode
/// case .error:
/// print("Decoding error")
/// break Decode
/// }
/// }
/// print(scalars)
/// // Prints "["\u{2728}", "U", "n", "i", "c", "o", "d", "e", "\u{2728}"]"
///
/// - Parameter input: An iterator of code units to be decoded. `input` must be
/// the same iterator instance in repeated calls to this method. Do not
/// advance the iterator or any copies of the iterator outside this
/// method.
/// - Returns: A `UnicodeDecodingResult` instance, representing the next
/// Unicode scalar, an indication of an error, or an indication that the
/// UTF sequence has been fully decoded.
@inlinable
@inline(__always)
public mutating func decode<I: IteratorProtocol>(
_ input: inout I
) -> UnicodeDecodingResult where I.Element == CodeUnit {
guard case ._swift3Buffer(var parser) = self else {
Builtin.unreachable()
}
defer { self = ._swift3Buffer(parser) }
switch parser.parseScalar(from: &input) {
case .valid(let s): return .scalarValue(UTF8.decode(s))
case .error: return .error
case .emptyInput: return .emptyInput
}
}
/// Attempts to decode a single UTF-8 code unit sequence starting at the LSB
/// of `buffer`.
///
/// - Returns:
/// - result: The decoded code point if the code unit sequence is
/// well-formed; `nil` otherwise.
/// - length: The length of the code unit sequence in bytes if it is
/// well-formed; otherwise the *maximal subpart of the ill-formed
/// sequence* (Unicode 8.0.0, Ch 3.9, D93b), i.e. the number of leading
/// code units that were valid or 1 in case none were valid. Unicode
/// recommends to skip these bytes and replace them by a single
/// replacement character (U+FFFD).
///
/// - Requires: There is at least one used byte in `buffer`, and the unused
/// space in `buffer` is filled with some value not matching the UTF-8
/// continuation byte form (`0b10xxxxxx`).
@inlinable
public // @testable
static func _decodeOne(_ buffer: UInt32) -> (result: UInt32?, length: UInt8) {
// Note the buffer is read least significant byte first: [ #3 #2 #1 #0 ].
if buffer & 0x80 == 0 { // 1-byte sequence (ASCII), buffer: [ ... ... ... CU0 ].
let value = buffer & 0xff
return (value, 1)
}
var p = ForwardParser()
p._buffer._storage = buffer
p._buffer._bitCount = 32
var i = EmptyCollection<UInt8>().makeIterator()
switch p.parseScalar(from: &i) {
case .valid(let s):
return (
result: UTF8.decode(s).value,
length: UInt8(truncatingIfNeeded: s.count))
case .error(let l):
return (result: nil, length: UInt8(truncatingIfNeeded: l))
case .emptyInput: Builtin.unreachable()
}
}
/// Encodes a Unicode scalar as a series of code units by calling the given
/// closure on each code unit.
///
/// For example, the musical fermata symbol ("𝄐") is a single Unicode scalar
/// value (`\u{1D110}`) but requires four code units for its UTF-8
/// representation. The following code encodes a fermata in UTF-8:
///
/// var bytes: [UTF8.CodeUnit] = []
/// UTF8.encode("𝄐", into: { bytes.append($0) })
/// print(bytes)
/// // Prints "[240, 157, 132, 144]"
///
/// - Parameters:
/// - input: The Unicode scalar value to encode.
/// - processCodeUnit: A closure that processes one code unit argument at a
/// time.
@inlinable
@inline(__always)
public static func encode(
_ input: Unicode.Scalar,
into processCodeUnit: (CodeUnit) -> Void
) {
var s = encode(input)!._biasedBits
processCodeUnit(UInt8(truncatingIfNeeded: s) &- 0x01)
s &>>= 8
if _fastPath(s == 0) { return }
processCodeUnit(UInt8(truncatingIfNeeded: s) &- 0x01)
s &>>= 8
if _fastPath(s == 0) { return }
processCodeUnit(UInt8(truncatingIfNeeded: s) &- 0x01)
s &>>= 8
if _fastPath(s == 0) { return }
processCodeUnit(UInt8(truncatingIfNeeded: s) &- 0x01)
}
/// Returns a Boolean value indicating whether the specified code unit is a
/// UTF-8 continuation byte.
///
/// Continuation bytes take the form `0b10xxxxxx`. For example, a lowercase
/// "e" with an acute accent above it (`"é"`) uses 2 bytes for its UTF-8
/// representation: `0b11000011` (195) and `0b10101001` (169). The second
/// byte is a continuation byte.
///
/// let eAcute = "é"
/// for codeUnit in eAcute.utf8 {
/// print(codeUnit, UTF8.isContinuation(codeUnit))
/// }
/// // Prints "195 false"
/// // Prints "169 true"
///
/// - Parameter byte: A UTF-8 code unit.
/// - Returns: `true` if `byte` is a continuation byte; otherwise, `false`.
@inlinable
public static func isContinuation(_ byte: CodeUnit) -> Bool {
return byte & 0b11_00__0000 == 0b10_00__0000
}
@inlinable
public static func _nullCodeUnitOffset(
in input: UnsafePointer<CodeUnit>
) -> Int {
return Int(_swift_stdlib_strlen_unsigned(input))
}
// Support parsing C strings as-if they are UTF8 strings.
@inlinable
public static func _nullCodeUnitOffset(
in input: UnsafePointer<CChar>
) -> Int {
return Int(_swift_stdlib_strlen(input))
}
}
/// A codec for translating between Unicode scalar values and UTF-16 code
/// units.
extension Unicode.UTF16: UnicodeCodec {
/// Creates an instance of the UTF-16 codec.
@inlinable
public init() { self = ._swift3Buffer(ForwardParser()) }
/// Starts or continues decoding a UTF-16 sequence.
///
/// To decode a code unit sequence completely, call this method repeatedly
/// until it returns `UnicodeDecodingResult.emptyInput`. Checking that the
/// iterator was exhausted is not sufficient, because the decoder can store
/// buffered data from the input iterator.
///
/// Because of buffering, it is impossible to find the corresponding position
/// in the iterator for a given returned `Unicode.Scalar` or an error.
///
/// The following example decodes the UTF-16 encoded bytes of a string into an
/// array of `Unicode.Scalar` instances. This is a demonstration only---if
/// you need the Unicode scalar representation of a string, use its
/// `unicodeScalars` view.
///
/// let str = "✨Unicode✨"
/// print(Array(str.utf16))
/// // Prints "[10024, 85, 110, 105, 99, 111, 100, 101, 10024]"
///
/// var codeUnitIterator = str.utf16.makeIterator()
/// var scalars: [Unicode.Scalar] = []
/// var utf16Decoder = UTF16()
/// Decode: while true {
/// switch utf16Decoder.decode(&codeUnitIterator) {
/// case .scalarValue(let v): scalars.append(v)
/// case .emptyInput: break Decode
/// case .error:
/// print("Decoding error")
/// break Decode
/// }
/// }
/// print(scalars)
/// // Prints "["\u{2728}", "U", "n", "i", "c", "o", "d", "e", "\u{2728}"]"
///
/// - Parameter input: An iterator of code units to be decoded. `input` must be
/// the same iterator instance in repeated calls to this method. Do not
/// advance the iterator or any copies of the iterator outside this
/// method.
/// - Returns: A `UnicodeDecodingResult` instance, representing the next
/// Unicode scalar, an indication of an error, or an indication that the
/// UTF sequence has been fully decoded.
@inlinable
public mutating func decode<I: IteratorProtocol>(
_ input: inout I
) -> UnicodeDecodingResult where I.Element == CodeUnit {
guard case ._swift3Buffer(var parser) = self else {
Builtin.unreachable()
}
defer { self = ._swift3Buffer(parser) }
switch parser.parseScalar(from: &input) {
case .valid(let s): return .scalarValue(UTF16.decode(s))
case .error: return .error
case .emptyInput: return .emptyInput
}
}
/// Try to decode one Unicode scalar, and return the actual number of code
/// units it spanned in the input. This function may consume more code
/// units than required for this scalar.
@inlinable
internal mutating func _decodeOne<I: IteratorProtocol>(
_ input: inout I
) -> (UnicodeDecodingResult, Int) where I.Element == CodeUnit {
let result = decode(&input)
switch result {
case .scalarValue(let us):
return (result, UTF16.width(us))
case .emptyInput:
return (result, 0)
case .error:
return (result, 1)
}
}
/// Encodes a Unicode scalar as a series of code units by calling the given
/// closure on each code unit.
///
/// For example, the musical fermata symbol ("𝄐") is a single Unicode scalar
/// value (`\u{1D110}`) but requires two code units for its UTF-16
/// representation. The following code encodes a fermata in UTF-16:
///
/// var codeUnits: [UTF16.CodeUnit] = []
/// UTF16.encode("𝄐", into: { codeUnits.append($0) })
/// print(codeUnits)
/// // Prints "[55348, 56592]"
///
/// - Parameters:
/// - input: The Unicode scalar value to encode.
/// - processCodeUnit: A closure that processes one code unit argument at a
/// time.
@inlinable
public static func encode(
_ input: Unicode.Scalar,
into processCodeUnit: (CodeUnit) -> Void
) {
var s = encode(input)!._storage
processCodeUnit(UInt16(truncatingIfNeeded: s))
s &>>= 16
if _fastPath(s == 0) { return }
processCodeUnit(UInt16(truncatingIfNeeded: s))
}
}
/// A codec for translating between Unicode scalar values and UTF-32 code
/// units.
extension Unicode.UTF32: UnicodeCodec {
/// Creates an instance of the UTF-32 codec.
@inlinable
public init() { self = ._swift3Codec }
/// Starts or continues decoding a UTF-32 sequence.
///
/// To decode a code unit sequence completely, call this method repeatedly
/// until it returns `UnicodeDecodingResult.emptyInput`. Checking that the
/// iterator was exhausted is not sufficient, because the decoder can store
/// buffered data from the input iterator.
///
/// Because of buffering, it is impossible to find the corresponding position
/// in the iterator for a given returned `Unicode.Scalar` or an error.
///
/// The following example decodes the UTF-16 encoded bytes of a string
/// into an array of `Unicode.Scalar` instances. This is a demonstration
/// only---if you need the Unicode scalar representation of a string, use
/// its `unicodeScalars` view.
///
/// // UTF-32 representation of "✨Unicode✨"
/// let codeUnits: [UTF32.CodeUnit] =
/// [10024, 85, 110, 105, 99, 111, 100, 101, 10024]
///
/// var codeUnitIterator = codeUnits.makeIterator()
/// var scalars: [Unicode.Scalar] = []
/// var utf32Decoder = UTF32()
/// Decode: while true {
/// switch utf32Decoder.decode(&codeUnitIterator) {
/// case .scalarValue(let v): scalars.append(v)
/// case .emptyInput: break Decode
/// case .error:
/// print("Decoding error")
/// break Decode
/// }
/// }
/// print(scalars)
/// // Prints "["\u{2728}", "U", "n", "i", "c", "o", "d", "e", "\u{2728}"]"
///
/// - Parameter input: An iterator of code units to be decoded. `input` must be
/// the same iterator instance in repeated calls to this method. Do not
/// advance the iterator or any copies of the iterator outside this
/// method.
/// - Returns: A `UnicodeDecodingResult` instance, representing the next
/// Unicode scalar, an indication of an error, or an indication that the
/// UTF sequence has been fully decoded.
@inlinable
public mutating func decode<I: IteratorProtocol>(
_ input: inout I
) -> UnicodeDecodingResult where I.Element == CodeUnit {
var parser = ForwardParser()
switch parser.parseScalar(from: &input) {
case .valid(let s): return .scalarValue(UTF32.decode(s))
case .error: return .error
case .emptyInput: return .emptyInput
}
}
/// Encodes a Unicode scalar as a UTF-32 code unit by calling the given
/// closure.
///
/// For example, like every Unicode scalar, the musical fermata symbol ("𝄐")
/// can be represented in UTF-32 as a single code unit. The following code
/// encodes a fermata in UTF-32:
///
/// var codeUnit: UTF32.CodeUnit = 0
/// UTF32.encode("𝄐", into: { codeUnit = $0 })
/// print(codeUnit)
/// // Prints "119056"
///
/// - Parameters:
/// - input: The Unicode scalar value to encode.
/// - processCodeUnit: A closure that processes one code unit argument at a
/// time.
@inlinable
public static func encode(
_ input: Unicode.Scalar,
into processCodeUnit: (CodeUnit) -> Void
) {
processCodeUnit(UInt32(input))
}
}
/// Translates the given input from one Unicode encoding to another by calling
/// the given closure.
///
/// The following example transcodes the UTF-8 representation of the string
/// `"Fermata 𝄐"` into UTF-32.
///
/// let fermata = "Fermata 𝄐"
/// let bytes = fermata.utf8
/// print(Array(bytes))
/// // Prints "[70, 101, 114, 109, 97, 116, 97, 32, 240, 157, 132, 144]"
///
/// var codeUnits: [UTF32.CodeUnit] = []
/// let sink = { codeUnits.append($0) }
/// transcode(bytes.makeIterator(), from: UTF8.self, to: UTF32.self,
/// stoppingOnError: false, into: sink)
/// print(codeUnits)
/// // Prints "[70, 101, 114, 109, 97, 116, 97, 32, 119056]"
///
/// The `sink` closure is called with each resulting UTF-32 code unit as the
/// function iterates over its input.
///
/// - Parameters:
/// - input: An iterator of code units to be translated, encoded as
/// `inputEncoding`. If `stopOnError` is `false`, the entire iterator will
/// be exhausted. Otherwise, iteration will stop if an encoding error is
/// detected.
/// - inputEncoding: The Unicode encoding of `input`.
/// - outputEncoding: The destination Unicode encoding.
/// - stopOnError: Pass `true` to stop translation when an encoding error is
/// detected in `input`. Otherwise, a Unicode replacement character
/// (`"\u{FFFD}"`) is inserted for each detected error.
/// - processCodeUnit: A closure that processes one `outputEncoding` code
/// unit at a time.
/// - Returns: `true` if the translation detected encoding errors in `input`;
/// otherwise, `false`.
@inlinable
@inline(__always)
public func transcode<
Input: IteratorProtocol,
InputEncoding: Unicode.Encoding,
OutputEncoding: Unicode.Encoding
>(
_ input: Input,
from inputEncoding: InputEncoding.Type,
to outputEncoding: OutputEncoding.Type,
stoppingOnError stopOnError: Bool,
into processCodeUnit: (OutputEncoding.CodeUnit) -> Void
) -> Bool
where InputEncoding.CodeUnit == Input.Element {
var input = input
// NB. It is not possible to optimize this routine to a memcpy if
// InputEncoding == OutputEncoding. The reason is that memcpy will not
// substitute U+FFFD replacement characters for ill-formed sequences.
var p = InputEncoding.ForwardParser()
var hadError = false
loop:
while true {
switch p.parseScalar(from: &input) {
case .valid(let s):
let t = OutputEncoding.transcode(s, from: inputEncoding)
guard _fastPath(t != nil), let s = t else { break }
s.forEach(processCodeUnit)
continue loop
case .emptyInput:
return hadError
case .error:
if _slowPath(stopOnError) { return true }
hadError = true
}
OutputEncoding.encodedReplacementCharacter.forEach(processCodeUnit)
}
}
/// Instances of conforming types are used in internal `String`
/// representation.
public // @testable
protocol _StringElement {
static func _toUTF16CodeUnit(_: Self) -> UTF16.CodeUnit
static func _fromUTF16CodeUnit(_ utf16: UTF16.CodeUnit) -> Self
}
extension UTF16.CodeUnit: _StringElement {
@inlinable
public // @testable
static func _toUTF16CodeUnit(_ x: UTF16.CodeUnit) -> UTF16.CodeUnit {
return x
}
@inlinable
public // @testable
static func _fromUTF16CodeUnit(
_ utf16: UTF16.CodeUnit
) -> UTF16.CodeUnit {
return utf16
}
}
extension UTF8.CodeUnit: _StringElement {
@inlinable
public // @testable
static func _toUTF16CodeUnit(_ x: UTF8.CodeUnit) -> UTF16.CodeUnit {
_internalInvariant(x <= 0x7f, "should only be doing this with ASCII")
return UTF16.CodeUnit(truncatingIfNeeded: x)
}
@inlinable
public // @testable
static func _fromUTF16CodeUnit(
_ utf16: UTF16.CodeUnit
) -> UTF8.CodeUnit {
_internalInvariant(utf16 <= 0x7f, "should only be doing this with ASCII")
return UTF8.CodeUnit(truncatingIfNeeded: utf16)
}
}
// Unchecked init to avoid precondition branches in hot code paths where we
// already know the value is a valid unicode scalar.
extension Unicode.Scalar {
/// Create an instance with numeric value `value`, bypassing the regular
/// precondition checks for code point validity.
@inlinable
internal init(_unchecked value: UInt32) {
_internalInvariant(value < 0xD800 || value > 0xDFFF,
"high- and low-surrogate code points are not valid Unicode scalar values")
_internalInvariant(value <= 0x10FFFF, "value is outside of Unicode codespace")
self._value = value
}
}
extension UnicodeCodec {
@inlinable
public static func _nullCodeUnitOffset(
in input: UnsafePointer<CodeUnit>
) -> Int {
var length = 0
while input[length] != 0 {
length += 1
}
return length
}
}
@available(*, unavailable, message: "use 'transcode(_:from:to:stoppingOnError:into:)'")
public func transcode<Input, InputEncoding, OutputEncoding>(
_ inputEncoding: InputEncoding.Type, _ outputEncoding: OutputEncoding.Type,
_ input: Input, _ output: (OutputEncoding.CodeUnit) -> Void,
stopOnError: Bool
) -> Bool
where
Input: IteratorProtocol,
InputEncoding: UnicodeCodec,
OutputEncoding: UnicodeCodec,
InputEncoding.CodeUnit == Input.Element {
Builtin.unreachable()
}
/// A namespace for Unicode utilities.
@frozen
public enum Unicode {}
| apache-2.0 | a3dd9e6c302a73864360fb7b63c79c07 | 35.75 | 87 | 0.645051 | 3.971703 | false | false | false | false |
catloafsoft/AudioKit | AudioKit/OSX/AudioKit/Playgrounds/AudioKit for OSX.playground/Pages/High Shelf Filter.xcplaygroundpage/Contents.swift | 1 | 1031 | //: [TOC](Table%20Of%20Contents) | [Previous](@previous) | [Next](@next)
//:
//: ---
//:
//: ## High Shelf Filter
//:
import XCPlayground
import AudioKit
//: This section prepares the player and the microphone
var mic = AKMicrophone()
mic.volume = 0
let micWindow = AKMicrophoneWindow(mic)
let bundle = NSBundle.mainBundle()
let file = bundle.pathForResource("mixloop", ofType: "wav")
var player = AKAudioPlayer(file!)
player.looping = true
let playerWindow = AKAudioPlayerWindow(player)
//: Next, we'll connect the audio sources to a high shelf filter
let inputMix = AKMixer(mic, player)
var highShelfFilter = AKHighShelfFilter(inputMix)
//: Set the parameters of the-high shelf filter here
highShelfFilter.cutOffFrequency = 10000 // Hz
highShelfFilter.gain = 0 // dB
var highShelfFilterWindow = AKHighShelfFilterWindow(highShelfFilter)
AudioKit.output = highShelfFilter
AudioKit.start()
XCPlaygroundPage.currentPage.needsIndefiniteExecution = true
//: [TOC](Table%20Of%20Contents) | [Previous](@previous) | [Next](@next)
| mit | c4407bc316c6c56f8571909691b10b6d | 27.638889 | 72 | 0.750727 | 3.980695 | false | false | false | false |
ZeeQL/ZeeQL3 | Sources/ZeeQL/Access/Codable/CodableModelEntityDecoder.swift | 1 | 4422 | //
// CodableModelEntityDecoder.swift
// ZeeQL3
//
// Created by Helge Hess on 10.02.18.
// Copyright © 2018-2019 ZeeZide GmbH. All rights reserved.
//
import Foundation
/**
* Just a helper type to check whether a decoder is a
* `CodableModelEntityDecoder`.
*/
internal protocol ReflectingDecoderType {}
extension CodableModelDecoder {
final class CodableModelEntityDecoder<EntityType: Decodable>
: Decoder, ReflectingDecoderType
{
let state : CodableModelDecoder
var log : ZeeQLLogger
let entity : CodableEntityType
var codingPath : [ CodingKey ]
var userInfo : [ CodingUserInfoKey : Any ] { return state.userInfo }
/// helper, remove this
var codingPathKK : String {
return codingPath.map { $0.stringValue }.joined(separator: ".")
}
init(state: CodableModelDecoder, entity: CodableEntityType) {
self.state = state
self.log = state.log
self.entity = entity
self.codingPath = state.codingPath
}
func container<Key>(keyedBy type: Key.Type) throws
-> KeyedDecodingContainer<Key> where Key : CodingKey
{
// Technically the user can have multiple 'Key' types. But that
// doesn't (really) make sense for us.
// TODO: It would be good to detect additional cycles here. That is, only
// create a single container and protect against multiple calls.
log.trace("\(" " * codingPath.count)DC[\(codingPathKK)]:",
"get-keyed-container<\(type)>")
return KeyedDecodingContainer(
EntityPropertyReflectionContainer<EntityType, Key>(
decoder: self, entity: entity))
}
func unkeyedContainer() throws -> UnkeyedDecodingContainer {
guard let key = codingPath.last else {
log.error("missing coding key:", codingPath, self)
throw Error.missingKey
}
log.trace("\(" " * codingPath.count)DC[\(codingPathKK)]:",
"get-unkeyed-container",
"\n source: ", entity,
"\n source-key:", key)
return EntityCollectionPropertyReflectionContainer(
decoder: self, entity: entity, key: key,
codingPath: codingPath)
}
func singleValueContainer() throws -> SingleValueDecodingContainer {
log.trace("\(" " * codingPath.count)DC[\(codingPathKK)]:",
"get-value-container")
return SingleContainer(decoder: self)
}
// MARK: - SingleContainer
private struct SingleContainer<EntityType: Decodable>
: SingleValueDecodingContainer
{
let log : ZeeQLLogger
let decoder : CodableModelEntityDecoder<EntityType>
var codingPath : [ CodingKey ] { return decoder.codingPath }
init(decoder: CodableModelEntityDecoder<EntityType>) {
self.decoder = decoder
self.log = decoder.log
}
func decodeNil() -> Bool {
log.log("\(" " * codingPath.count)SC[\(codingPath)]:decodeNil")
return false
}
func decode(_ type: Bool.Type) throws -> Bool { return true }
func decode(_ type: Int.Type) throws -> Int { return 42 }
func decode(_ type: Int8.Type) throws -> Int8 { return 48 }
func decode(_ type: Int16.Type) throws -> Int16 { return 416 }
func decode(_ type: Int32.Type) throws -> Int32 { return 432 }
func decode(_ type: Int64.Type) throws -> Int64 { return 464 }
func decode(_ type: UInt.Type) throws -> UInt { return 142 }
func decode(_ type: UInt8.Type) throws -> UInt8 { return 148 }
func decode(_ type: UInt16.Type) throws -> UInt16 { return 116 }
func decode(_ type: UInt32.Type) throws -> UInt32 { return 132 }
func decode(_ type: UInt64.Type) throws -> UInt64 { return 164 }
func decode(_ type: Float.Type) throws -> Float { return 42.42 }
func decode(_ type: Double.Type) throws -> Double { return 4242.42 }
func decode(_ type: String.Type) throws -> String {
log.log("\(" " * codingPath.count)SC[\(codingPath)]:decodeString")
return "Dooo"
}
func decode<T>(_ type: T.Type) throws -> T where T : Decodable {
throw Error.unsupportedSingleValue
}
}
}
}
| apache-2.0 | 023a1dad13ff2e134cc4aecf83ff5f7d | 34.943089 | 79 | 0.597376 | 4.465657 | false | false | false | false |
jpedrosa/sua_nc | Sources/io.swift | 2 | 2119 |
public class IO {
public static func sleep(f: Double) {
let sec = Int(f)
let nsec = sec > 0 ? Int((f % Double(sec)) * 1e9) : Int(f * 1e9)
Sys.nanosleep(sec, nanoseconds: nsec)
}
public static func sleep(n: Int) {
if n >= 0 {
Sys.sleep(UInt32(n))
}
}
public static func flush() {
Sys.fflush()
}
public static func read(filePath: String, maxBytes: Int = -1) throws
-> String? {
let f = try File(path: filePath)
defer { f.close() }
return try f.read(maxBytes)
}
public static func readLines(filePath: String) throws -> [String?] {
let f = try File(path: filePath)
defer { f.close() }
return try f.readLines()
}
public static func readAllBytes(filePath: String) throws -> [UInt8] {
let f = try File(path: filePath)
defer { f.close() }
return try f.readAllBytes()
}
public static func readAllCChar(filePath: String) throws -> [CChar] {
let f = try File(path: filePath)
defer { f.close() }
return try f.readAllCChar()
}
public static func write(filePath: String, string: String) throws -> Int {
let f = try File(path: filePath, mode: .W)
defer { f.close() }
return f.write(string)
}
public static func writeBytes(filePath: String, bytes: [UInt8],
maxBytes: Int) throws -> Int {
let f = try File(path: filePath, mode: .W)
defer { f.close() }
return f.writeBytes(bytes, maxBytes: maxBytes)
}
public static func writeCChar(filePath: String, bytes: [CChar],
maxBytes: Int) throws -> Int {
let f = try File(path: filePath, mode: .W)
defer { f.close() }
return f.writeCChar(bytes, maxBytes: maxBytes)
}
public static var env: Environment {
return Environment()
}
}
public struct Environment: SequenceType {
public subscript(name: String) -> String? {
get { return Sys.getenv(name) }
set {
if let v = newValue {
Sys.setenv(name, value: v)
} else {
Sys.unsetenv(name)
}
}
}
public func generate() -> DictionaryGenerator<String, String> {
return Sys.environment.generate()
}
}
| apache-2.0 | 01f03ba178de5195205d7cfa02e03624 | 22.544444 | 76 | 0.612553 | 3.519934 | false | false | false | false |
fuku2014/spritekit-original-game | src/scenes/home/sprites/TwitterBtn.swift | 1 | 1075 | //
// SubmitBtn.swift
// あるきスマホ
//
// Created by admin on 2015/05/30.
// Copyright (c) 2015年 m.fukuzawa. All rights reserved.
//
import UIKit
import SpriteKit
import Social
class TwitterBtn: SKSpriteNode {
let url = "https://itunes.apple.com/us/app/arukisumaho-batoru/id1095247230?l=ja&ls=1&mt=8"
var msg = ""
init (msg : String) {
self.msg = msg
let texture = SKTexture(imageNamed: "home_tweet")
super.init(texture: texture, color: UIColor.clearColor(), size: texture.size())
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
self.tweet()
}
func tweet(){
let cv = SLComposeViewController(forServiceType: SLServiceTypeTwitter)
cv.setInitialText(msg)
cv.addURL(NSURL(string: url))
self.scene!.view?.window?.rootViewController?.presentViewController(cv, animated: true, completion:nil )
}
}
| apache-2.0 | 85ff5ccbfffec3cb6058b1aea22e4993 | 25.525 | 112 | 0.645617 | 3.735915 | false | false | false | false |
nathantannar4/Parse-Dashboard-for-iOS-Pro | Pods/DynamicTabBarController/DynamicTabBarController/DynamicTabBar.swift | 1 | 8509 | //
// DynamicTabBar.swift
// DynamicTabBarController
//
// Copyright © 2017 Nathan Tannar.
//
// 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.
//
// Created by Nathan Tannar on 10/28/17.
//
import UIKit
final public class DynamicTabBar: UIView {
public enum ScrollIndicatorPosition {
case top, bottom
}
// MARK: - Properties [Public]
public var activeTintColor = UIColor(red: 0, green: 122/255, blue: 1, alpha: 1) {
didSet {
scrollIndicator.backgroundColor = activeTintColor
collectionView.reloadData()
}
}
public var inactiveTintColor = UIColor.lightGray {
didSet {
collectionView.reloadData()
}
}
public var scrollIndicatorPosition: ScrollIndicatorPosition = .top {
didSet {
updateScrollIndicatorPosition()
}
}
public var scrollIndicatorHeight: CGFloat = 5 {
didSet {
scrollIndicatorConstraints?.height?.constant = scrollIndicatorHeight
}
}
public let collectionView: UICollectionView = {
let layout = UICollectionViewFlowLayout()
layout.scrollDirection = .horizontal
let collectionView = UICollectionView(frame: .zero, collectionViewLayout: layout)
collectionView.translatesAutoresizingMaskIntoConstraints = false
collectionView.showsHorizontalScrollIndicator = false
collectionView.backgroundColor = .clear
return collectionView
}()
public let scrollIndicator: UIView = {
let view = UIView()
view.backgroundColor = UIColor(red: 0, green: 122/255, blue: 1, alpha: 1)
view.translatesAutoresizingMaskIntoConstraints = false
return view
}()
public let bufferView: UIView = {
let view = UIView()
view.translatesAutoresizingMaskIntoConstraints = false
return view
}()
public let blurView: UIVisualEffectView = {
let blurEffect = UIBlurEffect(style: .light)
let view = UIVisualEffectView(effect: blurEffect)
view.translatesAutoresizingMaskIntoConstraints = false
return view
}()
open var isTranslucent: Bool = false {
didSet {
if isTranslucent && blurView.superview == nil {
insertSubview(blurView, at: 0)
blurView.fillSuperview()
}
blurView.isHidden = !isTranslucent
backgroundColor = isTranslucent ? (backgroundColor?.withAlphaComponent(0.75) ?? UIColor.white.withAlphaComponent(0.75)) : .white
}
}
// MARK: - Properties [Private]
public var scrollIndicatorWidth: CGFloat = 0 {
didSet {
scrollIndicatorConstraints?.width?.constant = scrollIndicatorWidth
}
}
fileprivate var scrollIndicatorConstraints: NSLayoutConstraintSet?
// MARK: - Initialization
public override init(frame: CGRect) {
super.init(frame: frame)
setup()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup()
}
// MARK: - Setup [Private]
fileprivate func setup() {
backgroundColor = .white
setupSubviews()
setupConstraints()
}
fileprivate func setupSubviews() {
addSubview(bufferView)
addSubview(collectionView)
collectionView.addSubview(scrollIndicator)
}
fileprivate func setupConstraints() {
collectionView.addConstraints(topAnchor, left: leftAnchor, bottom: bufferView.topAnchor, right: rightAnchor)
bufferView.addConstraints(collectionView.bottomAnchor, left: leftAnchor, bottom: bottomAnchor, right: rightAnchor)
switch scrollIndicatorPosition {
case .top:
scrollIndicatorConstraints = NSLayoutConstraintSet(
top: scrollIndicator.topAnchor.constraint(equalTo: topAnchor),
left: scrollIndicator.leadingAnchor.constraint(equalTo: collectionView.leadingAnchor),
width: scrollIndicator.widthAnchor.constraint(equalToConstant: scrollIndicatorWidth),
height: scrollIndicator.heightAnchor.constraint(equalToConstant: scrollIndicatorHeight)
).activate()
case .bottom:
scrollIndicatorConstraints = NSLayoutConstraintSet(
bottom: scrollIndicator.bottomAnchor.constraint(equalTo: bottomAnchor),
left: scrollIndicator.leadingAnchor.constraint(equalTo: collectionView.leadingAnchor),
width: scrollIndicator.widthAnchor.constraint(equalToConstant: scrollIndicatorWidth),
height: scrollIndicator.heightAnchor.constraint(equalToConstant: scrollIndicatorHeight)
).activate()
}
}
// MARK: - Methods [Public]
open func scrollCurrentBarView(from oldIndex: Int, to newIndex: Int, with offset: CGFloat) {
deselectVisibleCells()
let currentIndexPath = IndexPath(row: oldIndex, section: 0)
let nextIndexPath = IndexPath(row: newIndex, section: 0)
guard let currentCell = collectionView.cellForItem(at: currentIndexPath) as? DynamicTabBarCell, let nextCell = collectionView.cellForItem(at: nextIndexPath) as? DynamicTabBarCell else { return }
let scrollRate = offset / frame.width
let width = fabs(scrollRate) * (nextCell.frame.width - currentCell.frame.width)
let newOffset = currentCell.frame.minX + scrollRate * (scrollRate > 0 ? currentCell.frame.width : nextCell.frame.width)
scrollIndicatorConstraints?.left?.constant = newOffset
scrollIndicatorWidth = currentCell.frame.width + width
collectionView.layoutIfNeeded()
}
open func moveCurrentBarView(to index: Int, animated: Bool, shouldScroll: Bool) {
let indexPath = IndexPath(item: index, section: 0)
if shouldScroll {
collectionView.scrollToItem(at: indexPath, at: .centeredHorizontally, animated: animated)
layoutIfNeeded()
}
guard let cell = collectionView.cellForItem(at: indexPath) as? DynamicTabBarCell else { return }
scrollIndicatorWidth = cell.frame.width
scrollIndicatorConstraints?.left?.constant = cell.frame.origin.x
if animated {
UIView.animate(withDuration: 0.3, animations: {
self.layoutIfNeeded()
}, completion: { _ in
self.updateUserInteraction(isEnabled: true)
cell.isActive = true
self.collectionView.reloadData()
})
} else {
layoutIfNeeded()
cell.isActive = true
collectionView.reloadData()
updateUserInteraction(isEnabled: true)
}
}
open func updateUserInteraction(isEnabled: Bool) {
collectionView.isUserInteractionEnabled = isEnabled
}
// MARK: - Methods [Private]
fileprivate func updateScrollIndicatorPosition() {
scrollIndicatorConstraints?.deactivate()
setupConstraints()
}
/// Updates the visible cells to their inactive state
private func deselectVisibleCells() {
collectionView.visibleCells.flatMap { $0 as? DynamicTabBarCell }.forEach { $0.tintColor = inactiveTintColor }
}
}
| mit | 121c367adb5a6740f4ad7a17e6c4cb48 | 36.646018 | 202 | 0.653503 | 5.568063 | false | false | false | false |
ppoh71/motoRoutes | motoRoutes/Utils.swift | 1 | 4546 | //
// utils.swift
// motoRoutes
//
// Created by Peter Pohlmann on 16.02.16.
// Copyright © 2016 Peter Pohlmann. All rights reserved.
//
import Foundation
import UIKit
import SystemConfiguration
import CoreLocation
import RealmSwift
import Mapbox
final class Utils {
/*
* get Time stamp
*/
class func getTimestamp()->Int{
return Int(Date().timeIntervalSince1970)
}
class func getUniqueUUID()->String{
return UUID().uuidString
}
/*
* define the speedIndex. km/h / 10 = Index for speedcolors
*/
class func getSpeedIndex(_ speed:Double) -> Int{
let speedIndex = Int(round((speed*3.6)/10))
//let speedIndex = 5
switch speedIndex {
case 0:
return 12
case 1..<7:
return 2
case 8..<16:
return 8
case 12..<50:
return 12
default:
return 1
}
// return speedIndex
}
/*
* define the speedIndex. km/h / 10 = Index for speedcolors
*/
class func getSpeedIndexFull(_ speed:Double) -> Int{
let speedIndex = Int(round((speed*3.6)/10))
//let speedIndex = 5
return speedIndex
}
/*
* get speed km/h mph
*/
class func getSpeed(_ speed:Double) -> Int{
let speed = Int(round((speed*3.6))) //kmh
//not 0 in return
//speed = speed == 0 ? 120 : speed
return speed
}
/*
* get speed Double km/h mph
*/
class func getSpeedDouble(_ speed:Double) -> Double{
let speed = round((speed*3.6)) //kmh
//not 0 in return
//speed = speed == 0 ? 120 : speed
return speed
}
/*
* get speed km/h mph
*/
class func getSpeedString(_ speed:Double) -> String{
let speed = speed*3.6//kmh
return String(format: "%.1f", speed)
}
/*
* get stringformat from double
*/
class func getDoubleString(_ double:Double) -> String{
return String(format: "%.2f", double)
}
/**
* Sets globalSppedSet by given speed (m/s)
*/
class func setGlobalSpeedSet(_ speed:Double){
// define speedIndex and set first Index
let speedIndex:Int = Utils.getSpeedIndex(speed)
globalSpeedSet.speedSet = speedIndex
}
/*
* helper get Document Directory
*/
class func getDocumentsDirectory() -> NSString {
let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
let documentsDirectory = paths[0]
//print("Path: \(documentsDirectory)")
return documentsDirectory as NSString
}
/*
* return full clock time hh:mm:ss
*/
static func clockFormat(_ totalSeconds:Int) -> String {
let seconds: Int = totalSeconds % 60
let minutes: Int = (totalSeconds / 60) % 60
let hours: Int = totalSeconds / 3600
var time: String
// if(hours<1){
// time = String(format: "%02d:%02d", minutes, seconds)
// } else {
// time = String(format: "%02d:%02d:%02d", hours, minutes, seconds)
// }
time = String(format: "%02d:%02d", hours, minutes)
return time
}
/*
* return full short clock time mm:ss
*/
static func clockFormatShort(_ totalSeconds:Int) -> String {
let seconds: Int = totalSeconds % 60
let minutes: Int = (totalSeconds / 60) % 60
return String(format: "%02d:%02d", minutes, seconds)
}
/*
* Performance time helper
*/
class func absolutePeromanceTime(_ x:Double) -> String {
let x = (CFAbsoluteTimeGetCurrent() - x) * 1000.0
return "Took \(x) milliseconds"
}
/*
* distance Formate
*/
class func distanceFormat(_ distance:Double) -> String {
let dist = String(format: "%.3f", distance/1000)
return dist
}
class func delay(_ delay:Double, closure:@escaping ()->()) {
DispatchQueue.main.asyncAfter(
deadline: DispatchTime.now() + Double(Int64(delay * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC), execute: closure)
//print("DISPATCH_TIME_NOW \(DISPATCH_TIME_NOW)")
}
}
| apache-2.0 | 710a96343efb34742db782b2f63b8bf2 | 21.61194 | 128 | 0.527833 | 4.408341 | false | false | false | false |
crspybits/SMCoreLib | SMCoreLib/Classes/Categories/UIViewController+Extras.swift | 1 | 815 | //
// UIViewController+Extras.swift
// SharedImages
//
// Created by Christopher G Prince on 9/10/18.
// Copyright © 2018 Spastic Muffin, LLC. All rights reserved.
//
import Foundation
import UIKit
extension UIViewController {
// Adapted from https://stackoverflow.com/questions/41073915/swift-3-how-to-get-the-current-displaying-uiviewcontroller-not-in-appdelegate
static func getTop() -> UIViewController? {
var viewController:UIViewController?
if let vc = UIApplication.shared.delegate?.window??.rootViewController {
viewController = vc
var presented = vc
while let top = presented.presentedViewController {
presented = top
viewController = top
}
}
return viewController
}
}
| gpl-3.0 | b72290274d2ae3921e43abf2f6778a95 | 25.258065 | 142 | 0.652334 | 4.760234 | false | false | false | false |
theMedvedev/eduConnect | eduConnect/AppDelegate.swift | 1 | 2246 | //
// AppDelegate.swift
// eduConnect
//
// Created by Alexey Medvedev on 1/14/17.
// Copyright © 2017 #nyc1-2devsandarussian. All rights reserved.
//
import UIKit
import Firebase
import GoogleSignIn
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, GIDSignInDelegate {
var window: UIWindow?
override init() {
super.init()
if FIRApp.defaultApp() == nil {
FIRApp.configure()
}
FIRDatabase.database().persistenceEnabled = true
}
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
GIDSignIn.sharedInstance().clientID = FIRApp.defaultApp()?.options.clientID
GIDSignIn.sharedInstance().delegate = self
return true
}
func sign(_ signIn: GIDSignIn!, didSignInFor user: GIDGoogleUser!, withError error: Error!) {
if let err = error {
print("Failed to login into EduConnect", err)
} else {
guard let idToken = user.authentication.idToken else { return }
guard let accessToken = user.authentication.accessToken else { return }
let credential = FIRGoogleAuthProvider.credential(withIDToken: idToken, accessToken: accessToken)
FIRAuth.auth()?.signIn(with: credential, completion: { (user, error) in
if let err = error {
print("Failed to login with Google", err)
return
}
guard let uid = user?.uid else { return }
guard let user = user?.displayName else { return }
UserDefaults.standard.set(uid, forKey: "uid")
UserDefaults.standard.set(user, forKey: "user")
NotificationCenter.default.post(name: .closeSafariVC, object: nil)
})
}
}
func application(_ application: UIApplication, open url: URL, sourceApplication: String?, annotation: Any) -> Bool {
return GIDSignIn.sharedInstance().handle(url,
sourceApplication: sourceApplication,
annotation: annotation)
}
}
| mit | c6ca97862bd8b8952bf88a98a2af87a1 | 34.078125 | 144 | 0.605791 | 5.245327 | false | false | false | false |
mikaoj/EnigmaKit | Sources/EnigmaKit/Enigma.swift | 1 | 2538 | // The MIT License (MIT)
//
// Copyright (c) 2017 Joakim Gyllström
//
// 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
/// Enigma machine simulator
public class Enigma {
private var spindle: Spindle
/// Plugboard
private(set) public var plugboard: Plugboard
/// Initializes enigma machine with given reflector, rotors and plugboard
///
/// - Parameters:
/// - reflector: Reflector to use
/// - rotors: Rotors to use
/// - plugboard: Plugboard to use
public init(reflector: Reflector = Reflector.B, rotors: [Rotor] = [Rotor.III, Rotor.II, Rotor.I], plugboard: Plugboard = Plugboard()) {
self.spindle = Spindle(reflector: reflector, rotors: rotors)
self.plugboard = plugboard
}
/// Encodes with enigma cipher
///
/// - Parameter input: The string to encode
/// - Returns: Encoded string
public func encode(_ input: String) -> String {
return String(input.uppercased().map {
encode(character: $0)
})
}
/// Encode character
///
/// - Parameter char: character to encode
/// - Returns: encoded character
private func encode(character char: Character) -> Character {
// Through the plugboard, into all the rotors and reflector and then back through plugboard again
return plugboard.encode(spindle.encode(plugboard.encode(char)))
}
}
extension Enigma {
/// Rotors
public var rotors: [Rotor] {
return spindle.rotors
}
/// Reflector
public var reflector: Reflector {
return spindle.reflector
}
}
| mit | 4e8cae0b2f540c50c68f83d5503665eb | 34.236111 | 137 | 0.715412 | 4.020602 | false | false | false | false |
wookay/Look | samples/LookSample/Pods/C4/C4/UI/C4View+Shadow.swift | 3 | 4042 | // Copyright © 2014 C4
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions: The above copyright
// notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
import CoreGraphics
/// Defines a structure representing the border of a C4View.
public struct Shadow {
/// Returns the corner radius of the border. Animatable.
///
/// Assigning an new value to this will change the corner radius of the shadow.
public var radius: Double
/// Returns the color of the shadow. Animatable.
///
/// Assigning an new value to this will change the color of the shadow.
public var color: C4Color?
/// Returns the offset of the shadow. Animatable.
///
/// Assigning an new value to this will change the offset of the shadow.
public var offset: C4Size
/// Returns the opacity of the shadow. Animatable.
///
/// Assigning an new value to this will change the opacity of the shadow.
public var opacity: Double
/// Returns the outline of the shadow. Animatable.
///
/// Assigning an new value to this will change the path of the shadow.
public var path: C4Path?
/// Initializes a new C4Shadow struct with the following defaults:
///
/// radius = 5.0
/// color = black
/// offset = (5,5)
/// opacity = 0.0
public init() {
radius = 5.0
color = C4Color(red: 0.0, green: 0.0, blue: 0.0, alpha: 1.0)
offset = C4Size(5,5)
opacity = 0.0
}
}
/// Extension to C4View that adds a shadow property.
public extension C4View {
/// Returns a struct that represents the current visible state of the receiver's shadow. Animatable.
///
/// Assigning a new value to this will change the `shadowRadius`, `shadowColor`, `shadowOpacity`, `shadowPath` and
/// `shadowOffset` of the receiver's layer.
///
/// The path is optional, and only set if it has a value.
///
/// ````
/// let v = C4View(frame: C4Rect(25,25,100,100))
/// v.backgroundColor = white
/// var s = Shadow()
/// s.opacity = 0.5
/// v.shadow = s
/// canvas.add(v)
/// ````
public var shadow: Shadow {
get {
var shadow = Shadow()
if let layer = layer {
shadow.radius = Double(layer.shadowRadius)
if let color = layer.shadowColor {
shadow.color = C4Color(color)
}
shadow.offset = C4Size(layer.shadowOffset)
shadow.opacity = Double(layer.shadowOpacity)
if let path = layer.shadowPath {
shadow.path = C4Path(path: path)
}
}
return shadow
}
set {
if let layer = layer {
layer.shadowColor = newValue.color?.CGColor
layer.shadowRadius = CGFloat(newValue.radius)
layer.shadowOffset = CGSize(newValue.offset)
layer.shadowOpacity = Float(newValue.opacity)
layer.shadowPath = newValue.path?.CGPath
}
}
}
}
| mit | 8d777eb1801129ddebf565a40a2c443e | 36.073394 | 118 | 0.62435 | 4.510045 | false | false | false | false |
fqhuy/minimind | minimind/optimisation/trust_region.swift | 1 | 3508 | //
// trust_region.swift
// minimind
//
// Created by Phan Quoc Huy on 6/23/17.
// Copyright © 2017 Phan Quoc Huy. All rights reserved.
//
import Foundation
public protocol TrustRegionOptimizer: Optimizer {
/// B_k in N.O
var hessianApproximate: MatrixT {get set}
/// x_k
var currentPosition: MatrixT {get set}
/// p_k in N.O
var currentSearchDirection: MatrixT {get set}
// trust region radius
var currentDelta: ScalarT {get set}
/// ∆
var deltaHat: ScalarT {get set}
/// rho
var eta: ScalarT {get set}
func computeCauchyPoint() -> MatrixT
func trustRegionSearch(_ delta0: ScalarT) -> MatrixT
func approximateSearchDirection() -> MatrixT
func quadraticApproximation(_ position: MatrixT) -> ScalarT
}
extension TrustRegionOptimizer {
func computeRho() -> ScalarT {
let nom = objective.compute(currentPosition) - objective.compute(currentPosition + currentSearchDirection)
let denom = quadraticApproximation(zeros_like(currentPosition)) - quadraticApproximation(currentSearchDirection)
return nom / denom
}
public func trustRegionSearch(_ Delta0: ScalarT) -> MatrixT {
// var Delta: ScalarT = Delta0
for k in 0..<100 {
let pk = approximateSearchDirection()
let rho = computeRho()
if rho < 0.25 {
currentDelta = 0.25 * currentDelta
} else {
if rho > 0.75 && norm(currentSearchDirection) == currentDelta {
currentDelta = min(2 * currentDelta, deltaHat)
}
}
if rho > eta {
currentPosition = currentPosition + currentSearchDirection
}
}
return currentPosition
}
public func computeCauchyPoint() -> MatrixT {
let gk = objective.gradient(currentPosition)
let Bk = hessianApproximate
let normgk = norm(gk)
let psk = -currentDelta / normgk * gk
let a = (gk * Bk * gk.t)[0,0]
var tauk: ScalarT = 1.0
if a > 0 {
let b = pow(normgk, 3) / (currentDelta * a)
tauk = min(b, 1.0)
}
return tauk * psk
}
}
extension TrustRegionOptimizer where ObjectiveFunctionT.ScalarT == Float {
/// iteratively solve subproblem
public func approximateSearchDirection() -> MatrixT {
var lamda: ScalarT = 0.1
let I: MatrixT = eye(hessianApproximate.rows)
let g = objective.gradient(currentPosition)
for _ in 0..<5 {
let R = cho_factor(hessianApproximate + lamda * I, "U")
let pl = cho_solve(R, -g, "U")
let ql = cho_solve(R.t, pl, "L")
let npl = norm(pl)
let nql = norm(ql)
lamda = lamda + pow(npl / nql, 2) * ((npl - currentDelta) / currentDelta)
}
let R = cho_factor(hessianApproximate + lamda * I, "U")
let p = cho_solve(R, -g)
return p
}
}
//public class DogLegOptimizer: TrustRegionOptimizer {
//
//
// var hessianApproximate: MatrixT
// var currentPosition: MatrixT
// var currentSearchDirection: MatrixT
// var currentDelta: ScalarT
// var deltaHat: ScalarT
// var eta: ScalarT
//
// public func optimize(verbose: Bool) {
//
// }
//
// public func approximateSearchDirection() -> MatrixT {
// <#code#>
// }
//}
| mit | 04a049a9ee35d22c9c918df883ee8c4b | 27.729508 | 120 | 0.571469 | 3.860132 | false | false | false | false |
lecason/SwiftCoAP | SwiftCoAP_Library/SCClient.swift | 10 | 18381 | //
// SCClient.swift
// SwiftCoAP
//
// Created by Wojtek Kordylewski on 03.05.15.
// Copyright (c) 2015 Wojtek Kordylewski. All rights reserved.
//
import UIKit
//MARK:
//MARK: SC Client Delegate Protocol implementation
@objc protocol SCClientDelegate {
//Tells the delegate that a valid CoAP message was received
func swiftCoapClient(client: SCClient, didReceiveMessage message: SCMessage)
//Tells the delegate that an error occured during or before transmission (refer to the "SCClientErrorCode" Enum)
optional func swiftCoapClient(client: SCClient, didFailWithError error: NSError)
//Tells the delegate that the respective message was sent. The property "number" indicates the amount of (re-)transmission attempts
optional func swiftCoapClient(client: SCClient, didSendMessage message: SCMessage, number: Int)
}
//MARK:
//MARK: SC Client Error Code Enumeration
enum SCClientErrorCode: Int {
case UdpSocketSetupError, UdpSocketSendError, MessageInvalidCodeForSendingError, ReceivedInvalidMessageError, NoResponseExpectedError, ProxyingError
func descriptionString() -> String {
switch self {
case .UdpSocketSetupError:
return "Failed to setup UDP socket"
case .UdpSocketSendError:
return "Failed to send data via UDP"
case .MessageInvalidCodeForSendingError:
return "CoAP-Message Code is not valid"
case .ReceivedInvalidMessageError:
return "Data received was not a valid CoAP Message"
case .NoResponseExpectedError:
return "The recipient does not respond"
case .ProxyingError:
return "HTTP-URL Request could not be sent"
}
}
}
//MARK:
//MARK: SC Client IMPLEMENTATION
class SCClient: NSObject {
//MARK: Constants and Properties
//CONSTANTS
let kMaxObserveOptionValue: UInt = 8388608
//INTERNAL PROPERTIES (allowed to modify)
weak var delegate: SCClientDelegate?
var sendToken = true //If true, a token with 4-8 Bytes is sent
var autoBlock1SZX: UInt? = 2 { didSet { if let newValue = autoBlock1SZX { autoBlock1SZX = min(6, newValue) } } } //If not nil, Block1 transfer will be used automatically when the payload size exceeds the value 2^(autoBlock1SZX + 4). Valid Values: 0-6.
var httpProxyingData: (hostName: String, port: UInt16)? //If not nil, all messages will be sent via http to the given proxy address
var cachingActive = false //Activates caching
//READ-ONLY PROPERTIES
private (set) var isMessageInTransmission = false //Indicates whether a message is in transmission and/or responses are still expected (e.g. separate, block, observe)
//PRIVATE PROPERTIES
private var udpSocket: GCDAsyncUdpSocket!
private var transmissionTimer: NSTimer!
private var messageInTransmission: SCMessage!
private var udpSocketTag: Int = 0
private var currentMessageId: UInt16 = UInt16(arc4random_uniform(0xFFFF) &+ 1)
private var retransmissionCounter = 0
private var currentTransmitWait = 0.0
private var recentNotificationInfo: (NSDate, UInt)!
lazy private var cachedMessagePairs = [SCMessage : SCMessage]()
//MARK: Internal Methods (allowed to use)
init(delegate: SCClientDelegate?) {
self.delegate = delegate
}
func sendCoAPMessage(message: SCMessage, hostName: String, port: UInt16) {
currentMessageId = (currentMessageId % 0xFFFF) + 1
message.hostName = hostName
message.port = port
message.messageId = currentMessageId
message.timeStamp = NSDate()
messageInTransmission = message
if sendToken {
message.token = UInt64(arc4random_uniform(0xFFFFFFFF) + 1) + (UInt64(arc4random_uniform(0xFFFFFFFF) + 1) << 32)
}
if cachingActive && message.code == SCCodeValue(classValue: 0, detailValue: 01) {
for cachedMessage in cachedMessagePairs.keys {
if cachedMessage.equalForCachingWithMessage(message) {
if cachedMessage.isFresh() {
if message.options[SCOption.Observe.rawValue] == nil { cachedMessage.options[SCOption.Observe.rawValue] = nil }
delegate?.swiftCoapClient(self, didReceiveMessage: cachedMessagePairs[cachedMessage]!)
handleBlock2WithMessage(cachedMessagePairs[cachedMessage]!)
return
}
else {
cachedMessagePairs[cachedMessage] = nil
break
}
}
}
}
if httpProxyingData != nil {
sendHttpMessageFromCoAPMessage(message)
}
else {
if udpSocket == nil && !setUpUdpSocket() {
closeTransmission()
notifyDelegateWithErrorCode(.UdpSocketSetupError)
return
}
if message.blockBody == nil && autoBlock1SZX != nil {
let fixedByteSize = pow(2, Double(autoBlock1SZX!) + 4)
if let payload = message.payload {
let blocksCount = ceil(Double(payload.length) / fixedByteSize)
if blocksCount > 1 {
message.blockBody = payload
let blockValue = 8 + UInt(autoBlock1SZX!)
sendBlock1MessageForCurrentContext(payload: payload.subdataWithRange(NSMakeRange(0, Int(fixedByteSize))), blockValue: blockValue)
return
}
}
}
initiateSending()
}
}
// Cancels observe directly, sending the previous message with an Observe-Option Value of 1. Only effective, if the previous message initiated a registration as observer with the respective server. To cancel observer indirectly (forget about the current state) call "closeTransmission()" or send another Message (this cleans up the old state automatically)
func cancelObserve() {
let cancelMessage = SCMessage(code: SCCodeValue(classValue: 0, detailValue: 01)!, type: .NonConfirmable, payload: nil)
cancelMessage.token = messageInTransmission.token
cancelMessage.options = messageInTransmission.options
var cancelByte: UInt8 = 1
cancelMessage.options[SCOption.Observe.rawValue] = [NSData(bytes: &cancelByte, length: 1)]
udpSocket.sendData(cancelMessage.toData()!, toHost: messageInTransmission.hostName!, port: messageInTransmission.port!, withTimeout: 0, tag: udpSocketTag)
udpSocketTag = (udpSocketTag % Int.max) + 1
}
//Closes the transmission. It is recommended to call this method anytime you do not expect to receive a response any longer.
func closeTransmission() {
udpSocket.close()
udpSocket = nil
messageInTransmission = nil
isMessageInTransmission = false
transmissionTimer?.invalidate()
transmissionTimer = nil
recentNotificationInfo = nil
cachedMessagePairs = [:]
}
// MARK: Private Methods
private func initiateSending() {
isMessageInTransmission = true
transmissionTimer?.invalidate()
transmissionTimer = nil
recentNotificationInfo = nil
if messageInTransmission.type == .Confirmable {
retransmissionCounter = 0
currentTransmitWait = 0
sendWithRentransmissionHandling()
}
else {
sendPendingMessage()
}
}
//Actually PRIVATE! Do not call from outside. Has to be internally visible as NSTimer won't find it otherwise
func sendWithRentransmissionHandling() {
sendPendingMessage()
if retransmissionCounter < SCMessage.kMaxRetransmit {
let timeout = SCMessage.kAckTimeout * pow(2.0, Double(retransmissionCounter)) * (SCMessage.kAckRandomFactor - (Double(arc4random()) / Double(UINT32_MAX) % 0.5));
currentTransmitWait += timeout
transmissionTimer = NSTimer(timeInterval: timeout, target: self, selector: "sendWithRentransmissionHandling", userInfo: nil, repeats: false)
retransmissionCounter++
}
else {
transmissionTimer = NSTimer(timeInterval: SCMessage.kMaxTransmitWait - currentTransmitWait, target: self, selector: "notifyNoResponseExpected", userInfo: nil, repeats: false)
}
NSRunLoop.currentRunLoop().addTimer(transmissionTimer, forMode: NSRunLoopCommonModes)
}
//Actually PRIVATE! Do not call from outside. Has to be internally visible as NSTimer won't find it otherwise
func notifyNoResponseExpected() {
closeTransmission()
notifyDelegateWithErrorCode(.NoResponseExpectedError)
}
private func sendPendingMessage() {
if let data = messageInTransmission.toData() {
udpSocket.sendData(data, toHost: messageInTransmission.hostName!, port: messageInTransmission.port!, withTimeout: 0, tag: udpSocketTag)
udpSocketTag = (udpSocketTag % Int.max) + 1
delegate?.swiftCoapClient?(self, didSendMessage: messageInTransmission, number: retransmissionCounter + 1)
}
else {
closeTransmission()
notifyDelegateWithErrorCode(.MessageInvalidCodeForSendingError)
}
}
private func setUpUdpSocket() -> Bool {
udpSocket = GCDAsyncUdpSocket(delegate: self, delegateQueue: dispatch_get_main_queue())
var error: NSError?
if !udpSocket!.bindToPort(0, error: &error) {
return false
}
if !udpSocket!.beginReceiving(&error) {
return false
}
return true
}
private func sendEmptyMessageWithType(type: SCType, messageId: UInt16, addressData: NSData) {
let emptyMessage = SCMessage()
emptyMessage.type = type;
emptyMessage.messageId = messageId
udpSocket?.sendData(emptyMessage.toData()!, toAddress: addressData, withTimeout: 0, tag: udpSocketTag)
udpSocketTag = (udpSocketTag % Int.max) + 1
}
private func notifyDelegateWithErrorCode(clientErrorCode: SCClientErrorCode) {
delegate?.swiftCoapClient?(self, didFailWithError: NSError(domain: SCMessage.kCoapErrorDomain, code: clientErrorCode.rawValue, userInfo: [NSLocalizedDescriptionKey : clientErrorCode.descriptionString()]))
}
private func handleBlock2WithMessage(message: SCMessage) {
if let block2opt = message.options[SCOption.Block2.rawValue], blockData = block2opt.first {
let actualValue = UInt.fromData(blockData)
if actualValue & 8 == 8 {
//more bit is set, request next block
let blockMessage = SCMessage(code: messageInTransmission.code, type: messageInTransmission.type, payload: messageInTransmission.payload)
blockMessage.options = messageInTransmission.options
let newValue = (actualValue & ~8) + 16
var byteArray = newValue.toByteArray()
blockMessage.options[SCOption.Block2.rawValue] = [NSData(bytes: &byteArray, length: byteArray.count)]
sendCoAPMessage(blockMessage, hostName: messageInTransmission.hostName!, port: messageInTransmission.port!)
}
else {
isMessageInTransmission = false
}
}
}
private func continueBlock1ForBlockNumber(block: Int, szx: UInt) {
let byteSize = pow(2, Double(szx) + 4)
let blocksCount = ceil(Double(messageInTransmission.blockBody!.length) / byteSize)
if block < Int(blocksCount) {
var nextBlockLength: Int
var blockValue: UInt = (UInt(block) << 4) + UInt(szx)
if block < Int(blocksCount - 1) {
nextBlockLength = Int(byteSize)
blockValue += 8
}
else {
nextBlockLength = messageInTransmission.blockBody!.length - Int(byteSize) * block
}
sendBlock1MessageForCurrentContext(payload: messageInTransmission.blockBody!.subdataWithRange(NSMakeRange(Int(byteSize) * block, nextBlockLength)), blockValue: blockValue)
}
}
private func sendBlock1MessageForCurrentContext(#payload: NSData, blockValue: UInt) {
let blockMessage = SCMessage(code: messageInTransmission.code, type: messageInTransmission.type, payload: payload)
blockMessage.options = messageInTransmission.options
blockMessage.blockBody = messageInTransmission.blockBody
var byteArray = blockValue.toByteArray()
blockMessage.options[SCOption.Block1.rawValue] = [NSData(bytes: &byteArray, length: byteArray.count)]
sendCoAPMessage(blockMessage, hostName: messageInTransmission.hostName!, port: messageInTransmission.port!)
}
private func sendHttpMessageFromCoAPMessage(message: SCMessage) {
let urlRequest = message.toHttpUrlRequestWithUrl()
let urlString = "http://\(httpProxyingData!.hostName):\(httpProxyingData!.port)/\(message.hostName!):\(message.port!)"
urlRequest.URL = NSURL(string: urlString)
urlRequest.timeoutInterval = SCMessage.kMaxTransmitWait
urlRequest.cachePolicy = .UseProtocolCachePolicy
NSURLConnection.sendAsynchronousRequest(urlRequest, queue: NSOperationQueue.mainQueue()) { (response, data, error) -> Void in
if error != nil {
self.notifyDelegateWithErrorCode(.ProxyingError)
}
else {
let coapResponse = SCMessage.fromHttpUrlResponse(response as! NSHTTPURLResponse, data: data)
coapResponse.timeStamp = NSDate()
if self.cachingActive && self.messageInTransmission.code == SCCodeValue(classValue: 0, detailValue: 01) {
self.cachedMessagePairs[self.messageInTransmission] = SCMessage.copyFromMessage(coapResponse)
}
self.delegate?.swiftCoapClient(self, didReceiveMessage: coapResponse)
self.handleBlock2WithMessage(coapResponse)
}
}
}
}
// MARK:
// MARK: SC Client Extension
// MARK: GCD Async Udp Socket Delegate
extension SCClient: GCDAsyncUdpSocketDelegate {
func udpSocket(sock: GCDAsyncUdpSocket!, didReceiveData data: NSData!, fromAddress address: NSData!, withFilterContext filterContext: AnyObject!) {
println("Client received data: \(data)")
if let message = SCMessage.fromData(data) {
//Invalidate Timer
transmissionTimer?.invalidate()
transmissionTimer = nil
//Check for spam
if message.messageId != messageInTransmission.messageId && message.token != messageInTransmission.token {
if message.type.rawValue <= SCType.NonConfirmable.rawValue {
sendEmptyMessageWithType(.Reset, messageId: message.messageId, addressData: address)
}
return
}
//Set timestamp
message.timeStamp = NSDate()
//Handle Caching, Separate, etc
if cachingActive && messageInTransmission.code == SCCodeValue(classValue: 0, detailValue: 01) {
cachedMessagePairs[messageInTransmission] = SCMessage.copyFromMessage(message)
}
//Handle Observe-Option (Observe Draft Section 3.4)
if let observeValueArray = message.options[SCOption.Observe.rawValue], observeValue = observeValueArray.first {
let currentNumber = UInt.fromData(observeValue)
if recentNotificationInfo == nil ||
(recentNotificationInfo.1 < currentNumber && currentNumber - recentNotificationInfo.1 < kMaxObserveOptionValue) ||
(recentNotificationInfo.1 > currentNumber && recentNotificationInfo.1 - currentNumber > kMaxObserveOptionValue) ||
(recentNotificationInfo.0 .compare(message.timeStamp!.dateByAddingTimeInterval(128)) == .OrderedAscending) {
recentNotificationInfo = (message.timeStamp!, currentNumber)
}
else {
return
}
}
//Notify Delegate
delegate?.swiftCoapClient(self, didReceiveMessage: message)
//Handle Block2
handleBlock2WithMessage(message)
//Handle Block1
if message.code.toCodeSample() == SCCodeSample.Continue, let block1opt = message.options[SCOption.Block1.rawValue], blockData = block1opt.first {
var actualValue = UInt.fromData(blockData)
let serverSZX = actualValue & 0b111
actualValue >>= 4
if serverSZX <= 6 {
var blockOffset = 1
if serverSZX < autoBlock1SZX! {
blockOffset = Int(pow(2, Double(autoBlock1SZX! - serverSZX)))
autoBlock1SZX = serverSZX
}
continueBlock1ForBlockNumber(Int(actualValue) + blockOffset, szx: serverSZX)
}
}
//Further Operations
if message.type == .Confirmable {
sendEmptyMessageWithType(.Acknowledgement, messageId: message.messageId, addressData: address)
}
if (message.type != .Acknowledgement || message.code.toCodeSample() != .Empty) && message.options[SCOption.Block2.rawValue] == nil && message.code.toCodeSample() != SCCodeSample.Continue {
isMessageInTransmission = false
}
}
else {
notifyDelegateWithErrorCode(.ReceivedInvalidMessageError)
}
}
func udpSocket(sock: GCDAsyncUdpSocket!, didNotSendDataWithTag tag: Int, dueToError error: NSError!) {
notifyDelegateWithErrorCode(.UdpSocketSendError)
transmissionTimer?.invalidate()
transmissionTimer = nil
}
} | mit | bf4c05dc2a8894ac591ea9852b8a1bae | 42.976077 | 360 | 0.635874 | 5.452685 | false | false | false | false |
jorik041/mpv | video/out/cocoa_cb_common.swift | 7 | 7111 | /*
* This file is part of mpv.
*
* mpv is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* mpv 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with mpv. If not, see <http://www.gnu.org/licenses/>.
*/
import Cocoa
class CocoaCB: Common {
var libmpv: LibmpvHelper
var layer: GLLayer?
@objc var isShuttingDown: Bool = false
enum State {
case uninitialized
case needsInit
case initialized
}
var backendState: State = .uninitialized
@objc init(_ mpvHandle: OpaquePointer) {
let newlog = mp_log_new(UnsafeMutablePointer<MPContext>(mpvHandle), mp_client_get_log(mpvHandle), "cocoacb")
libmpv = LibmpvHelper(mpvHandle, newlog)
super.init(newlog)
layer = GLLayer(cocoaCB: self)
}
func preinit(_ vo: UnsafeMutablePointer<vo>) {
mpv = MPVHelper(vo, log)
if backendState == .uninitialized {
backendState = .needsInit
guard let layer = self.layer else {
log.sendError("Something went wrong, no GLLayer was initialized")
exit(1)
}
initView(vo, layer)
initMisc(vo)
}
}
func uninit() {
window?.orderOut(nil)
window?.close()
mpv = nil
}
func reconfig(_ vo: UnsafeMutablePointer<vo>) {
mpv?.vo = vo
if backendState == .needsInit {
DispatchQueue.main.sync { self.initBackend(vo) }
} else {
DispatchQueue.main.async {
self.updateWindowSize(vo)
self.layer?.update(force: true)
}
}
}
func initBackend(_ vo: UnsafeMutablePointer<vo>) {
let previousActiveApp = getActiveApp()
initApp()
initWindow(vo, previousActiveApp)
updateICCProfile()
initWindowState()
backendState = .initialized
}
func updateWindowSize(_ vo: UnsafeMutablePointer<vo>) {
guard let targetScreen = getTargetScreen(forFullscreen: false) ?? NSScreen.main else
{
log.sendWarning("Couldn't update Window size, no Screen available")
return
}
let wr = getWindowGeometry(forScreen: targetScreen, videoOut: vo)
if !(window?.isVisible ?? false) &&
!(window?.isMiniaturized ?? false) &&
!NSApp.isHidden
{
window?.makeKeyAndOrderFront(nil)
}
layer?.atomicDrawingStart()
window?.updateSize(wr.size)
}
override func displayLinkCallback(_ displayLink: CVDisplayLink,
_ inNow: UnsafePointer<CVTimeStamp>,
_ inOutputTime: UnsafePointer<CVTimeStamp>,
_ flagsIn: CVOptionFlags,
_ flagsOut: UnsafeMutablePointer<CVOptionFlags>) -> CVReturn
{
libmpv.reportRenderFlip()
return kCVReturnSuccess
}
override func lightSensorUpdate() {
libmpv.setRenderLux(lmuToLux(lastLmu))
}
override func updateICCProfile() {
guard let colorSpace = window?.screen?.colorSpace else {
log.sendWarning("Couldn't update ICC Profile, no color space available")
return
}
libmpv.setRenderICCProfile(colorSpace)
if #available(macOS 10.11, *) {
layer?.colorspace = colorSpace.cgColorSpace
}
}
override func windowDidEndAnimation() {
layer?.update()
checkShutdown()
}
override func windowSetToFullScreen() {
layer?.update(force: true)
}
override func windowSetToWindow() {
layer?.update(force: true)
}
override func windowDidUpdateFrame() {
layer?.update(force: true)
}
override func windowDidChangeScreen() {
layer?.update(force: true)
}
override func windowDidChangeScreenProfile() {
layer?.needsICCUpdate = true
}
override func windowDidChangeBackingProperties() {
layer?.contentsScale = window?.backingScaleFactor ?? 1
}
override func windowWillStartLiveResize() {
layer?.inLiveResize = true
}
override func windowDidEndLiveResize() {
layer?.inLiveResize = false
}
override func windowDidChangeOcclusionState() {
layer?.update(force: true)
}
var controlCallback: mp_render_cb_control_fn = { ( v, ctx, e, request, d ) -> Int32 in
let ccb = unsafeBitCast(ctx, to: CocoaCB.self)
// the data pointer can be a null pointer, the libmpv control callback
// provides nil instead of the 0 address like the usual control call of
// an internal vo, workaround to create a null pointer instead of nil
var data = UnsafeMutableRawPointer.init(bitPattern: 0).unsafelyUnwrapped
if let dunwrapped = d {
data = dunwrapped
}
guard let vo = v, let events = e else {
ccb.log.sendWarning("Unexpected nil value in Control Callback")
return VO_FALSE
}
return ccb.control(vo, events: events, request: request, data: data)
}
override func control(_ vo: UnsafeMutablePointer<vo>,
events: UnsafeMutablePointer<Int32>,
request: UInt32,
data: UnsafeMutableRawPointer) -> Int32
{
switch mp_voctrl(request) {
case VOCTRL_PREINIT:
DispatchQueue.main.sync { self.preinit(vo) }
return VO_TRUE
case VOCTRL_UNINIT:
DispatchQueue.main.async { self.uninit() }
return VO_TRUE
case VOCTRL_RECONFIG:
reconfig(vo)
return VO_TRUE
default:
break
}
return super.control(vo, events: events, request: request, data: data)
}
func shutdown(_ destroy: Bool = false) {
isShuttingDown = window?.isAnimating ?? false ||
window?.isInFullscreen ?? false && Bool(mpv?.opts.native_fs ?? 1)
if window?.isInFullscreen ?? false && !(window?.isAnimating ?? false) {
window?.close()
}
if isShuttingDown { return }
uninit()
uninitCommon()
libmpv.deinitRender()
libmpv.deinitMPV(destroy)
}
func checkShutdown() {
if isShuttingDown {
shutdown(true)
}
}
@objc func processEvent(_ event: UnsafePointer<mpv_event>) {
switch event.pointee.event_id {
case MPV_EVENT_SHUTDOWN:
shutdown()
default:
break
}
}
}
| gpl-3.0 | d1f726cc2449fb15d9b5893ab67ba5b7 | 28.629167 | 116 | 0.589931 | 4.656843 | false | false | false | false |
MrSongzj/MSDouYuZB | MSDouYuZB/MSDouYuZB/Classes/Tools/Extension/UIViewController+Loading.swift | 1 | 1698 | //
// UIViewController+Loading.swift
// MSDouYuZB
//
// Created by jiayuan on 2017/8/10.
// Copyright © 2017年 mrsong. All rights reserved.
//
import UIKit
class LoadingView: UIView {
let imageV: UIImageView = UIImageView(image: UIImage(named: "img_loading_1"))
convenience init(inView: UIView) {
self.init(frame: inView.bounds)
imageV.animationImages = [UIImage(named: "img_loading_1")!, UIImage(named: "img_loading_2")!]
imageV.animationDuration = 0.5
imageV.animationRepeatCount = Int.max
imageV.center = self.center
imageV.autoresizingMask = [
.flexibleTopMargin,
.flexibleBottomMargin,
.flexibleLeftMargin,
.flexibleRightMargin]
self.addSubview(imageV)
self.backgroundColor = UIColor.white
self.autoresizingMask = [.flexibleWidth, .flexibleHeight]
inView.addSubview(self)
}
}
extension UIViewController {
@discardableResult func showLoading() -> Bool {
for subV in view.subviews {
if subV is LoadingView {
return false
}
}
let loadingV = LoadingView(inView: view)
loadingV.imageV.startAnimating()
return true
}
@discardableResult func hideLoading() -> Bool {
for subV in view.subviews {
if subV is LoadingView {
let loadingV = subV as! LoadingView
loadingV.imageV.stopAnimating()
loadingV.removeFromSuperview()
return true
}
}
return false
}
}
| mit | b20682c58f4f5e7be4d19a130cc2020c | 25.076923 | 101 | 0.568732 | 5.044643 | false | false | false | false |
mattdonnelly/Swifter | Sources/SwifterUsers.swift | 1 | 22389 | //
// SwifterUsers.swift
// Swifter
//
// Copyright (c) 2014 Matt Donnelly.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
public extension Swifter {
/**
GET account/settings
Returns settings (including current trend, geo and sleep time information) for the authenticating user.
*/
func getAccountSettings(success: SuccessHandler? = nil,
failure: FailureHandler? = nil) {
let path = "account/settings.json"
self.getJSON(path: path, baseURL: .api, parameters: [:], success: { json, _ in
success?(json)
}, failure: failure)
}
/**
GET account/verify_credentials
Returns an HTTP 200 OK response code and a representation of the requesting user if authentication was successful; returns a 401 status code and an error message if not. Use this method to test if supplied user credentials are valid.
*/
func verifyAccountCredentials(includeEntities: Bool? = nil,
skipStatus: Bool? = nil,
includeEmail: Bool? = nil,
success: SuccessHandler? = nil,
failure: FailureHandler? = nil) {
let path = "account/verify_credentials.json"
var parameters = [String: Any]()
parameters["include_entities"] ??= includeEntities
parameters["skip_status"] ??= skipStatus
parameters["include_email"] ??= includeEmail
self.getJSON(path: path, baseURL: .api, parameters: parameters, success: { json, _ in
success?(json)
}, failure: failure)
}
/**
POST account/settings
Updates the authenticating user's settings.
*/
func updateAccountSettings(trendLocationWOEID: String? = nil,
sleepTimeEnabled: Bool? = nil,
startSleepTime: Int? = nil,
endSleepTime: Int? = nil,
timeZone: String? = nil,
lang: String? = nil,
success: SuccessHandler? = nil,
failure: FailureHandler? = nil) {
assert(trendLocationWOEID != nil || sleepTimeEnabled != nil || startSleepTime != nil || endSleepTime != nil || timeZone != nil || lang != nil, "At least one or more should be provided when executing this request")
let path = "account/settings.json"
var parameters = [String: Any]()
parameters["trend_location_woeid"] ??= trendLocationWOEID
parameters["sleep_time_enabled"] ??= sleepTimeEnabled
parameters["start_sleep_time"] ??= startSleepTime
parameters["end_sleep_time"] ??= endSleepTime
parameters["time_zone"] ??= timeZone
parameters["lang"] ??= lang
self.postJSON(path: path, baseURL: .api, parameters: parameters, success: { json, _ in success?(json) }, failure: failure)
}
/**
POST account/update_profile
Sets values that users are able to set under the "Account" tab of their settings page. Only the parameters specified will be updated.
*/
func updateUserProfile(name: String? = nil,
url: String? = nil,
location: String? = nil,
description: String? = nil,
includeEntities: Bool? = nil,
skipStatus: Bool? = nil,
success: SuccessHandler? = nil,
failure: FailureHandler? = nil) {
assert(name != nil || url != nil || location != nil || description != nil,
"At least one of name, url, location, description should be non-nil")
let path = "account/update_profile.json"
var parameters = [String: Any]()
parameters["name"] ??= name
parameters["url"] ??= url
parameters["location"] ??= location
parameters["description"] ??= description
parameters["include_entities"] ??= includeEntities
parameters["skip_status"] ??= skipStatus
self.postJSON(path: path, baseURL: .api, parameters: parameters, success: { json, _ in
success?(json)
}, failure: failure)
}
/**
POST account/update_profile_background_image
Updates the authenticating user's profile background image. This method can also be used to enable or disable the profile background image. Although each parameter is marked as optional, at least one of image, tile or use must be provided when making this request.
*/
func updateProfileBackground(using imageData: Data,
title: String? = nil,
includeEntities: Bool? = nil,
use: Bool? = nil,
success: SuccessHandler? = nil,
failure: FailureHandler? = nil) {
assert(title != nil || use != nil, "At least one of image, title or use must be provided when making this request")
let path = "account/update_profile_background_image.json"
var parameters = [String: Any]()
parameters["image"] = imageData.base64EncodedString(options: [])
parameters["title"] ??= title
parameters["include_entities"] ??= includeEntities
parameters["use"] ??= use
self.postJSON(path: path, baseURL: .api, parameters: parameters, success: { json, _ in
success?(json)
}, failure: failure)
}
/**
POST account/update_profile_colors
Sets one or more hex values that control the color scheme of the authenticating user's profile page on twitter.com. Each parameter's value must be a valid hexidecimal value, and may be either three or six characters (ex: #fff or #ffffff).
*/
func updateProfileColors(backgroundColor: String? = nil,
linkColor: String? = nil,
sidebarBorderColor: String? = nil,
sidebarFillColor: String? = nil,
textColor: String? = nil,
includeEntities: Bool? = nil,
skipStatus: Bool? = nil,
success: SuccessHandler? = nil,
failure: FailureHandler? = nil) {
let path = "account/update_profile_colors.json"
var parameters = [String: Any]()
parameters["profile_background_color"] ??= backgroundColor
parameters["profile_link_color"] ??= linkColor
parameters["profile_sidebar_link_color"] ??= sidebarBorderColor
parameters["profile_sidebar_fill_color"] ??= sidebarFillColor
parameters["profile_text_color"] ??= textColor
parameters["include_entities"] ??= includeEntities
parameters["skip_status"] ??= skipStatus
self.postJSON(path: path, baseURL: .api, parameters: parameters, success: { json, _ in
success?(json)
}, failure: failure)
}
/**
POST account/update_profile_image
Updates the authenticating user's profile image. Note that this method expects raw multipart data, not a URL to an image.
This method asynchronously processes the uploaded file before updating the user's profile image URL. You can either update your local cache the next time you request the user's information, or, at least 5 seconds after uploading the image, ask for the updated URL using GET users/show.
*/
func updateProfileImage(using imageData: Data,
includeEntities: Bool? = nil,
skipStatus: Bool? = nil,
success: SuccessHandler? = nil,
failure: FailureHandler? = nil) {
let path = "account/update_profile_image.json"
var parameters = [String: Any]()
parameters["image"] = imageData.base64EncodedString(options: [])
parameters["include_entities"] ??= includeEntities
parameters["skip_status"] ??= skipStatus
self.postJSON(path: path, baseURL: .api, parameters: parameters, success: { json, _ in
success?(json)
}, failure: failure)
}
/**
GET blocks/list
Returns a collection of user objects that the authenticating user is blocking.
*/
func getBlockedUsers(includeEntities: Bool? = nil,
skipStatus: Bool? = nil,
cursor: String? = nil,
success: CursorSuccessHandler? = nil,
failure: FailureHandler? = nil) {
let path = "blocks/list.json"
var parameters = [String: Any]()
parameters["include_entities"] ??= includeEntities
parameters["skip_status"] ??= skipStatus
parameters["cursor"] ??= cursor
self.getJSON(path: path, baseURL: .api, parameters: parameters, success: { json, _ in
success?(json["users"], json["previous_cursor_str"].string, json["next_cursor_str"].string)
}, failure: failure)
}
/**
GET blocks/ids
Returns an array of numeric user ids the authenticating user is blocking.
*/
func getBlockedUsersIDs(stringifyIDs: String? = nil,
cursor: String? = nil,
success: CursorSuccessHandler? = nil,
failure: FailureHandler? = nil) {
let path = "blocks/ids.json"
var parameters = [String: Any]()
parameters["stringify_ids"] ??= stringifyIDs
parameters["cursor"] ??= cursor
self.getJSON(path: path, baseURL: .api, parameters: parameters, success: { json, _ in
success?(json["ids"], json["previous_cursor_str"].string, json["next_cursor_str"].string)
}, failure: failure)
}
/**
POST blocks/create
Blocks the specified user from following the authenticating user. In addition the blocked user will not show in the authenticating users mentions or timeline (unless retweeted by another user). If a follow or friend relationship exists it is destroyed.
*/
func blockUser(_ userTag: UserTag,
includeEntities: Bool? = nil,
skipStatus: Bool? = nil,
success: SuccessHandler? = nil,
failure: FailureHandler? = nil) {
let path = "blocks/create.json"
var parameters = [String: Any]()
parameters[userTag.key] = userTag.value
parameters["include_entities"] ??= includeEntities
parameters["skip_status"] ??= skipStatus
self.postJSON(path: path, baseURL: .api, parameters: parameters, success: { json, _ in
success?(json)
}, failure: failure)
}
/**
POST blocks/destroy
Un-blocks the user specified in the ID parameter for the authenticating user. Returns the un-blocked user in the requested format when successful. If relationships existed before the block was instated, they will not be restored.
*/
func unblockUser(for userTag: UserTag,
includeEntities: Bool? = nil,
skipStatus: Bool? = nil,
success: SuccessHandler? = nil,
failure: FailureHandler? = nil) {
let path = "blocks/destroy.json"
var parameters = [String: Any]()
parameters[userTag.key] = userTag.value
parameters["include_entities"] ??= includeEntities
parameters["skip_status"] ??= skipStatus
self.postJSON(path: path, baseURL: .api, parameters: parameters, success: { json, _ in
success?(json)
}, failure: failure)
}
/**
GET users/lookup
Returns fully-hydrated user objects for up to 100 users per request, as specified by comma-separated values passed to the user_id and/or screen_name parameters.
This method is especially useful when used in conjunction with collections of user IDs returned from GET friends/ids and GET followers/ids.
GET users/show is used to retrieve a single user object.
There are a few things to note when using this method.
- You must be following a protected user to be able to see their most recent status update. If you don't follow a protected user their status will be removed.
- The order of user IDs or screen names may not match the order of users in the returned array.
- If a requested user is unknown, suspended, or deleted, then that user will not be returned in the results list.
- If none of your lookup criteria can be satisfied by returning a user object, a HTTP 404 will be thrown.
- You are strongly encouraged to use a POST for larger requests.
*/
func lookupUsers(for usersTag: UsersTag,
includeEntities: Bool? = nil,
success: SuccessHandler? = nil,
failure: FailureHandler? = nil) {
let path = "users/lookup.json"
var parameters = [String: Any]()
parameters[usersTag.key] = usersTag.value
parameters["include_entities"] ??= includeEntities
self.getJSON(path: path, baseURL: .api, parameters: parameters, success: { json, _ in
success?(json)
}, failure: failure)
}
/**
GET users/show
Returns a variety of information about the user specified by the required user_id or screen_name parameter. The author's most recent Tweet will be returned inline when possible. GET users/lookup is used to retrieve a bulk collection of user objects.
You must be following a protected user to be able to see their most recent Tweet. If you don't follow a protected user, the users Tweet will be removed. A Tweet will not always be returned in the current_status field.
*/
func showUser(_ userTag: UserTag,
includeEntities: Bool? = nil,
success: SuccessHandler? = nil,
failure: FailureHandler? = nil) {
let path = "users/show.json"
var parameters = [String: Any]()
parameters[userTag.key] = userTag.value
parameters["include_entities"] ??= includeEntities
self.getJSON(path: path, baseURL: .api, parameters: parameters, success: { json, _ in
success?(json)
}, failure: failure)
}
/**
GET users/search
Provides a simple, relevance-based search interface to public user accounts on Twitter. Try querying by topical interest, full name, company name, location, or other criteria. Exact match searches are not supported.
Only the first 1,000 matching results are available.
*/
func searchUsers(using query: String,
page: Int? = nil,
count: Int? = nil,
includeEntities: Bool? = nil,
success: SuccessHandler? = nil,
failure: FailureHandler? = nil) {
let path = "users/search.json"
var parameters = [String: Any]()
parameters["q"] = query
parameters["page"] ??= page
parameters["count"] ??= count
parameters["include_entities"] ??= includeEntities
self.getJSON(path: path, baseURL: .api, parameters: parameters, success: { json, _ in
success?(json)
}, failure: failure)
}
/**
POST account/remove_profile_banner
Removes the uploaded profile banner for the authenticating user. Returns HTTP 200 upon success.
*/
func removeProfileBanner(success: SuccessHandler? = nil, failure: FailureHandler? = nil) {
let path = "account/remove_profile_banner.json"
self.postJSON(path: path, baseURL: .api, parameters: [:], success: { json, _ in
success?(json)
}, failure: failure)
}
/**
POST account/update_profile_banner
Uploads a profile banner on behalf of the authenticating user. For best results, upload an <5MB image that is exactly 1252px by 626px. Images will be resized for a number of display options. Users with an uploaded profile banner will have a profile_banner_url node in their Users objects. More information about sizing variations can be found in User Profile Images and Banners and GET users/profile_banner.
Profile banner images are processed asynchronously. The profile_banner_url and its variant sizes will not necessary be available directly after upload.
If providing any one of the height, width, offset_left, or offset_top parameters, you must provide all of the sizing parameters.
HTTP Response Codes
200, 201, 202 Profile banner image succesfully uploaded
400 Either an image was not provided or the image data could not be processed
422 The image could not be resized or is too large.
*/
func updateProfileBanner(using imageData: Data,
width: Int? = nil,
height: Int? = nil,
offsetLeft: Int? = nil,
offsetTop: Int? = nil,
success: SuccessHandler? = nil,
failure: FailureHandler? = nil) {
let path = "account/update_profile_banner.json"
var parameters = [String: Any]()
parameters["banner"] = imageData.base64EncodedString
parameters["width"] ??= width
parameters["height"] ??= height
parameters["offset_left"] ??= offsetLeft
parameters["offset_top"] ??= offsetTop
self.postJSON(path: path, baseURL: .api, parameters: parameters, success: { json, _ in
success?(json)
}, failure: failure)
}
/**
GET users/profile_banner
Returns a map of the available size variations of the specified user's profile banner. If the user has not uploaded a profile banner, a HTTP 404 will be served instead. This method can be used instead of string manipulation on the profile_banner_url returned in user objects as described in User Profile Images and Banners.
*/
func getProfileBanner(for userTag: UserTag,
success: SuccessHandler? = nil,
failure: FailureHandler? = nil) {
let path = "users/profile_banner.json"
let parameters: [String: Any] = [userTag.key: userTag.value]
self.getJSON(path: path, baseURL: .api, parameters: parameters, success: { json, _ in
success?(json)
}, failure: failure)
}
/**
POST mutes/users/create
Mutes the user specified in the ID parameter for the authenticating user.
Returns the muted user in the requested format when successful. Returns a string describing the failure condition when unsuccessful.
Actions taken in this method are asynchronous and changes will be eventually consistent.
*/
func muteUser(_ userTag: UserTag,
success: SuccessHandler? = nil,
failure: FailureHandler? = nil) {
let path = "mutes/users/create.json"
let parameters: [String: Any] = [userTag.key: userTag.value]
self.postJSON(path: path, baseURL: .api, parameters: parameters, success: { json, _ in
success?(json)
}, failure: failure)
}
/**
POST mutes/users/destroy
Un-mutes the user specified in the ID parameter for the authenticating user.
Returns the unmuted user in the requested format when successful. Returns a string describing the failure condition when unsuccessful.
Actions taken in this method are asynchronous and changes will be eventually consistent.
*/
func unmuteUser(for userTag: UserTag,
success: SuccessHandler? = nil,
failure: FailureHandler? = nil) {
let path = "mutes/users/destroy.json"
let parameters = [userTag.key: userTag.value]
self.postJSON(path: path, baseURL: .api, parameters: parameters, success: { json, _ in
success?(json)
}, failure: failure)
}
/**
GET mutes/users/ids
Returns an array of numeric user ids the authenticating user has muted.
*/
func getMuteUsersIDs(cursor: String? = nil,
success: CursorSuccessHandler? = nil,
failure: FailureHandler? = nil) {
let path = "mutes/users/ids.json"
var parameters = [String: Any]()
parameters["cursor"] ??= cursor
self.getJSON(path: path, baseURL: .api, parameters: parameters, success: { json, _ in
success?(json["ids"], json["previous_cursor_str"].string, json["next_cursor_str"].string)
}, failure: failure)
}
/**
GET mutes/users/list
Returns an array of user objects the authenticating user has muted.
*/
func getMutedUsers(cursor: String? = nil,
includeEntities: Bool? = nil,
skipStatus: Bool? = nil,
success: CursorSuccessHandler? = nil,
failure: FailureHandler? = nil) {
let path = "mutes/users/list.json"
var parameters = [String: Any]()
parameters["include_entities"] ??= includeEntities
parameters["skip_status"] ??= skipStatus
parameters["cursor"] ??= cursor
self.getJSON(path: path, baseURL: .api, parameters: parameters, success: { json, _ in
success?(json["users"], json["previous_cursor_str"].string, json["next_cursor_str"].string)
}, failure: failure)
}
}
| mit | fc43906d7ff215430edb6354ed87a6bc | 42.473786 | 411 | 0.619456 | 4.739416 | false | false | false | false |
gerardogrisolini/Webretail | Sources/Webretail/Models/Registry.swift | 1 | 3527 | //
// Registry.swift
// Webretail
//
// Created by Gerardo Grisolini on 13/03/17.
//
//
import StORM
import Turnstile
import TurnstileCrypto
class Registry: PostgresSqlORM, Codable, Account {
public var registryId : Int = 0
public var registryName : String = ""
public var registryEmail : String = ""
public var registryPassword : String = ""
public var registryPhone : String = ""
public var registryAddress : String = ""
public var registryCity : String = ""
public var registryZip : String = ""
public var registryProvince : String = ""
public var registryCountry : String = ""
public var registryFiscalCode : String = ""
public var registryVatNumber : String = ""
public var registryCreated : Int = Int.now()
public var registryUpdated : Int = Int.now()
/// The User account's Unique ID
public var uniqueID: String {
return registryId.description
}
private enum CodingKeys: String, CodingKey {
case registryId
case registryName
case registryEmail
case registryPhone
case registryAddress
case registryCity
case registryZip
case registryProvince
case registryCountry
case registryFiscalCode
case registryVatNumber
case registryUpdated = "updatedAt"
}
open override func table() -> String { return "registries" }
open override func tableIndexes() -> [String] { return ["registryName", "registryEmail"] }
open override func to(_ this: StORMRow) {
registryId = this.data["registryid"] as? Int ?? 0
registryName = this.data["registryname"] as? String ?? ""
registryEmail = this.data["registryemail"] as? String ?? ""
registryPassword = this.data["registrypassword"] as? String ?? ""
registryPhone = this.data["registryphone"] as? String ?? ""
registryAddress = this.data["registryaddress"] as? String ?? ""
registryCity = this.data["registrycity"] as? String ?? ""
registryZip = this.data["registryzip"] as? String ?? ""
registryProvince = this.data["registryprovince"] as? String ?? ""
registryCountry = this.data["registrycountry"] as? String ?? ""
registryFiscalCode = this.data["registryfiscalcode"] as? String ?? ""
registryVatNumber = this.data["registryvatnumber"] as? String ?? ""
registryCreated = this.data["registrycreated"] as? Int ?? 0
registryUpdated = this.data["registryupdated"] as? Int ?? 0
}
func rows() -> [Registry] {
var rows = [Registry]()
for i in 0..<self.results.rows.count {
let row = Registry()
row.to(self.results.rows[i])
rows.append(row)
}
return rows
}
func get(email: String) throws {
try query(
whereclause: "registryEmail = $1",
params: [email],
cursor: StORMCursor(limit: 1, offset: 0)
)
if self.results.rows.count == 0 {
throw StORMError.noRecordFound
}
}
/// Performs a find on supplied email, and matches hashed password
open func get(_ email: String, _ pwd: String) throws -> Registry {
try get(email: email)
if try BCrypt.verify(password: pwd, matchesHash: registryPassword) {
return self
} else {
throw StORMError.noRecordFound
}
}
/// Returns a true / false depending on if the email exits in the database.
func exists(_ email: String) -> Bool {
do {
try get(email: email)
return true
} catch {
return false
}
}
}
| apache-2.0 | 1e7d1169c8d4a0531419d8de524f80ae | 31.063636 | 91 | 0.635101 | 4.082176 | false | false | false | false |
MaddTheSane/WWDC | WWDC/TranscriptViewController.swift | 1 | 3905 | //
// TranscriptViewController.swift
// WWDC
//
// Created by Guilherme Rambo on 19/12/15.
// Copyright © 2015 Guilherme Rambo. All rights reserved.
//
import Cocoa
import RealmSwift
class TranscriptViewController: NSViewController, NSTableViewDelegate, NSTableViewDataSource {
var session: Session!
var jumpToTimeCallback: (time: Double) -> () = { _ in }
@IBOutlet weak var searchContainer: NSVisualEffectView!
@IBOutlet weak var searchField: NSSearchField!
var filteredLines: Results<TranscriptLine> {
return session.transcript!.lines.filter("text CONTAINS[c] %@", searchField.stringValue)
}
var font: NSFont? {
didSet {
tableView.reloadData()
}
}
var textColor: NSColor? {
didSet {
tableView.reloadData()
}
}
var backgroundColor: NSColor? {
didSet {
guard let backgroundColor = backgroundColor else { return }
tableView.backgroundColor = backgroundColor
}
}
var enableScrolling = true
@IBOutlet weak var scrollView: NSScrollView!
@IBOutlet weak private var tableView: NSTableView!
private struct Storyboard {
static let cellIdentifier = "transcriptCell"
static let rowIdentifier = "rowView"
}
init(session: Session) {
self.session = session
super.init(nibName: "TranscriptViewController", bundle: nil)!
}
required init?(coder: NSCoder) {
self.session = nil
super.init(coder: coder)
}
override func viewDidLoad() {
super.viewDidLoad()
tableView.setDelegate(self)
tableView.setDataSource(self)
tableView.target = self
tableView.doubleAction = Selector("doubleClickedLine:")
scrollView.automaticallyAdjustsContentInsets = false
scrollView.contentInsets = NSEdgeInsets(top: 22.0, left: 0.0, bottom: NSHeight(searchContainer.bounds), right: 0.0)
}
func highlightLineAt(roundedTimecode: String) {
guard enableScrolling else { return }
guard let lines = session.transcript?.lines else { return }
let result = lines.filter { Transcript.roundedStringFromTimecode($0.timecode) == roundedTimecode }
guard result.count > 0 else { return }
guard let row = lines.indexOf(result[0]) else { return }
tableView.selectRowIndexes(NSIndexSet(index: row), byExtendingSelection: false)
tableView.scrollRowToVisible(row)
}
// MARK: - TableView
func numberOfRowsInTableView(tableView: NSTableView) -> Int {
return filteredLines.count
}
func tableView(tableView: NSTableView, viewForTableColumn tableColumn: NSTableColumn?, row: Int) -> NSView? {
let cell = tableView.makeViewWithIdentifier(Storyboard.cellIdentifier, owner: tableView) as! TranscriptLineTableCellView
cell.foregroundColor = textColor
cell.font = font
cell.line = filteredLines[row]
return cell
}
func tableView(tableView: NSTableView, rowViewForRow row: Int) -> NSTableRowView? {
return tableView.makeViewWithIdentifier(Storyboard.rowIdentifier, owner: tableView) as? NSTableRowView
}
func tableView(tableView: NSTableView, heightOfRow row: Int) -> CGFloat {
guard let font = font else { return 17.0 }
return font.pointSize * 2
}
func doubleClickedLine(sender: AnyObject?) {
let line = filteredLines[tableView.clickedRow]
jumpToTimeCallback(time: line.timecode)
}
// MARK: - Search
@IBAction func search(sender: NSSearchField) {
// disables scrolling during search
enableScrolling = (sender.stringValue == "")
tableView.reloadData()
}
}
| bsd-2-clause | 468664f54888af446d77ba30a31f1ef1 | 29.263566 | 128 | 0.639344 | 5.164021 | false | false | false | false |
dtrauger/Charts | Source/ChartsRealm/Data/RealmBarDataSet.swift | 1 | 8271 | //
// RealmBarDataSet.swift
// Charts
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/Charts
//
import Foundation
import CoreGraphics
#if NEEDS_CHARTS
import Charts
#endif
import Realm
import Realm.Dynamic
open class RealmBarDataSet: RealmBarLineScatterCandleBubbleDataSet, IBarChartDataSet
{
open override func initialize()
{
self.highlightColor = NSUIColor.black
}
public required init()
{
super.init()
}
public override init(results: RLMResults<RLMObject>?, xValueField: String?, yValueField: String, label: String?)
{
super.init(results: results, xValueField: xValueField, yValueField: yValueField, label: label)
}
public init(results: RLMResults<RLMObject>?, xValueField: String?, yValueField: String, stackValueField: String, label: String?)
{
_stackValueField = stackValueField
super.init(results: results, xValueField: xValueField, yValueField: yValueField, label: label)
}
public convenience init(results: RLMResults<RLMObject>?, xValueField: String?, yValueField: String, stackValueField: String)
{
self.init(results: results, xValueField: xValueField, yValueField: yValueField, stackValueField: stackValueField, label: "DataSet")
}
public convenience init(results: RLMResults<RLMObject>?, yValueField: String, stackValueField: String, label: String)
{
self.init(results: results, xValueField: nil, yValueField: yValueField, stackValueField: stackValueField, label: label)
}
public convenience init(results: RLMResults<RLMObject>?, yValueField: String, stackValueField: String)
{
self.init(results: results, xValueField: nil, yValueField: yValueField, stackValueField: stackValueField)
}
public override init(realm: RLMRealm?, modelName: String, resultsWhere: String, xValueField: String?, yValueField: String, label: String?)
{
super.init(realm: realm, modelName: modelName, resultsWhere: resultsWhere, xValueField: xValueField, yValueField: yValueField, label: label)
}
public init(realm: RLMRealm?, modelName: String, resultsWhere: String, xValueField: String?, yValueField: String, stackValueField: String, label: String?)
{
_stackValueField = stackValueField
super.init(realm: realm, modelName: modelName, resultsWhere: resultsWhere, xValueField: xValueField, yValueField: yValueField, label: label)
}
public convenience init(realm: RLMRealm?, modelName: String, resultsWhere: String, xValueField: String?, yValueField: String, stackValueField: String)
{
self.init(realm: realm, modelName: modelName, resultsWhere: resultsWhere, xValueField: nil, yValueField: yValueField, stackValueField: stackValueField)
}
public convenience init(realm: RLMRealm?, modelName: String, resultsWhere: String, yValueField: String, stackValueField: String, label: String?)
{
self.init(realm: realm, modelName: modelName, resultsWhere: resultsWhere, xValueField: nil, yValueField: yValueField, stackValueField: stackValueField, label: label)
}
public convenience init(realm: RLMRealm?, modelName: String, resultsWhere: String, yValueField: String, stackValueField: String)
{
self.init(realm: realm, modelName: modelName, resultsWhere: resultsWhere, xValueField: nil, yValueField: yValueField, stackValueField: stackValueField, label: nil)
}
open override func notifyDataSetChanged()
{
super.notifyDataSetChanged()
self.calcStackSize(entries: _cache as! [BarChartDataEntry])
}
// MARK: - Data functions and accessors
internal var _stackValueField: String?
/// the maximum number of bars that are stacked upon each other, this value
/// is calculated from the Entries that are added to the DataSet
fileprivate var _stackSize = 1
internal override func buildEntryFromResultObject(_ object: RLMObject, x: Double) -> ChartDataEntry
{
let value = object[_yValueField!]
let entry: BarChartDataEntry
if value is RLMArray
{
var values = [Double]()
let iterator = NSFastEnumerationIterator(value as! RLMArray)
while let val = iterator.next()
{
values.append((val as! RLMObject)[_stackValueField!] as! Double)
}
entry = BarChartDataEntry(x: _xValueField == nil ? x : object[_xValueField!] as! Double, yValues: values)
}
else
{
entry = BarChartDataEntry(x: _xValueField == nil ? x : object[_xValueField!] as! Double, y: value as! Double)
}
return entry
}
/// calculates the maximum stacksize that occurs in the Entries array of this DataSet
fileprivate func calcStackSize(entries: [BarChartDataEntry])
{
for i in 0 ..< entries.count
{
if let vals = entries[i].yValues
{
if vals.count > _stackSize
{
_stackSize = vals.count
}
}
}
}
open override func calcMinMax()
{
if _cache.count == 0
{
return
}
_yMax = -Double.greatestFiniteMagnitude
_yMin = Double.greatestFiniteMagnitude
_xMax = -Double.greatestFiniteMagnitude
_xMin = Double.greatestFiniteMagnitude
for e in _cache as! [BarChartDataEntry]
{
if !e.y.isNaN
{
if e.yValues == nil
{
if e.y < _yMin
{
_yMin = e.y
}
if e.y > _yMax
{
_yMax = e.y
}
}
else
{
if -e.negativeSum < _yMin
{
_yMin = -e.negativeSum
}
if e.positiveSum > _yMax
{
_yMax = e.positiveSum
}
}
if e.x < _xMin
{
_xMin = e.x
}
if e.x > _xMax
{
_xMax = e.x
}
}
}
}
/// - returns: The maximum number of bars that can be stacked upon another in this DataSet.
open var stackSize: Int
{
return _stackSize
}
/// - returns: `true` if this DataSet is stacked (stacksize > 1) or not.
open var isStacked: Bool
{
return _stackSize > 1 ? true : false
}
/// array of labels used to describe the different values of the stacked bars
open var stackLabels: [String] = ["Stack"]
// MARK: - Styling functions and accessors
/// the color used for drawing the bar-shadows. The bar shadows is a surface behind the bar that indicates the maximum value
open var barShadowColor = NSUIColor(red: 215.0/255.0, green: 215.0/255.0, blue: 215.0/255.0, alpha: 1.0)
/// the width used for drawing borders around the bars. If borderWidth == 0, no border will be drawn.
open var barBorderWidth : CGFloat = 0.0
/// the color drawing borders around the bars.
open var barBorderColor = NSUIColor(red: 0.0/255.0, green: 0.0/255.0, blue: 0.0/255.0, alpha: 1.0)
/// the alpha value (transparency) that is used for drawing the highlight indicator bar. min = 0.0 (fully transparent), max = 1.0 (fully opaque)
open var highlightAlpha = CGFloat(120.0 / 255.0)
// MARK: - NSCopying
open override func copyWithZone(_ zone: NSZone?) -> AnyObject
{
let copy = super.copyWithZone(zone) as! RealmBarDataSet
copy._stackSize = _stackSize
copy.stackLabels = stackLabels
copy.barShadowColor = barShadowColor
copy.highlightAlpha = highlightAlpha
return copy
}
}
| apache-2.0 | 6a3aaaa6dad71a1ad204a5cadad32706 | 34.805195 | 173 | 0.601257 | 5.052535 | false | false | false | false |
whitepixelstudios/Material | Sources/iOS/NavigationBar.swift | 1 | 6394 | /*
* Copyright (C) 2015 - 2017, Daniel Dahan and CosmicMind, Inc. <http://cosmicmind.com>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* * Neither the name of CosmicMind nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import UIKit
open class NavigationBar: UINavigationBar {
/// Will layout the view.
open var willLayout: Bool {
return 0 < bounds.width && 0 < bounds.height && nil != superview
}
/// Detail UILabel when in landscape for iOS 11.
fileprivate var toolbarToText: [Toolbar: String?]?
open override var intrinsicContentSize: CGSize {
return CGSize(width: bounds.width, height: bounds.height)
}
/// A preset wrapper around contentEdgeInsets.
open var contentEdgeInsetsPreset = EdgeInsetsPreset.none {
didSet {
contentEdgeInsets = EdgeInsetsPresetToValue(preset: contentEdgeInsetsPreset)
}
}
/// A reference to EdgeInsets.
@IBInspectable
open var contentEdgeInsets = EdgeInsets.zero {
didSet {
layoutSubviews()
}
}
/// A preset wrapper around interimSpace.
open var interimSpacePreset = InterimSpacePreset.interimSpace3 {
didSet {
interimSpace = InterimSpacePresetToValue(preset: interimSpacePreset)
}
}
/// A wrapper around grid.interimSpace.
@IBInspectable
open var interimSpace: InterimSpace = 0 {
didSet {
layoutSubviews()
}
}
/**
The back button image writes to the backIndicatorImage property and
backIndicatorTransitionMaskImage property.
*/
@IBInspectable
open var backButtonImage: UIImage? {
get {
return backIndicatorImage
}
set(value) {
let image: UIImage? = value
backIndicatorImage = image
backIndicatorTransitionMaskImage = image
}
}
/// A property that accesses the backing layer's background
@IBInspectable
open override var backgroundColor: UIColor? {
get {
return barTintColor
}
set(value) {
barTintColor = value
}
}
/**
An initializer that initializes the object with a NSCoder object.
- Parameter aDecoder: A NSCoder instance.
*/
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
prepare()
}
/**
An initializer that initializes the object with a CGRect object.
If AutoLayout is used, it is better to initilize the instance
using the init() initializer.
- Parameter frame: A CGRect instance.
*/
public override init(frame: CGRect) {
super.init(frame: frame)
prepare()
}
/// A convenience initializer.
public convenience init() {
self.init(frame: .zero)
}
open override func sizeThatFits(_ size: CGSize) -> CGSize {
return intrinsicContentSize
}
open override func layoutSubviews() {
super.layoutSubviews()
layoutShape()
layoutShadowPath()
if let v = topItem {
layoutNavigationItem(item: v)
}
if let v = backItem {
layoutNavigationItem(item: v)
}
layoutDivider()
}
/**
Prepares the view instance when intialized. When subclassing,
it is recommended to override the prepare method
to initialize property values and other setup operations.
The super.prepare method should always be called immediately
when subclassing.
*/
open func prepare() {
barStyle = .black
isTranslucent = false
depthPreset = .depth1
contentScaleFactor = Screen.scale
contentEdgeInsetsPreset = .square1
interimSpacePreset = .interimSpace3
backButtonImage = Icon.cm.arrowBack
if #available(iOS 11, *) {
toolbarToText = [:]
}
let image = UIImage()
shadowImage = image
setBackgroundImage(image, for: .default)
backgroundColor = .white
}
}
internal extension NavigationBar {
/**
Lays out the UINavigationItem.
- Parameter item: A UINavigationItem to layout.
*/
func layoutNavigationItem(item: UINavigationItem) {
guard willLayout else {
return
}
let toolbar = item.toolbar
toolbar.backgroundColor = .clear
toolbar.interimSpace = interimSpace
toolbar.contentEdgeInsets = contentEdgeInsets
if #available(iOS 11, *) {
if Application.shouldStatusBarBeHidden {
toolbar.contentEdgeInsetsPreset = .none
if nil != toolbar.detailLabel.text {
toolbarToText?[toolbar] = toolbar.detailLabel.text
toolbar.detailLabel.text = nil
}
} else if nil != toolbarToText?[toolbar] {
toolbar.detailLabel.text = toolbarToText?[toolbar] ?? nil
toolbarToText?[toolbar] = nil
}
}
item.titleView = toolbar
item.titleView!.frame = bounds
}
}
| bsd-3-clause | f59c9d09bc153f3f1cd55c671a6a5ea1 | 29.888889 | 88 | 0.657648 | 4.937452 | false | false | false | false |
materik/stubborn | Stubborn/Http/Regex.swift | 1 | 656 |
class Regex {
private(set) var pattern: String
private var regularExpresion: NSRegularExpression? {
return try? NSRegularExpression(pattern: self.pattern, options: .caseInsensitive)
}
init(_ pattern: String) {
self.pattern = pattern
}
func matches(_ string: String) -> Bool {
let range = (string as NSString).range(of: string)
let matches = self.regularExpresion?.matches(in: string, options: [], range: range)
return (matches?.count ?? 0) > 0
}
}
infix operator =~
func =~ (input: String, pattern: String) -> Bool {
return Regex(pattern).matches(input)
}
| mit | 3b5d526d946fb1e008a891dac772bbe0 | 24.230769 | 91 | 0.617378 | 4.125786 | false | false | false | false |
steelwheels/KiwiControls | UnitTest/OSX/UTNavigationBar/ViewController.swift | 1 | 1130 | //
// ViewController.swift
// UTNavigationBar
//
// Created by Tomoo Hamada on 2019/01/23.
// Copyright © 2019 Steel Wheels Project. All rights reserved.
//
import CoconutData
import KiwiControls
import Cocoa
class ViewController: NSViewController
{
public var console: CNConsole? = nil
@IBOutlet weak var mNavigationBar: KCNavigationBar!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
mNavigationBar.title = "Hello, World !!"
mNavigationBar.isLeftButtonEnabled = true
mNavigationBar.leftButtonTitle = "Left"
mNavigationBar.leftButtonPressedCallback = {
() -> Void in
CNLog(logLevel: .debug, message: "Left button pressed")
}
mNavigationBar.isRightButtonEnabled = true
mNavigationBar.rightButtonTitle = "Right"
mNavigationBar.rightButtonPressedCallback = {
() -> Void in
CNLog(logLevel: .debug, message: "Right button pressed")
}
let _ = KCLogManager.shared
CNPreference.shared.systemPreference.logLevel = .detail
}
override var representedObject: Any? {
didSet {
// Update the view, if already loaded.
}
}
}
| lgpl-2.1 | bea87e9cbc8eee04c8c64a4f4c60cd95 | 22.040816 | 63 | 0.730735 | 3.750831 | false | false | false | false |
michaelarmstrong/SuperMock | Example/Tests/SuperMockNSURLSessionConfigurationExtensionTests.swift | 1 | 1432 | //
// SuperMockNSURLSessionConfigurationExtensionTests.swift
// SuperMock_Tests
//
// Created by Scheggia on 21/01/2019.
// Copyright © 2019 CocoaPods. All rights reserved.
//
import XCTest
@testable import SuperMock
class SuperMockNSURLSessionConfigurationExtensionTests: XCTestCase {
func test_addProtocols_appendRecordingProtocols_whenRecording() {
SuperMock.beginRecording(Bundle(for: SuperMockNSURLSessionConfigurationExtensionTests.self))
let sut = URLSessionConfiguration.background(withIdentifier: "")
sut.addProtocols()
XCTAssertTrue(sut.protocolClasses?.first === SuperMockRecordingURLProtocol.self)
SuperMock.endRecording()
}
func test_addProtocols_appendMockingProtocols_whenRecording() {
SuperMock.beginMocking(Bundle(for: SuperMockNSURLSessionConfigurationExtensionTests.self))
let sut = URLSessionConfiguration.background(withIdentifier: "")
sut.addProtocols()
XCTAssertTrue(verify(protocols: sut.protocolClasses, contains: SuperMockURLProtocol.self), "SuperMockUrlProtocol is not the first protocol in \(String(describing: sut.protocolClasses))")
SuperMock.endMocking()
}
private func verify(protocols:[AnyClass]?, contains aClass: AnyClass) -> Bool {
return protocols?.contains(where: { classProtocol -> Bool in
return classProtocol === aClass
}) ?? false
}
}
| mit | 1b3d15f0f99acde416f673cd9a03a6bd | 37.675676 | 194 | 0.730957 | 5.222628 | false | true | false | false |
exchangegroup/swift-badge | Demo-iOS/ViewControllers/CreateBadgeFromCodeViewController.swift | 2 | 1916 | import BadgeSwift
class CreateBadgeFromCodeViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
createBadge()
}
private func createBadge() {
let badge = BadgeSwift()
view.addSubview(badge)
configureBadge(badge)
positionBadge(badge)
}
private func configureBadge(_ badge: BadgeSwift) {
// Text
badge.text = "2"
// Insets
badge.insets = CGSize(width: 12, height: 12)
// Font
badge.font = UIFont.preferredFont(forTextStyle: UIFont.TextStyle.body)
// Text color
badge.textColor = UIColor.yellow
// Badge color
badge.badgeColor = UIColor.black
// Shadow
badge.shadowOpacityBadge = 0.5
badge.shadowOffsetBadge = CGSize(width: 0, height: 0)
badge.shadowRadiusBadge = 1.0
badge.shadowColorBadge = UIColor.black
// No shadow
badge.shadowOpacityBadge = 0
// Border width and color
badge.borderWidth = 5.0
badge.borderColor = UIColor.magenta
}
private func positionBadge(_ badge: UIView) {
badge.translatesAutoresizingMaskIntoConstraints = false
var constraints = [NSLayoutConstraint]()
// Center the badge vertically in its container
constraints.append(NSLayoutConstraint(
item: badge,
attribute: NSLayoutConstraint.Attribute.centerY,
relatedBy: NSLayoutConstraint.Relation.equal,
toItem: view,
attribute: NSLayoutConstraint.Attribute.centerY,
multiplier: 1, constant: 0)
)
// Center the badge horizontally in its container
constraints.append(NSLayoutConstraint(
item: badge,
attribute: NSLayoutConstraint.Attribute.centerX,
relatedBy: NSLayoutConstraint.Relation.equal,
toItem: view,
attribute: NSLayoutConstraint.Attribute.centerX,
multiplier: 1, constant: 0)
)
view.addConstraints(constraints)
}
}
| mit | 2767d8fed216f5b532b18d9091dc99c9 | 25.246575 | 74 | 0.676931 | 4.850633 | false | false | false | false |
morisk/CalculatorKeyboard | paykeyboard/KeyboardDesign.swift | 1 | 1478 | //
// KeyboardDesign.swift
// paykeyboard
//
// Created by Moris Kramer on 16/6/16.
// Copyright © 2016 Paykeyboard. All rights reserved.
//
import Foundation
/**
* @brief describing design properties that we can manipulate
*/
@objc
public protocol KeyboardDesign {
var landscapeHeight: CGFloat { get }
var portraitHeight: CGFloat { get }
var backgroundColor: UIColor { get }
var keyBackgroundColor: UIColor { get }
var keyStokeColor: UIColor { get }
}
/**
* @brief Default values
*
*/
public class DefaultKeyboardDesign: NSObject, KeyboardDesign {
public var landscapeHeight: CGFloat = 180
public var portraitHeight: CGFloat = 290
public var backgroundColor: UIColor = UIColor.darkGrayColor()
public var keyBackgroundColor: UIColor = UIColor.grayColor()
public var keyStokeColor: UIColor = UIColor.lightGrayColor()
override public init() {}
}
// design element helpers
extension KeyboardDesign {
/// should be used to initialise design properties
///
/// - parameter background: keyboard background
/// - parameter buttons: calculator keys/buttons
func custom(background: UIView, buttons: [UIView]) {
setBackgroundColor(background)
setKeyStyle(buttons)
}
//MARK: Helpers
private func setBackgroundColor(view: UIView) {
view.backgroundColor = backgroundColor
}
private func setKeyStyle(views: [UIView]) {
_ = views.map {
$0.backgroundColor = keyBackgroundColor
$0.layer.borderColor = UIColor.lightGrayColor().CGColor
}
}
} | apache-2.0 | b94554318be7b99838498ae0d7c37f85 | 22.83871 | 62 | 0.737982 | 3.897098 | false | false | false | false |
EricConnerApps/SwiftyRadio | Examples/SwiftyRadio-tvOS/Pods/SwiftyRadio/Sources/SwiftyRadio.swift | 1 | 13330 | //
// SwiftyRadio.swift
// Swifty Radio
// Simple and easy way to build streaming radio apps for iOS, tvOS, & macOS
//
// Version 1.4.2
// Created by Eric Conner on 7/9/16.
// Copyright © 2017 Eric Conner Apps. All rights reserved.
//
import Foundation
import AVFoundation
// MARK: Typealiases
#if os(iOS) || os(tvOS)
import UIKit
import MediaPlayer
public typealias Image = UIImage
#elseif os(OSX)
import AppKit
public typealias Image = NSImage
#endif
/// Simple and easy way to build streaming radio apps for iOS, tvOS, & macOS
open class SwiftyRadio: NSObject {
//*****************************************************************
// MARK: - SwiftyRadio Variables
//*****************************************************************
fileprivate var Player: AVPlayer!
fileprivate var PlayerItem: AVPlayerItem!
fileprivate var track: Track!
fileprivate var stationInfo: StationInfo!
fileprivate struct Track {
var title: String = ""
var artist: String = ""
var isPlaying: Bool = false
}
fileprivate struct StationInfo {
var name: String = ""
var URL: String = ""
var shortDesc: String = ""
var stationArt: Image?
}
//*****************************************************************
// MARK: - Initialization Functions
//*****************************************************************
/// Initial setup for SwiftyRadio. Should be included in AppDelegate.swift under `didFinishLaunchingWithOptions`
open func setup() {
#if os(iOS) || os(tvOS)
NotificationCenter.default.addObserver(self, selector: #selector(audioRouteChangeListener(_:)), name: NSNotification.Name.AVAudioSessionRouteChange, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(audioInterruption(_:)), name: NSNotification.Name.AVAudioSessionInterruption, object: nil)
// Set AVFoundation category, required for background audio
do {
try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
try AVAudioSession.sharedInstance().setActive(true)
} catch {
print("SwiftyRadio Error: Setting category to AVAudioSessionCategoryPlayback failed")
}
setupRemote()
#endif
track = Track()
}
/// Setup the station, must be called before `Play()`
/// - parameter name: Name of the station
/// - parameter URL: The station URL
/// - parameter shortDesc: A short description of the station **(Not required)**
/// - parameter artwork: Image to display as album art **(Not required)**
open func setStation(name: String, URL: String, shortDesc: String = "", artwork: Image = Image()) {
stationInfo = StationInfo(name: name, URL: URL, shortDesc: shortDesc, stationArt: artwork)
track.title = stationInfo.shortDesc
track.artist = stationInfo.name
updateLockScreen()
NotificationCenter.default.post(name: Notification.Name(rawValue: "SwiftyRadioMetadataUpdated"), object: nil)
}
/// Setup the Control Center Remote
fileprivate func setupRemote() {
#if os(iOS) || os(tvOS)
if #available(iOS 7.1, tvOS 9.0, *) {
let center = MPRemoteCommandCenter.shared()
center.previousTrackCommand.isEnabled = false
center.nextTrackCommand.isEnabled = false
center.seekForwardCommand.isEnabled = false
center.seekBackwardCommand.isEnabled = false
center.skipForwardCommand.isEnabled = false
center.skipBackwardCommand.isEnabled = false
center.ratingCommand.isEnabled = false
center.changePlaybackRateCommand.isEnabled = false
center.likeCommand.isEnabled = false
center.dislikeCommand.isEnabled = false
center.bookmarkCommand.isEnabled = false
if #available(iOS 9.1, tvOS 9.1, *) {
center.changePlaybackPositionCommand.isEnabled = false
}
center.playCommand.addTarget { (commandEvent) -> MPRemoteCommandHandlerStatus in
self.play()
return MPRemoteCommandHandlerStatus.success
}
if #available(iOS 10.0, tvOS 10.0, *) {
center.pauseCommand.isEnabled = false
center.togglePlayPauseCommand.isEnabled = false
center.stopCommand.addTarget { (commandEvent) -> MPRemoteCommandHandlerStatus in
self.stop()
return MPRemoteCommandHandlerStatus.success
}
} else {
center.pauseCommand.addTarget { (commandEvent) -> MPRemoteCommandHandlerStatus in
self.stop()
return MPRemoteCommandHandlerStatus.success
}
center.togglePlayPauseCommand.addTarget { (commandEvent) -> MPRemoteCommandHandlerStatus in
self.togglePlayStop()
return MPRemoteCommandHandlerStatus.success
}
}
}
#endif
}
//*****************************************************************
// MARK: - General Functions
//*****************************************************************
/// Get the current playing track title. Use with notification `SwiftyRadioMetadataUpdated`
/// - returns: Text string of the track title.
open func trackTitle() -> String {
return track.title
}
/// Get the current playing track artist. Use with notification `SwiftyRadioMetadataUpdated`
/// - returns: Text string of the track artist.
open func trackArtist() -> String {
return track.artist
}
/// Get the current playing state
/// - returns: `True` if SwiftyRadio is playing and `False` if it is not
open func isPlaying() -> Bool {
return track.isPlaying
}
/// Plays the current set station. Uses notification `SwiftyRadioPlayWasPressed`
open func play() {
if stationInfo.URL != "" {
if !isPlaying() {
PlayerItem = AVPlayerItem(url: URL(string: stationInfo.URL)!)
PlayerItem.addObserver(self, forKeyPath: "timedMetadata", options: NSKeyValueObservingOptions.new, context: nil)
PlayerItem.addObserver(self, forKeyPath: "status", options: NSKeyValueObservingOptions.new, context: nil)
Player = AVPlayer(playerItem: PlayerItem)
Player.play()
track.isPlaying = true
NotificationCenter.default.post(name: Notification.Name(rawValue: "SwiftyRadioPlayWasPressed"), object: nil)
} else {
print("SwiftyRadio Error: Station is already playing")
}
} else {
print("SwiftyRadio Error: Station has not been setup")
}
}
/// Stops the current set station. Uses notification `SwiftyRadioStopWasPressed`
open func stop() {
if isPlaying() {
Player.pause()
PlayerItem.removeObserver(self, forKeyPath: "timedMetadata")
PlayerItem.removeObserver(self, forKeyPath: "status")
Player = nil
track.isPlaying = false
NotificationCenter.default.post(name: Notification.Name(rawValue: "SwiftyRadioStopWasPressed"), object: nil)
} else {
print("SwiftyRadio Error: Station is already stopped")
}
}
/// Toggles between `play()` and `stop()`. Uses notifications `SwiftyRadioPlayWasPressed` & `SwiftyRadioStopWasPressed`
open func togglePlayStop() {
if isPlaying() {
stop()
} else {
play()
}
}
/// Set the metadata to custom values. Uses notification `SwiftyRadioMetadataUpdated`
/// - parameter title: Custom metadata title
/// - parameter artist: Custom metadata artist **(If not provided the Station Name will be used)**
open func customMetadata(_ title: String, artist: String = "") {
track.title = title
track.artist = artist
if artist == "" {
track.artist = stationInfo.name
}
updateLockScreen()
NotificationCenter.default.post(name: Notification.Name(rawValue: "SwiftyRadioMetadataUpdated"), object: nil)
}
/// Update the lockscreen with the now playing information
fileprivate func updateLockScreen() {
#if os(iOS) || os(tvOS)
var songInfo = [:] as [String : Any]
if NSClassFromString("MPNowPlayingInfoCenter") != nil {
if stationInfo.stationArt != nil {
let image: UIImage = stationInfo.stationArt!
var artwork: MPMediaItemArtwork
if #available(iOS 10.0, tvOS 10.0, *) {
artwork = MPMediaItemArtwork.init(boundsSize: image.size, requestHandler: { (size) -> UIImage in
return image
})
} else {
artwork = MPMediaItemArtwork(image: image)
}
songInfo[MPMediaItemPropertyArtwork] = artwork
}
songInfo[MPMediaItemPropertyTitle] = track.title
songInfo[MPMediaItemPropertyArtist] = track.artist
if #available(iOS 10.0, tvOS 10.0, *) {
songInfo[MPNowPlayingInfoPropertyIsLiveStream] = true
}
MPNowPlayingInfoCenter.default().nowPlayingInfo = songInfo
}
#elseif os(OSX)
let notification = NSUserNotification()
notification.title = stationInfo.name
notification.subtitle = track.artist
notification.informativeText = track.title
notification.identifier = "com.ericconnerapps.SwiftyRadio"
if stationInfo.stationArt != nil {
notification.contentImage = stationInfo.stationArt
}
NSUserNotificationCenter.default.removeAllDeliveredNotifications()
NSUserNotificationCenter.default.deliver(notification)
#endif
}
/// Update the now playing artwork
/// - parameter image: Image to display as album art
open func updateArtwork(_ image: Image) {
stationInfo.stationArt = image
updateLockScreen()
}
/// Removes special characters from a text string
/// - parameter text: Text to be cleaned
/// - returns: Cleaned text
fileprivate func clean(_ text: String) -> String {
let safeChars : Set<Character> = Set("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLKMNOPQRSTUVWXYZ1234567890'- []".characters)
return String(text.characters.filter { safeChars.contains($0) })
}
//*****************************************************************
// MARK: - Notification Functions
//*****************************************************************
/// Informs the observing object when the value at the specified key path relative to the observed object has changed.
/// - parameter keyPath: The key path, relative to object, to the value that has changed.
/// - parameter object: The source object of the key path keyPath.
/// - parameter change: A dictionary that describes the changes that have been made to the value of the property at the key path keyPath relative to object. Entries are described in Change Dictionary Keys.
/// - parameter context: The value that was provided when the observer was registered to receive key-value observation notifications.
override open func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
/// Called when the player item status changes
if keyPath == "status" {
if PlayerItem.status == AVPlayerItemStatus.failed {
stop()
customMetadata("\(stationInfo.name) is offline", artist: "Please try again later")
NotificationCenter.default.post(name: Notification.Name(rawValue: "SwiftyRadioStationOffline"), object: nil)
}
}
/// Called when new song metadata is available
if keyPath == "timedMetadata" {
if(PlayerItem.timedMetadata != nil && PlayerItem.timedMetadata!.count > 0) {
let metaData = PlayerItem.timedMetadata!.first!.value as! String
let cleanedMetadata = clean(metaData)
// Remove junk song code i.e. [4T3]
var removeSongCode = [String]()
removeSongCode = cleanedMetadata.components(separatedBy: " [")
// Separate metadata by " - "
var metadataParts = [String]()
metadataParts = removeSongCode[0].components(separatedBy: " - ")
// Set artist to the station name if it is blank or unknown
switch metadataParts[0] {
case "", "Unknown", "unknown":
track.artist = stationInfo.name
default:
track.artist = metadataParts[0]
}
if metadataParts.count > 0 {
// Remove artist and join remaining values for song title
metadataParts.remove(at: 0)
let combinedTitle = metadataParts.joined(separator: " - ")
track.title = combinedTitle
} else {
// If the song title is missing
track.title = metadataParts[0]
track.artist = stationInfo.name
}
// If the track title is still blank use the station description
if track.title == "" {
track.title = stationInfo.shortDesc
}
print("SwiftyRadio: METADATA - artist: \(track.artist) | title: \(track.title)")
updateLockScreen()
NotificationCenter.default.post(name: Notification.Name(rawValue: "SwiftyRadioMetadataUpdated"), object: nil)
}
}
}
#if os(iOS) || os(tvOS)
/// Called when when the current audio routing changes
@objc fileprivate func audioRouteChangeListener(_ notification: Notification) {
DispatchQueue.main.async(execute: {
let audioRouteChangeReason = notification.userInfo![AVAudioSessionRouteChangeReasonKey] as! UInt
// Stop audio when headphones are removed
if AVAudioSessionRouteChangeReason.oldDeviceUnavailable.rawValue == audioRouteChangeReason {
if self.isPlaying() {
self.stop()
}
print("SwiftyRadio: Audio Device was removed")
}
})
}
/// Called when the current audio is interrupted
@objc fileprivate func audioInterruption(_ notification: Notification) {
DispatchQueue.main.async(execute: {
let audioInterruptionReason = notification.userInfo![AVAudioSessionInterruptionTypeKey] as! UInt
// Stop audio when a phone call is received
if AVAudioSessionInterruptionType.began.rawValue == audioInterruptionReason {
if self.isPlaying() {
self.stop()
}
print("SwiftyRadio: Interruption Began")
}
if AVAudioSessionInterruptionType.ended.rawValue == audioInterruptionReason {
print("SwiftyRadio: Interruption Ended")
}
})
}
#endif
}
| mit | 7452e0778bb6cbee41eaa5e57bd4e8f7 | 34.639037 | 206 | 0.6933 | 4.235462 | false | false | false | false |
tsolomko/SWCompression | Sources/swcomp/Extensions/GzipHeader+CustomStringConvertible.swift | 1 | 703 | // Copyright (c) 2022 Timofey Solomko
// Licensed under MIT License
//
// See LICENSE for license information
import Foundation
import SWCompression
extension GzipHeader: CustomStringConvertible {
public var description: String {
var output = """
File name: \(self.fileName ?? "")
File system type: \(self.osType)
Compression method: \(self.compressionMethod)
"""
if let mtime = self.modificationTime {
output += "Modification time: \(mtime)\n"
}
if let comment = self.comment {
output += "Comment: \(comment)\n"
}
output += "Is text file: \(self.isTextFile)"
return output
}
}
| mit | a2e0be0e352df889854bb2b2b791aa66 | 24.107143 | 53 | 0.59744 | 4.564935 | false | false | false | false |
aniluyg/AUForms | Examples/SampleFormPage/SampleFormPage/AUForms/Validations/AUControlValidator.swift | 2 | 2160 | //
// AUControlValidator.swift
// Copyright (c) 2015 Anıl Uygun
//
// 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
class AUControlValidator:Equatable{
private var validationTypes = [AUValidationChecking]()
weak var delegate : AUValidatable?
init(){
}
func validate() -> Bool{
let AUValidatableValue: AnyObject? = delegate?.getValidationValue()
for type in validationTypes{
if !type.check(AUValidatableValue){
let errorMsg = type.getErrorMessage()
delegate?.setValidationError(errorMsg)
return false
} else{
delegate?.setValidationSuccess()
}
}
return true
}
//Fluent interface for readability
func addRule(newRule:AUValidationChecking)->AUControlValidator{
self.validationTypes.append(newRule)
return self
}
}
//TODO: Use indexof() func instead of this in swift 2.0
func == (lhs: AUControlValidator, rhs: AUControlValidator) -> Bool {
return lhs === rhs
}
| mit | 8f723606cace9fb0be7a8f5015447d84 | 36.224138 | 82 | 0.679944 | 4.633047 | false | false | false | false |
a2/Oberholz | Example/Oberholz/AppDelegate.swift | 1 | 2500 | import Oberholz
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
let window = UIWindow(frame: UIScreen.mainScreen().bounds)
window.rootViewController = {
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let master = storyboard.instantiateViewControllerWithIdentifier("MasterViewController")
let detail = storyboard.instantiateViewControllerWithIdentifier("DetailViewController")
return OberholzViewController(masterViewController: master, detailViewController: detail)
}()
window.makeKeyAndVisible()
self.window = window
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| mit | f0be453dcb01a0e9010441f1329dca1a | 53.347826 | 285 | 0.7496 | 5.910165 | false | false | false | false |
steveholt55/Wage-Calculator-Swift | Classes/MoneyCalculator.swift | 1 | 1356 | //
// Copyright © 2015 Brandon Jenniges. All rights reserved.
//
import Foundation
class MoneyCalculator: NSObject {
var wage: Double = 0.0
let formatter = NumberFormatter()
static let wageKey = "savedWage"
static let userDefaults = UserDefaults.standard
override init() {
self.wage = MoneyCalculator.getSavedWage()
self.formatter.numberStyle = .currency
self.formatter.minimumIntegerDigits = 1
self.formatter.minimumFractionDigits = 2
self.formatter.maximumFractionDigits = 2
super.init()
}
func updateWage() {
self.wage = MoneyCalculator.getSavedWage()
}
func getMoneyDisplay(_ seconds: Int) -> String {
let factor: Double = Double(seconds) / 3600
return "\(formatter.string(from: NSNumber(value: wage * factor))!)"
}
static func getSavedWage() -> Double {
return userDefaults.double(forKey: wageKey)
}
static func saveWage(_ wage: Double) {
userDefaults.set(wage, forKey: wageKey)
userDefaults.synchronize()
}
func formatStringToCurrency(_ string: String) -> String? {
if let doubleValue = Double(string) {
return self.formatter.string(from: NSNumber(value: doubleValue))
}
return nil
}
}
| mit | 8e43ed36ac4df07bca3373445f19fe2b | 25.057692 | 76 | 0.616236 | 4.486755 | false | false | false | false |
dmorrow/UTSwiftUtils | Classes/Base/NSMutableAttributedString+UT.swift | 1 | 7340 | //
// NSMutableAttributedString+UT.swift
//
// Created by Daniel Morrow on 10/25/16.
// Copyright © 2016 unitytheory. All rights reserved.
//
import Foundation
import CoreGraphics
import UIKit
import CoreText
@available(iOS 9, *)
extension NSMutableAttributedString
{
public var range:NSRange {
get {
return NSMakeRange(0, self.length)
}
}
public func setMultiple(_ properties:NSDictionary) {
for (key, value) in properties
{
//NSAssert([self respondsToSelector:NSSelectorFromString(key)], @"trying to set nonexistant property: '%@'", key)
self.setValue(value, forKey: key as! String)
}
}
public func setAttribute(_ name: NSAttributedString.Key, value:AnyObject) {
self.removeAttribute(name, range: self.range)
self.addAttribute(name, value: value, range: self.range)
}
public var backgroundColor:UIColor {
get {
return self.attribute(NSAttributedString.Key.backgroundColor, at: 0, effectiveRange: nil) as! UIColor
}
set {
self.setAttribute(NSAttributedString.Key.backgroundColor, value: newValue)
}
}
public var baselineOffset:CGFloat {
get {
return CGFloat(((self.attribute(NSAttributedString.Key.baselineOffset, at: 0, effectiveRange: nil) as AnyObject).floatValue)!)
}
set {
self.setAttribute(NSAttributedString.Key.baselineOffset, value: newValue as AnyObject)
}
}
public var font:UIFont {
get {
return self.attribute(NSAttributedString.Key.font, at: 0, effectiveRange: nil) as! UIFont
}
set {
self.setAttribute(NSAttributedString.Key.font, value: newValue)
}
}
public var color:UIColor {
get {
return self.attribute(NSAttributedString.Key.foregroundColor, at: 0, effectiveRange: nil) as! UIColor
}
set {
self.setAttribute(NSAttributedString.Key.foregroundColor, value: newValue)
}
}
public var kerning:CGFloat {
get {
return CGFloat(((self.attribute(NSAttributedString.Key.kern, at: 0, effectiveRange: nil) as AnyObject).floatValue)!)
}
set {
self.setAttribute(NSAttributedString.Key.kern, value: newValue as AnyObject)
}
}
public var photoshopKerning:CGFloat {
get {
return self.kerning * 1000.0 / self.font.pointSize
}
set {
self.kerning = NSMutableAttributedString.kerningFromPhotoshopKerning(photoshopKerning, pointSize: self.font.pointSize)
}
}
public static func kerningFromPhotoshopKerning(_ psKerning:CGFloat, pointSize:CGFloat)->CGFloat {
return psKerning / 1000.0 * pointSize
}
public var ligature:Int {
get {
return ((self.attribute(NSAttributedString.Key.ligature, at: 0, effectiveRange: nil) as AnyObject).intValue)!
}
set {
self.setAttribute(NSAttributedString.Key.ligature, value: newValue as AnyObject)
}
}
public var link:URL {
get {
return self.attribute(NSAttributedString.Key.link, at: 0, effectiveRange: nil) as! URL
}
set {
self.setAttribute(NSAttributedString.Key.link, value: newValue as AnyObject)
}
}
public var strokeWidth:CGFloat {
get {
return CGFloat(((self.attribute(NSAttributedString.Key.strokeWidth, at: 0, effectiveRange: nil) as AnyObject).floatValue)!)
}
set {
self.setAttribute(NSAttributedString.Key.strokeWidth, value: newValue as AnyObject)
}
}
public var strokeColor:UIColor {
get {
return self.attribute(NSAttributedString.Key.strokeColor, at: 0, effectiveRange: nil) as! UIColor
}
set {
self.setAttribute(NSAttributedString.Key.strokeColor, value: newValue)
}
}
var superscript:Int {
get {
return ((self.attribute(NSAttributedString.Key(rawValue: String(kCTSuperscriptAttributeName)), at: 0, effectiveRange: nil) as AnyObject).intValue)!
}
set {
self.setAttribute(NSAttributedString.Key(rawValue: String(kCTSuperscriptAttributeName)), value: newValue as AnyObject)
}
}
public var underlineColor:UIColor {
get {
return self.attribute(NSAttributedString.Key.underlineColor, at: 0, effectiveRange: nil) as! UIColor
}
set {
self.setAttribute(NSAttributedString.Key.underlineColor, value: newValue)
}
}
public var underlineStyle:NSUnderlineStyle {
get {
if let style = self.attribute(NSAttributedString.Key.underlineStyle, at: 0, effectiveRange: nil) as? NSUnderlineStyle {
return style
}
return []
}
set {
self.setAttribute(NSAttributedString.Key.underlineStyle, value: newValue.rawValue as AnyObject)
}
}
public var paragraphStyle:NSParagraphStyle {
get {
if let existingParagraphStyle = self.attribute(NSAttributedString.Key.paragraphStyle, at: 0, effectiveRange: nil) as? NSParagraphStyle {
return existingParagraphStyle
}
return NSParagraphStyle.default
}
set {
self.setAttribute(NSAttributedString.Key.paragraphStyle, value: newValue)
}
}
fileprivate var mutableParagraphStyle: NSMutableParagraphStyle {
return self.paragraphStyle.mutableCopy() as! NSMutableParagraphStyle
}
public var lineSpacing:CGFloat {
get {
return self.paragraphStyle.lineSpacing
}
set {
let paragraphStyle = self.mutableParagraphStyle
paragraphStyle.lineSpacing = newValue
self.paragraphStyle = paragraphStyle
}
}
public var alignment:NSTextAlignment {
get {
return self.paragraphStyle.alignment
}
set {
let paragraphStyle = self.mutableParagraphStyle
paragraphStyle.alignment = newValue
self.paragraphStyle = paragraphStyle
}
}
public var paragraphSpacing:CGFloat {
get {
return self.paragraphStyle.paragraphSpacing
}
set {
let paragraphStyle = self.mutableParagraphStyle
paragraphStyle.paragraphSpacing = newValue
self.paragraphStyle = paragraphStyle
}
}
public var lineHeightMultiple:CGFloat {
get {
return self.paragraphStyle.lineHeightMultiple
}
set {
let paragraphStyle = self.mutableParagraphStyle
paragraphStyle.lineHeightMultiple = newValue
self.paragraphStyle = paragraphStyle
}
}
public var lineBreakMode:NSLineBreakMode {
get {
return self.paragraphStyle.lineBreakMode
}
set {
let paragraphStyle = self.mutableParagraphStyle
paragraphStyle.lineBreakMode = newValue
self.paragraphStyle = paragraphStyle
}
}
}
| mit | 02fa4230102652e5cd7e9d2ac55c88e9 | 30.908696 | 159 | 0.613435 | 5.349125 | false | false | false | false |
rahul-apple/XMPP-Zom_iOS | Zom/Zom/Classes/View Controllers/ZomStickerPackTableViewController.swift | 1 | 3862 | //
// ZomStickerPackListViewController.swift
// Zom
//
// Created by N-Pex on 2015-11-12.
//
//
import UIKit
import Photos
public class ZomStickerPackTableViewController: UIPageViewController, UIPageViewControllerDataSource, UIPageViewControllerDelegate {
private var stickerPacks: Array<String> = [];
private(set) lazy var orderedViewControllers: [UIViewController] = []
public override func viewDidLoad() {
super.viewDidLoad()
let docsPath = NSBundle.mainBundle().resourcePath! + "/Stickers"
let fileManager = NSFileManager.defaultManager()
do {
stickerPacks = try fileManager.contentsOfDirectoryAtPath(docsPath)
} catch {
print(error)
}
// Create view controllers
for stickerPack in stickerPacks {
let vc:ZomPickStickerViewController = self.storyboard?.instantiateViewControllerWithIdentifier("pickStickerViewController") as! ZomPickStickerViewController
vc.stickerPack = stickerPack
orderedViewControllers.append(vc)
}
dataSource = self
delegate = self
if let firstViewController:ZomPickStickerViewController = orderedViewControllers.first as? ZomPickStickerViewController {
self.navigationItem.title = firstViewController.stickerPack
setViewControllers([firstViewController],
direction: .Forward,
animated: true,
completion: nil)
}
}
public func pageViewController(pageViewController: UIPageViewController,
viewControllerBeforeViewController viewController: UIViewController) -> UIViewController? {
guard let viewControllerIndex = orderedViewControllers.indexOf(viewController) else {
return nil
}
let previousIndex = viewControllerIndex - 1
guard previousIndex >= 0 else {
return nil
}
guard orderedViewControllers.count > previousIndex else {
return nil
}
return orderedViewControllers[previousIndex]
}
public func pageViewController(pageViewController: UIPageViewController,
viewControllerAfterViewController viewController: UIViewController) -> UIViewController? {
guard let viewControllerIndex = orderedViewControllers.indexOf(viewController) else {
return nil
}
let nextIndex = viewControllerIndex + 1
let orderedViewControllersCount = orderedViewControllers.count
guard orderedViewControllersCount != nextIndex else {
return nil
}
guard orderedViewControllersCount > nextIndex else {
return nil
}
return orderedViewControllers[nextIndex]
}
public func presentationCountForPageViewController(pageViewController: UIPageViewController) -> Int {
return orderedViewControllers.count
}
public func presentationIndexForPageViewController(pageViewController: UIPageViewController) -> Int {
guard let firstViewController = viewControllers?.first,
firstViewControllerIndex = orderedViewControllers.indexOf(firstViewController) else {
return 0
}
return firstViewControllerIndex
}
public func pageViewController(pageViewController: UIPageViewController, didFinishAnimating finished: Bool, previousViewControllers: [UIViewController], transitionCompleted completed: Bool) {
if let vc:ZomPickStickerViewController = pageViewController.viewControllers?[0] as? ZomPickStickerViewController {
self.navigationItem.title = vc.stickerPack
}
}
}
| mpl-2.0 | 004c05c4fb40322bb801fae995fbeb05 | 36.495146 | 195 | 0.659762 | 7.165121 | false | false | false | false |
tomquist/CoreJSON | Tests/CoreJSONFoundationTests/CoreJSONToFoundationTests.swift | 1 | 3058 | /**
* CoreJSON
*
* Copyright (c) 2016 Tom Quist. Licensed under the MIT license, as follows:
*
* 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 XCTest
import CoreJSON
import CoreJSONFoundation
class CoreJSONToFoundationTests: XCTestCase {
func testString() {
let json = JSON.string("string")
XCTAssertEqual(json.toFoundation() as? String, "string")
}
func testNull() {
let json = JSON.null
XCTAssertEqual(json.toFoundation() as? NSNull, NSNull())
}
func testBoolTrue() {
let json = JSON.bool(true)
XCTAssertEqual(json.toFoundation() as? Bool, true)
}
func testBoolFalse() {
let json = JSON.bool(false)
XCTAssertEqual(json.toFoundation() as? Bool, false)
}
func testInt() {
let json = JSON.number(.int(10))
XCTAssertEqual(json.toFoundation() as? Int, 10)
}
func testUInt() {
let json = JSON.number(.uint(10))
XCTAssertEqual(json.toFoundation() as? UInt, 10)
}
func testDouble() {
let json = JSON.number(.double(10))
XCTAssertEqual(json.toFoundation() as? Double, 10)
}
func testEmptyArray() {
let json = JSON.array([])
XCTAssertEqual((json.toFoundation() as? [Any])?.count, 0)
}
func testArrayWithString() {
let json = JSON.array([.string("string")])
XCTAssertEqual((json.toFoundation() as? [Any])?.count, 1)
XCTAssertEqual((json.toFoundation() as? [Any])?.first as? String, "string")
}
func testEmptyObject() {
let json = JSON.object([:])
XCTAssertEqual((json.toFoundation() as? [String: Any])?.count, 0)
}
func testObjectWithString() {
let json = JSON.object(["key": .string("string")])
XCTAssertEqual((json.toFoundation() as? [String: Any])?.count, 1)
XCTAssertEqual((json.toFoundation() as? [String: Any])?["key"] as? String, "string")
}
}
| mit | dc33fcf78d2378891f4ee1ae956f5cdb | 33.359551 | 92 | 0.650425 | 4.235457 | false | true | false | false |
radex/RxExperiments | viewmodels/sketch-reactlike-viewmodel.swift | 1 | 2163 | class VM: ViewModel {
struct State {
// MARK: - Inputs
let username = ""
let password = ""
let repeatPassword = ""
// MARK: - Internal state
private let usernameValidation = .empty
private let signingIn = false
}
// MARK: - Outputs
typealias OutputState = (
usernameValid: ValidationResult,
passwordValid: ValidationResult,
repeatPasswordValid: ValidationResult,
signupEnabled: Bool
)
// MARK: - Implementation
var state = State() {
didSet {
username_rx.value = state.username
updateOutput()
}
}
private let username_rx = Variable("")
private func setup_rx() {
username_rx.asObservable()
.distinctUntilChanged()
.flatMapLatest { username in
return validateUsername(username)
.catchErrorJustReturn(.failed)
}.subscribe(onNext: {
self.state.usernameValidation = $0
})
.addDisposableTo(disposeBag)
}
func outputState() -> Output {
let usernameValid = state.usernameValidation
let passwordValid = passwordValidation(state.password)
let repeatPasswordValid = passwordValidation(state.password, state.repeatPassword)
let signupEnabled = usernameValid && passwordValid && repeatPasswordValid && !state.signingIn
return (usernameValid, passwordValid, repeatPasswordValid, signupEnabled)
}
}
class VC: ReactyViewController {
let viewModel = VM(render: self.render)
func setUp() {
usernameInput.onChange = { viewModel.state.username = $0 }
passwordInput.onChange = { viewModel.state.password = $0 }
repeatPasswordInput.onChange = { viewModel.state.repeatPassword = $0 }
}
func render(state: VM.OutputState) {
usernameValidLabel.state = state.usernameValid
passwordValidLabel.state = state.passwordValid
repeatPasswordValid.state = state.repeatPasswordValid
signupButton.enabled = state.signupEnabled
}
} | mit | 821b8bea068b3e6b11053dbdc7997e0f | 30.362319 | 101 | 0.613037 | 5.288509 | false | false | false | false |
kean/Nuke | Sources/NukeUI/Image.swift | 1 | 3314 | // The MIT License (MIT)
//
// Copyright (c) 2015-2021 Alexander Grebenyuk (github.com/kean).
import SwiftUI
#if os(macOS)
import AppKit
#else
import UIKit
#endif
#if os(macOS)
/// Displays images. Supports animated images and video playback.
@MainActor
public struct Image: NSViewRepresentable {
let imageContainer: ImageContainer
let onCreated: ((ImageView) -> Void)?
var isAnimatedImageRenderingEnabled: Bool?
var isVideoRenderingEnabled: Bool?
var isVideoLooping: Bool?
var resizingMode: ImageResizingMode?
public init(_ image: NSImage) {
self.init(ImageContainer(image: image))
}
public init(_ imageContainer: ImageContainer, onCreated: ((ImageView) -> Void)? = nil) {
self.imageContainer = imageContainer
self.onCreated = onCreated
}
public func makeNSView(context: Context) -> ImageView {
let view = ImageView()
onCreated?(view)
return view
}
public func updateNSView(_ imageView: ImageView, context: Context) {
updateImageView(imageView)
}
}
#elseif os(iOS) || os(tvOS)
/// Displays images. Supports animated images and video playback.
@MainActor
public struct Image: UIViewRepresentable {
let imageContainer: ImageContainer
let onCreated: ((ImageView) -> Void)?
var isAnimatedImageRenderingEnabled: Bool?
var isVideoRenderingEnabled: Bool?
var isVideoLooping: Bool?
var resizingMode: ImageResizingMode?
public init(_ image: UIImage) {
self.init(ImageContainer(image: image))
}
public init(_ imageContainer: ImageContainer, onCreated: ((ImageView) -> Void)? = nil) {
self.imageContainer = imageContainer
self.onCreated = onCreated
}
public func makeUIView(context: Context) -> ImageView {
let imageView = ImageView()
onCreated?(imageView)
return imageView
}
public func updateUIView(_ imageView: ImageView, context: Context) {
updateImageView(imageView)
}
}
#endif
#if os(macOS) || os(iOS) || os(tvOS)
extension Image {
func updateImageView(_ imageView: ImageView) {
if imageView.imageContainer?.image !== imageContainer.image {
imageView.imageContainer = imageContainer
}
if let value = resizingMode { imageView.resizingMode = value }
if let value = isVideoRenderingEnabled { imageView.isVideoRenderingEnabled = value }
if let value = isAnimatedImageRenderingEnabled { imageView.isAnimatedImageRenderingEnabled = value }
if let value = isVideoLooping { imageView.isVideoLooping = value }
}
/// Sets the resizing mode for the image.
public func resizingMode(_ mode: ImageResizingMode) -> Self {
var copy = self
copy.resizingMode = mode
return copy
}
public func videoRenderingEnabled(_ isEnabled: Bool) -> Self {
var copy = self
copy.isVideoRenderingEnabled = isEnabled
return copy
}
public func videoLoopingEnabled(_ isEnabled: Bool) -> Self {
var copy = self
copy.isVideoLooping = isEnabled
return copy
}
public func animatedImageRenderingEnabled(_ isEnabled: Bool) -> Self {
var copy = self
copy.isAnimatedImageRenderingEnabled = isEnabled
return copy
}
}
#endif
| mit | 932128d74a39f61fb328934845153bd1 | 28.589286 | 108 | 0.673205 | 4.720798 | false | false | false | false |
mercadopago/px-ios | MercadoPagoSDK/MercadoPagoSDK/PXSpruce/Animations/PXDefaultAnimations.swift | 1 | 10055 | import UIKit
/// Direction that a slide animation should use.
///
/// - up: start the view below its current position, and then slide upwards to where it currently is
/// - down: start the view above its current position, and then slide downwards to where it currently is
/// - left: start the view to the right of its current position, and then slide left to where it currently is
/// - right: start the view to the left of its current position, and then slide right to where it currently is
enum SlideDirection {
/// start the view below its current position, and then slide upwards to where it currently is
case up
/// start the view above its current position, and then slide downwards to where it currently is
case down
/// start the view to the right of its current position, and then slide left to where it currently is
case left
/// start the view to the left of its current position, and then slide right to where it currently is
case right
}
/// How much the angle of an animation should change. This value changes based off of which type of `StockAnimation` is used.
///
/// - slightly: slightly animate the object
/// - moderately: the object should move a moderate amount
/// - severely: the object should move very noticeably
/// - toAngle: provide your own angle value that you feel the object should rotate
enum Angle {
/// slightly animate the object
case slightly
/// the object should move a moderate amount
case moderately
/// the object should move very noticeably
case severely
/// provide your own value that you feel the object should move. The value you should provide should be a `Double`
case toAngle(CGFloat)
}
/// How much the scale of an animation should change. This value changes based off of which type of `StockAnimation` is used.
///
/// - slightly: slightly animate the object
/// - moderately: the object should scale a moderate amount
/// - severely: the object should scale very noticeably
/// - toScale: provide your own scale value that you feel the object should grow/shrink
enum Scale {
/// slightly animate the object
case slightly
/// the object should scale a moderate amount
case moderately
/// the object should scale very noticeably
case severely
/// provide your own scale value that you feel the object should grow/shrink
case toScale(CGFloat)
}
/// How much the distance of a view animation should change. This value changes based off of which type of `StockAnimation` is used.
///
/// - slightly: slightly move the object
/// - moderately: the object should move a moderate amount
/// - severely: the object should move very noticeably
/// - byPoints: provide your own distance value that you feel the object should slide over
enum Distance {
/// slightly move the object
case slightly
/// the object should move a moderate amount
case moderately
/// the object should move very noticeably
case severely
/// provide your own distance value that you feel the object should slide over
case byPoints(CGFloat)
}
/// A few stock animations that you can use with Spruce. We want to make it really easy for you to include animations so we tried to include the basics. Use these stock animations to `slide`, `fade`, `spin`, `expand`, or `contract` your views.
enum StockAnimation {
/// Have your view slide to where it currently is. Provide a `SlideDirection` and `Size` to determine what the animation should look like.
case slide(SlideDirection, Distance)
/// Fade the view in
case fadeIn
/// Spin the view in the direction of the size. Provide a `Size` to define how much the view should spin
case spin(Angle)
/// Have the view grow in size. Provide a `Size` to define by which scale the view should grow
case expand(Scale)
/// Have the view shrink in size. Provide a `Size` to define by which scale the view should shrink
case contract(Scale)
/// Provide custom prepare and change functions for the view to animate
case custom(prepareFunction: PrepareHandler, animateFunction: ChangeFunction)
/// Given the `StockAnimation`, how should Spruce prepare your view for animation. Since we want all of the views to end the animation where they are supposed to be positioned, we have to reverse their animation effect.
var prepareFunction: PrepareHandler {
get {
switch self {
case .slide:
let offset = slideOffset
return { view in
let currentTransform = view.transform
let offsetTransform = CGAffineTransform(translationX: offset.x, y: offset.y)
view.transform = currentTransform.concatenating(offsetTransform)
}
case .fadeIn:
return { view in
view.alpha = 0.0
}
case .spin:
let angle = spinAngle
return { view in
let currentTransform = view.transform
let spinTransform = CGAffineTransform(rotationAngle: angle)
view.transform = currentTransform.concatenating(spinTransform)
}
case .expand, .contract:
let scale = self.scale
return { view in
let currentTransform = view.transform
let scaleTransform = CGAffineTransform(scaleX: scale, y: scale)
view.transform = currentTransform.concatenating(scaleTransform)
}
case .custom(let prepare, _):
return prepare
}
}
}
/// Reset any of the transforms on the view so that the view will end up in its original position. If a `custom` animation is used, then that animation `ChangeFunction` is returned.
var animationFunction: ChangeFunction {
get {
switch self {
case .slide:
return { view in
view.transform = CGAffineTransform(translationX: 0.0, y: 0.0)
}
case .fadeIn:
return { view in
view.alpha = 1.0
}
case .spin:
return { view in
view.transform = CGAffineTransform(rotationAngle: 0.0)
}
case .expand, .contract:
return { view in
view.transform = CGAffineTransform(scaleX: 1.0, y: 1.0)
}
case .custom(_, let animation):
return animation
}
}
}
/// Given the animation is a `slide`, return the slide offset
var slideOffset: CGPoint {
get {
switch self {
case .slide(let direction, let size):
switch (direction, size) {
case (.up, .slightly):
return CGPoint(x: 0.0, y: 10.0)
case (.up, .moderately):
return CGPoint(x: 0.0, y: 30.0)
case (.up, .severely):
return CGPoint(x: 0.0, y: 50.0)
case (.up, .byPoints(let value)):
return CGPoint(x: 0.0, y: -value)
case (.down, .slightly):
return CGPoint(x: 0.0, y: -10.0)
case (.down, .moderately):
return CGPoint(x: 0.0, y: -30.0)
case (.down, .severely):
return CGPoint(x: 0.0, y: -50.0)
case (.down, .byPoints(let value)):
return CGPoint(x: 0.0, y: -value)
case (.left, .slightly):
return CGPoint(x: 10.0, y: 0.0)
case (.left, .moderately):
return CGPoint(x: 30.0, y: 0.0)
case (.left, .severely):
return CGPoint(x: 50.0, y: 0.0)
case (.left, .byPoints(let value)):
return CGPoint(x: -value, y: 0.0)
case (.right, .slightly):
return CGPoint(x: -10.0, y: 0.0)
case (.right, .moderately):
return CGPoint(x: -30.0, y: 0.0)
case (.right, .severely):
return CGPoint(x: -50.0, y: 0.0)
case (.right, .byPoints(let value)):
return CGPoint(x: -value, y: 0.0)
}
default:
return CGPoint.zero
}
}
}
/// Given the animation is a `spin`, then this will return the angle that the view should spin.
var spinAngle: CGFloat {
get {
switch self {
case .spin(let size):
switch size {
case .slightly:
return CGFloat(Double.pi / 4)
case .moderately:
return CGFloat(Double.pi / 2)
case .severely:
return CGFloat(Double.pi)
case .toAngle(let value):
return value
}
default:
return 0.0
}
}
}
/// Given the animation is either `expand` or `contract`, this will return the scale from which the view should grow/shrink
var scale: CGFloat {
switch self {
case .contract(let size):
switch size {
case .slightly:
return 1.1
case .moderately:
return 1.3
case .severely:
return 1.5
case .toScale(let value):
return value
}
case .expand(let size):
switch size {
case .slightly:
return 0.9
case .moderately:
return 0.7
case .severely:
return 0.5
case .toScale(let value):
return value
}
default:
return 0.0
}
}
}
| mit | 2f44ef8d1989b92834b5fb694374a777 | 37.822394 | 243 | 0.569269 | 4.799523 | false | false | false | false |
YOLayout/YOLayout | YOLayoutExample/YOLayoutExample/SwiftView/SwiftViewController.swift | 1 | 1712 | //
// SwiftViewController.swift
// YOLayoutExample
//
// Created by John Boiles on 1/9/15.
// Copyright (c) 2015 YOLayout. All rights reserved.
//
import UIKit
class SwiftViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
self.edgesForExtendedLayout = .None;
self.title = "Swift Circle View"
}
override func loadView() {
super.loadView()
let swiftView = CircleLayoutView()
let informationLabel = UILabel()
informationLabel.textAlignment = .Center
informationLabel.lineBreakMode = .ByWordWrapping
informationLabel.numberOfLines = 0
informationLabel.text = "With YOLayout, you can build any layout you can imagine mathematically. The following view, written in Swift, uses trigonometry to layout subviews in a circle around the center. Try rotating the device."
// Use a simple container view to hold the informationLabel and the circleView after it sizes to fit
let containerView = YOView()
containerView.backgroundColor = UIColor.whiteColor()
containerView.layout = YOLayout(layoutBlock: { (layout: YOLayoutProtocol!, size) -> CGSize in
var y : CGFloat = 10;
y += layout.setFrame(CGRectMake(10, y, size.width - 20, 100), view: informationLabel, options:.SizeToFitVertical).size.height
y += 5
layout.setFrame(CGRectMake(5, y, size.width - 10 , size.height - y - 5), view:swiftView, options:[.SizeToFit, .AlignCenter])
return size
})
containerView.addSubview(swiftView)
containerView.addSubview(informationLabel)
self.view = containerView;
}
}
| mit | d7abf802b423b2730d632f79268bf6f8 | 33.938776 | 236 | 0.671145 | 4.768802 | false | false | false | false |
gribozavr/swift | test/Driver/Dependencies/fail-new-fine.swift | 1 | 3512 | /// bad ==> main | bad --> other
// RUN: %empty-directory(%t)
// RUN: cp -r %S/Inputs/fail-simple-fine/* %t
// RUN: touch -t 201401240005 %t/*
// RUN: cd %t && not %swiftc_driver -enable-fine-grained-dependencies -c -driver-use-frontend-path "%{python};%S/Inputs/update-dependencies-bad.py" -output-file-map %t/output.json -incremental -driver-always-rebuild-dependents ./main.swift ./bad.swift ./other.swift -module-name main -j1 -v 2>&1 | %FileCheck %s
// CHECK-NOT: warning
// CHECK: Handled main.swift
// CHECK: Handled bad.swift
// CHECK-NOT: Handled other.swift
// RUN: cd %t && not %swiftc_driver -enable-fine-grained-dependencies -c -driver-use-frontend-path "%{python};%S/Inputs/update-dependencies-bad.py" -output-file-map %t/output.json -incremental -driver-always-rebuild-dependents ./bad.swift ./main.swift ./other.swift -module-name main -j1 -v 2>&1 | %FileCheck -check-prefix=CHECK-BAD-ONLY %s
// CHECK-BAD-ONLY-NOT: warning
// CHECK-BAD-ONLY-NOT: Handled
// CHECK-BAD-ONLY: Handled bad.swift
// CHECK-BAD-ONLY-NOT: Handled
// RUN: cd %t && %swiftc_driver -enable-fine-grained-dependencies -c -driver-use-frontend-path "%{python};%S/Inputs/update-dependencies.py" -output-file-map %t/output.json -incremental -driver-always-rebuild-dependents ./main.swift ./bad.swift ./other.swift -module-name main -j1 -v 2>&1 | %FileCheck -check-prefix=CHECK-OKAY %s
// CHECK-OKAY: Handled main.swift
// CHECK-OKAY: Handled bad.swift
// CHECK-OKAY: Handled other.swift
// CHECK-OKAY-NOT: Handled
// RUN: touch -t 201401240006 %t/bad.swift
// RUN: rm %t/bad.swiftdeps
// RUN: cd %t && not %swiftc_driver -enable-fine-grained-dependencies -c -driver-use-frontend-path "%{python};%S/Inputs/update-dependencies-bad.py" -output-file-map %t/output.json -incremental -driver-always-rebuild-dependents ./main.swift ./bad.swift ./other.swift -module-name main -j1 -v 2>&1 | %FileCheck %s
// RUN: touch -t 201401240005 %t/*
// RUN: cd %t && %swiftc_driver -enable-fine-grained-dependencies -c -driver-use-frontend-path "%{python};%S/Inputs/update-dependencies.py" -output-file-map %t/output.json -incremental -driver-always-rebuild-dependents ./main.swift ./bad.swift ./other.swift -module-name main -j1 -v 2>&1 | %FileCheck -check-prefix=CHECK-OKAY-2 %s
// CHECK-OKAY-2-DAG: Handled bad.swift
// CHECK-OKAY-2-DAG: Handled other.swift
// CHECK-OKAY-2-DAG: Handled main.swift
// RUN: touch -t 201401240006 %t/main.swift
// RUN: rm %t/main.swiftdeps
// RUN: cd %t && not %swiftc_driver -enable-fine-grained-dependencies -c -driver-use-frontend-path "%{python};%S/Inputs/update-dependencies-bad.py" -output-file-map %t/output.json -incremental -driver-always-rebuild-dependents ./main.swift ./bad.swift ./other.swift -module-name main -j1 -v 2>&1 | %FileCheck %s
// RUN: touch -t 201401240005 %t/*
// RUN: cd %t && %swiftc_driver -enable-fine-grained-dependencies -c -driver-use-frontend-path "%{python};%S/Inputs/update-dependencies.py" -output-file-map %t/output.json -incremental -driver-always-rebuild-dependents ./main.swift ./bad.swift ./other.swift -module-name main -j1 -v 2>&1 | %FileCheck -check-prefix=CHECK-OKAY %s
// RUN: touch -t 201401240006 %t/other.swift
// RUN: rm %t/other.swiftdeps
// RUN: cd %t && not %swiftc_driver -enable-fine-grained-dependencies -c -driver-use-frontend-path "%{python};%S/Inputs/update-dependencies-bad.py" -output-file-map %t/output.json -incremental -driver-always-rebuild-dependents ./main.swift ./bad.swift ./other.swift -module-name main -j1 -v 2>&1 | %FileCheck %s
| apache-2.0 | 049c37ceb051c006a5bc74bd43bf66a0 | 77.044444 | 340 | 0.718109 | 3.113475 | false | false | true | false |
dekatotoro/FluxWithRxSwiftSample | FluxWithRxSwiftSample/Views/SearchUser/SearchUserInputView.swift | 1 | 1814 | //
// SearchUserInputView.swift
// FluxWithRxSwiftSample
//
// Created by Yuji Hato on 2016/10/13.
// Copyright © 2016年 dekatotoro. All rights reserved.
//
import UIKit
import RxSwift
class SearchUserInputView: UIView, Nibable {
@IBOutlet weak var searchBar: UISearchBar!
@IBOutlet weak var numberLable: UILabel!
private let store = SearchUserStore.shared
override func awakeFromNib() {
super.awakeFromNib()
configureUI()
observeStore()
observeUI()
}
private func configureUI() {
searchBar.barTintColor = .lightGray
searchBar.tintColor = .gray
searchBar.layer.borderColor = UIColor.lightGray.cgColor
searchBar.layer.borderWidth = 1
numberLable.textColor = .gray
}
private func observeStore() {
store.rx.searchUser.asObservable()
.map { $0.totalCountText }
.subscribe(onNext: { [unowned self] totalCountText in
self.numberLable.text = totalCountText
})
.addDisposableTo(rx_disposeBag)
// Dismiss keyboard on scroll
store.rx.scrollViewDidEndDragging
.subscribe(onNext: { _ in
if self.searchBar.isFirstResponder {
_ = self.searchBar.resignFirstResponder()
}
})
.addDisposableTo(rx_disposeBag)
}
private func observeUI() {
searchBar.rx.text.asDriver()
.skip(1) // skip init time
.filterNil()
.throttle(0.3)
.distinctUntilChanged()
.drive(onNext: { query in
SearchUserAction.searchUser(query: query, page: 0)
})
.addDisposableTo(rx_disposeBag)
}
}
| mit | 0c4766f6bc702f54ac8b6b22f3a68bde | 26.439394 | 66 | 0.575373 | 5.002762 | false | false | false | false |
OlexaBoyko/KGCellDescription | KGTableViewSource.swift | 1 | 4960 | //
// KGTableViewSource.swift
//
//
// Created by Olexa Boyko on 5/11/17.
// Copyright © 2017 Olexa Boyko. All rights reserved.
//
import Foundation
class KGTableViewSource: NSObject {
fileprivate var sections: Int {
get {
return cellDescriptionArray.count
}
}
public weak var tableView: UITableView? {
didSet {
self.tableView?.dataSource = self
self.registerCells()
}
}
fileprivate var cellDescriptionArray: [[KGCellDescription]] = []
public func clearTable() {
self.cellDescriptionArray = []
}
public func addSection(cellDescriptionArray: [KGCellDescription]) {
for value in cellDescriptionArray {
value.cellReloader = self
}
self.cellDescriptionArray.append(cellDescriptionArray)
}
public func indexPathFor(_ cellDescription: KGCellDescription) -> IndexPath? {
for i in 0..<self.cellDescriptionArray.count {
for j in 0..<self.cellDescriptionArray[i].count {
if self.cellDescriptionArray[i][j] === cellDescription {
return IndexPath.init(row: j, section: i)
}
}
}
return nil
}
public func cellDescription(at: IndexPath) -> KGCellDescription {
return self.cellDescriptionArray[at.section][at.row]
}
public func modifyKGCellDescription(modifier: @escaping (KGCellDescription) -> Void) {
for section in self.cellDescriptionArray {
_ = section.map({modifier($0)})
}
}
public func heightForRow(at: IndexPath) -> CGFloat {
return cellDescription(at: at).height
}
private func registerCells() {
guard let tableView = self.tableView else {
fatalError("Assign tableView to source.tableView")
}
var set = Set<String>()
for section in self.cellDescriptionArray {
for row in section {
if (set.insert(row.reuseIdentifier)).inserted {
type(of: row).registerCell(for: tableView)
}
}
}
}
public func didSelectRow(
cellDescription: KGCellDescription,
selectedRow: ((KGCellDescription) -> Void)? = nil,
otherRows: ((KGCellDescription) -> Void)? = nil) {
for section in self.cellDescriptionArray {
for row in section {
if row === cellDescription {
selectedRow?(row)
} else {
otherRows?(row)
}
}
}
self.tableView?.reloadData()
}
public func didSelectRowAt(
indexPath: IndexPath,
selectedRow: ((KGCellDescription) -> Void)? = nil,
otherRows: ((KGCellDescription) -> Void)? = nil) {
for sectionIndex in 0..<self.cellDescriptionArray.count {
for rowIndex in 0..<sectionIndex {
guard sectionIndex != indexPath.section,
rowIndex != indexPath.row else {
selectedRow?(self.cellDescriptionArray[sectionIndex][rowIndex])
continue
}
otherRows?(self.cellDescriptionArray[sectionIndex][rowIndex])
}
}
self.tableView?.reloadData()
}
public subscript(index: Int) -> [KGCellDescription] {
get {
return self.cellDescriptionArray[index]
}
set(value) {
self.cellDescriptionArray[index] = value
}
}
public subscript(indexPath: IndexPath) -> KGCellDescription {
get {
return self.cellDescription(at: indexPath)
}
set(value) {
self.cellDescriptionArray[indexPath.section][indexPath.row] = value
}
}
}
extension KGTableViewSource: KGCellReloader {
func reloadCell(cellDescription: KGCellDescription, animation: UITableViewRowAnimation = .right) {
guard let indexPath = indexPathFor(cellDescription) else {
return
}
self.tableView?.reloadRows(at: [indexPath], with: animation)
}
}
extension KGTableViewSource: UITableViewDataSource {
public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.cellDescriptionArray[section].count
}
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
return self.cellDescriptionArray[indexPath.section][indexPath.row].instantiateCell(for: tableView)
}
public func numberOfSections(in tableView: UITableView) -> Int {
return self.cellDescriptionArray.count
}
}
| mit | e2104b6f010ac36e7eb5ce218918ade4 | 28.873494 | 107 | 0.568058 | 5.107106 | false | false | false | false |
suzuki-0000/HoneycombView | HoneycombView/HoneycombZoomingScrollView.swift | 1 | 6315 | //
// HoneycombZoomingScrollView.swift
// HoneycombViewExample
//
// Created by suzuki_keihsi on 2015/10/01.
// Copyright © 2015 suzuki_keishi. All rights reserved.
//
import UIKit
public class HoneycombZoomingScrollView:UIScrollView, UIScrollViewDelegate, HoneycombDetectingViewDelegate, HoneycombDetectingImageViewDelegate{
weak var photoBrowser:HoneycombPhotoBrowser!
var photo:HoneycombPhoto!{
didSet{
photoImageView.image = nil
displayImage()
}
}
var tapView:HoneycombDetectingView!
var photoImageView:HoneycombDetectingImageView!
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup()
}
override init(frame: CGRect) {
super.init(frame: frame)
setup()
}
convenience init(frame: CGRect, browser: HoneycombPhotoBrowser) {
self.init(frame: frame)
photoBrowser = browser
setup()
}
func setup() {
// tap
tapView = HoneycombDetectingView(frame: bounds)
tapView.delegate = self
tapView.backgroundColor = UIColor.clearColor()
tapView.autoresizingMask = [.FlexibleHeight, .FlexibleWidth]
addSubview(tapView)
// image
photoImageView = HoneycombDetectingImageView(frame: frame)
photoImageView.delegate = self
photoImageView.backgroundColor = UIColor.clearColor()
addSubview(photoImageView)
// self
backgroundColor = UIColor.clearColor()
delegate = self
showsHorizontalScrollIndicator = false
showsVerticalScrollIndicator = false
decelerationRate = UIScrollViewDecelerationRateFast
autoresizingMask = [.FlexibleHeight, .FlexibleWidth]
}
// MARK: - override
public override func layoutSubviews() {
super.layoutSubviews()
tapView.frame = bounds
let boundsSize = bounds.size
var frameToCenter = photoImageView.frame
// horizon
if frameToCenter.size.width < boundsSize.width {
frameToCenter.origin.x = floor((boundsSize.width - frameToCenter.size.width) / 2)
} else {
frameToCenter.origin.x = 0
}
// vertical
if frameToCenter.size.height < boundsSize.height {
frameToCenter.origin.y = floor((boundsSize.height - frameToCenter.size.height) / 2)
} else {
frameToCenter.origin.y = 0
}
// Center
if !CGRectEqualToRect(photoImageView.frame, frameToCenter){
photoImageView.frame = frameToCenter
}
}
public func setMaxMinZoomScalesForCurrentBounds(){
maximumZoomScale = 1
minimumZoomScale = 1
zoomScale = 1
if photoImageView == nil {
return
}
let boundsSize = bounds.size
let imageSize = photoImageView.frame.size
let xScale = boundsSize.width / imageSize.width
let yScale = boundsSize.height / imageSize.height
var maxScale:CGFloat = 4.0
let minScale:CGFloat = min(xScale, yScale)
maximumZoomScale = maxScale
minimumZoomScale = minScale
zoomScale = minScale
// on high resolution screens we have double the pixel density, so we will be seeing every pixel if we limit the
// maximum zoom scale to 0.5
maxScale = maxScale / UIScreen.mainScreen().scale
if maxScale < minScale {
maxScale = minScale * 2
}
// reset position
photoImageView.frame = CGRectMake(0, 0, photoImageView.frame.size.width, photoImageView.frame.size.height)
setNeedsLayout()
}
public func prepareForReuse(){
photo = nil
}
// MARK: - image
public func displayImage(){
// reset scale
maximumZoomScale = 1
minimumZoomScale = 1
zoomScale = 1
contentSize = CGSizeZero
if photo != nil {
let image = photo.underlyingImage
photoImageView.image = image
var photoImageViewFrame = CGRectZero
photoImageViewFrame.origin = CGPointZero
photoImageViewFrame.size = image.size
photoImageView.frame = CGRectMake(0, 0,
min(photoImageViewFrame.size.width, photoImageViewFrame.size.height),
min(photoImageViewFrame.size.width, photoImageViewFrame.size.height))
contentSize = photoImageViewFrame.size
setMaxMinZoomScalesForCurrentBounds()
}
setNeedsLayout()
}
// MARK: - handle tap
public func handleDoubleTap(touchPoint: CGPoint){
NSObject.cancelPreviousPerformRequestsWithTarget(photoBrowser)
if zoomScale == maximumZoomScale {
// zoom out
setZoomScale(minimumZoomScale, animated: true)
} else {
// zoom in
zoomToRect(CGRectMake(touchPoint.x, touchPoint.y, 1, 1), animated:true)
}
// delay control
photoBrowser.hideControlsAfterDelay()
}
// MARK: - UIScrollViewDelegate
public func viewForZoomingInScrollView(scrollView: UIScrollView) -> UIView? {
return photoImageView
}
public func scrollViewWillBeginZooming(scrollView: UIScrollView, withView view: UIView?) {
photoBrowser.cancelControlHiding()
}
public func scrollViewDidZoom(scrollView: UIScrollView) {
setNeedsLayout()
layoutIfNeeded()
}
// MARK: - HoneycombDetectingViewDelegate
func handleSingleTap(view: UIView, touch: UITouch) {
photoBrowser.toggleControls()
}
func handleDoubleTap(view: UIView, touch: UITouch) {
handleDoubleTap(touch.locationInView(view))
}
// MARK: - HoneycombDetectingImageViewDelegate
func handleImageViewSingleTap(view: UIImageView, touch: UITouch) {
photoBrowser.toggleControls()
}
func handleImageViewDoubleTap(view: UIImageView, touch: UITouch) {
handleDoubleTap(touch.locationInView(view))
}
} | mit | fca1f4cd0bfd878cc70d300081eaff67 | 29.360577 | 144 | 0.614032 | 5.862581 | false | false | false | false |
jay18001/brickkit-ios | Example/Source/Examples/Simple/SimpleRepeatBrickViewController.swift | 1 | 2282 | //
// SimpleRepeatBrickViewController.swift
// BrickApp
//
// Created by Ruben Cagnie on 5/25/16.
// Copyright © 2016 Wayfair. All rights reserved.
//
import UIKit
import BrickKit
class SimpleRepeatBrickViewController: BrickViewController, LabelBrickCellDataSource, BrickRepeatCountDataSource {
override class var brickTitle: String {
return "Simple Repeat"
}
override class var subTitle: String {
return "Example how to use the repeatCountDataSource"
}
let numberOfLabels = 100
override func viewDidLoad() {
super.viewDidLoad()
self.brickCollectionView.registerBrickClass(LabelBrick.self)
self.view.backgroundColor = .brickBackground
let section = BrickSection(bricks: [
LabelBrick(BrickIdentifiers.repeatLabel, width: .ratio(ratio: 1/2), height: .auto(estimate: .fixed(size: 50)), backgroundColor: .brickGray1, dataSource: self),
], inset: 10, edgeInsets: UIEdgeInsets(top: 5, left: 5, bottom: 5, right: 5))
section.repeatCountDataSource = self
self.setSection(section)
updateNavigationItem()
}
func updateNavigationItem() {
let selector: Selector = #selector(SimpleRepeatBrickViewController.toggleAlignBehavior)
let title = self.brickCollectionView.section.alignRowHeights ? "Don't Align" : "Align"
self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: title, style: .plain, target: self, action: selector)
}
func toggleAlignBehavior() {
self.brickCollectionView.section.alignRowHeights = !self.brickCollectionView.section.alignRowHeights
brickCollectionView.reloadData()
updateNavigationItem()
}
func repeatCount(for identifier: String, with collectionIndex: Int, collectionIdentifier: String) -> Int {
if identifier == BrickIdentifiers.repeatLabel {
return numberOfLabels
} else {
return 1
}
}
func configureLabelBrickCell(_ cell: LabelBrickCell) {
var text = ""
for _ in 0...cell.index {
if !text.isEmpty {
text += "\n"
}
text += "BRICK \(cell.index)"
}
cell.label.text = text
cell.configure()
}
}
| apache-2.0 | 6a452156b40deee9382a734335ecd7fa | 30.680556 | 171 | 0.658483 | 4.873932 | false | false | false | false |
watson-developer-cloud/ios-sdk | Sources/DiscoveryV2/Models/CreateEnrichment.swift | 1 | 2724 | /**
* (C) Copyright IBM Corp. 2022.
*
* 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
/**
Information about a specific enrichment.
*/
public struct CreateEnrichment: Codable, Equatable {
/**
The type of this enrichment.
*/
public enum TypeEnum: String {
case classifier = "classifier"
case dictionary = "dictionary"
case regularExpression = "regular_expression"
case uimaAnnotator = "uima_annotator"
case ruleBased = "rule_based"
case watsonKnowledgeStudioModel = "watson_knowledge_studio_model"
}
/**
The human readable name for this enrichment.
*/
public var name: String?
/**
The description of this enrichment.
*/
public var description: String?
/**
The type of this enrichment.
*/
public var type: String?
/**
An object that contains options for the current enrichment. Starting with version `2020-08-30`, the enrichment
options are not included in responses from the List Enrichments method.
*/
public var options: EnrichmentOptions?
// Map each property name to the key that shall be used for encoding/decoding.
private enum CodingKeys: String, CodingKey {
case name = "name"
case description = "description"
case type = "type"
case options = "options"
}
/**
Initialize a `CreateEnrichment` with member variables.
- parameter name: The human readable name for this enrichment.
- parameter description: The description of this enrichment.
- parameter type: The type of this enrichment.
- parameter options: An object that contains options for the current enrichment. Starting with version
`2020-08-30`, the enrichment options are not included in responses from the List Enrichments method.
- returns: An initialized `CreateEnrichment`.
*/
public init(
name: String? = nil,
description: String? = nil,
type: String? = nil,
options: EnrichmentOptions? = nil
)
{
self.name = name
self.description = description
self.type = type
self.options = options
}
}
| apache-2.0 | b831f7f4832aa534c31d1b57944cfaaf | 29.606742 | 115 | 0.664464 | 4.45098 | false | false | false | false |
mikelbrownus/SwiftMythTVBackend | Sources/mythserver/model/Recorded+MySQLResult.swift | 1 | 1466 | import MySQL
import LoggerAPI
import Foundation
// MARK: - MySQLResultProtocol (Activity)
public extension MySQLResultProtocol {
public func toRecordings() -> [Recorded] {
var recordings = [Recorded]()
while case let row? = self.nextResult() {
let recordid = row["recordid"] as? Int ?? 0
let title = row["title"] as? String ?? ""
let description = row["description"] as? String ?? ""
let filesize = row["filesize"] as? Int ?? 0
let chanid = row["chanid"] as? Int ?? 0
let channelName = row["name"] as? String ?? ""
let channelNumber = row["channum"] as? String ?? ""
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
let programStartString = row["progstart"] as? String ?? ""
let pStart = dateFormatter.date(from: programStartString) ?? Date()
let programendEndString = row["progend"] as? String ?? ""
let pEnd = dateFormatter.date(from: programendEndString) ?? Date()
let recording = Recorded(recordid: recordid, title: title, description: description, filesize: filesize, chanid: chanid, programstart: pStart,
programend: pEnd, channelName: channelName, channelNumber: channelNumber)
recordings.append(recording)
}
return recordings
}
} | mit | f4d84b2cc8f2af8695fdf177521b8105 | 38.648649 | 154 | 0.584584 | 4.624606 | false | false | false | false |
dreamsxin/swift | test/Interpreter/defer.swift | 8 | 689 | // RUN: %target-run-simple-swift | FileCheck %s
// REQUIRES: executable_test
do {
defer { print("deferred 1") }
defer { print("deferred 2") }
print("start!")
// CHECK-NOT: deferred
// CHECK-LABEL: start!
// CHECK-NEXT: deferred 2
// CHECK-NEXT: deferred 1
}
// ensure #function ignores defer blocks
do {
print("top-level #function")
let name = #function
defer { print(name == #function ? "good" : "bad") }
// CHECK-LABEL: top-level #function
// CHECK-NEXT: good
}
func foo() {
print("foo()")
let name = #function
defer { print(name == #function ? "good" : "bad") }
// CHECK-LABEL: foo()
// CHECK-NEXT: good
}
foo()
| apache-2.0 | cc2761a1b506bd5bef9bddc6abf222ba | 19.878788 | 55 | 0.577649 | 3.394089 | false | false | false | false |
itouch2/LeetCode | LeetCode/PalindromeLinkedList.swift | 1 | 1517 | //
// PalindromeLinkedList.swift
// LeetCode
//
// Created by You Tu on 2017/9/12.
// Copyright © 2017年 You Tu. All rights reserved.
//
import Cocoa
/*
Given a singly linked list, determine if it is a palindrome.
Follow up:
Could you do it in O(n) time and O(1) space?
*/
class PalindromeLinkedList: NSObject {
func isPalindrome(_ head: ListNode?) -> Bool {
if head == nil {
return true
}
var slow = head, fast = head?.next
while fast?.next != nil {
slow = slow?.next
fast = fast?.next
fast = fast?.next
}
var tail = reverseLinkedList(slow?.next)
if tail == nil {
return true
}
var begin = head, terminate: ListNode? = nil
if fast != nil {
// even
terminate = slow?.next
} else {
// odd
terminate = slow
}
while begin?.next !== terminate! {
if begin?.val != tail?.val {
return false
}
begin = begin?.next
tail = tail?.next
}
return begin?.val == tail?.val
}
func reverseLinkedList(_ head: ListNode?) -> ListNode? {
var pre = head, next = pre?.next
while next != nil {
let tmp = next?.next
next?.next = pre
pre = next
next = tmp
}
return pre
}
}
| mit | b91748a5cb57cbc28472eaafde062a22 | 21.264706 | 61 | 0.463012 | 4.560241 | false | false | false | false |
zhubinchen/MarkLite | MarkLite/ViewController/RecentImagesViewController.swift | 2 | 3828 | //
// RecentImagesViewController.swift
// Markdown
//
// Created by 朱炳程 on 2019/11/10.
// Copyright © 2019 zhubch. All rights reserved.
//
import UIKit
import Kingfisher
private let reuseIdentifier = "Cell"
class RecentImagesViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
var items = [URL]()
var collectionView: UICollectionView!
var didPickRecentImage: ((URL)->Void)?
override func viewDidLoad() {
super.viewDidLoad()
title = /"Recent"
let layout = UICollectionViewFlowLayout()
collectionView = UICollectionView(frame: .zero, collectionViewLayout: layout)
collectionView.delegate = self
collectionView.dataSource = self
view.addSubview(collectionView)
collectionView.snp.makeConstraints { maker in
maker.top.bottom.equalTo(0)
maker.left.equalTo(2)
maker.right.equalTo(-2)
}
collectionView.register(RecentImageCell.self, forCellWithReuseIdentifier: reuseIdentifier)
collectionView.setBackgroundColor(.tableBackground)
view.setBackgroundColor(.tableBackground)
navBar?.setTintColor(.navTint)
navBar?.setBackgroundColor(.navBar)
navBar?.setTitleColor(.navTitle)
navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .cancel, target: self, action: #selector(close))
navigationItem.leftBarButtonItem = UIBarButtonItem(title: /"Clear", style: .plain, target: self, action: #selector(clear))
}
@objc func close() {
impactIfAllow()
dismiss(animated: true, completion: nil)
}
@objc func clear() {
impactIfAllow()
showDestructiveAlert(title: nil, message: /"ClearMessage", actionTitle: /"Clear") {
// Configure.shared.recentImages.removeAll()
// self.items = []
self.collectionView.reloadData()
KingfisherManager.shared.cache.clearDiskCache()
KingfisherManager.shared.cache.clearMemoryCache()
}
}
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return items.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! RecentImageCell
cell.setBackgroundColor(.background)
let url = items[indexPath.item]
if url.isFileURL {
cell.imageView.image = UIImage(contentsOfFile: url.path)
} else {
cell.imageView.kf.setImage(with: items[indexPath.item])
}
return cell
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
return 2
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
return 2
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let w = (view.w - 2 * 4) / 3
let h = w
return CGSize(width: w, height: h)
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
didPickRecentImage?(items[indexPath.item])
dismiss(animated: true, completion: nil)
impactIfAllow()
}
}
| gpl-3.0 | b10b839026754112f801ba9bb4790780 | 35.740385 | 175 | 0.677833 | 5.404526 | false | false | false | false |
qds-hoi/suracare | suracare/suracare/Core/Library/SwiftValidator/Rules/RegexRule.swift | 1 | 1561 | //
// RegexRule.swift
// Validator
//
// Created by Jeff Potter on 4/3/15.
// Copyright (c) 2015 jpotts18. All rights reserved.
//
import Foundation
/**
`RegexRule` is a subclass of Rule that defines how a regular expression is validated.
*/
public class RegexRule : Rule {
/// Regular express string to be used in validation.
private var REGEX: String = "^(?=.*?[A-Z]).{8,}$"
/// String that holds error message.
private var message : String
/**
Method used to initialize `RegexRule` object.
- parameter regex: Regular expression string to be used in validation.
- parameter message: String of error message.
- returns: An initialized `RegexRule` object, or nil if an object could not be created for some reason that would not result in an exception.
*/
public init(regex: String, message: String = "Invalid Regular Expression"){
self.REGEX = regex
self.message = message
}
/**
Method used to validate field.
- parameter value: String to checked for validation.
- returns: Boolean value. True if validation is successful; False if validation fails.
*/
public func validate(value: String) -> Bool {
let test = NSPredicate(format: "SELF MATCHES %@", self.REGEX)
return test.evaluateWithObject(value)
}
/**
Method used to dispaly error message when field fails validation.
- returns: String of error message.
*/
public func errorMessage() -> String {
return message
}
}
| mit | 8cd3f10ce4f958bd9e320ba609c799ec | 29.607843 | 146 | 0.647021 | 4.472779 | false | false | false | false |
tensorflow/swift-models | MiniGo/GameLib/GameConfiguration.swift | 1 | 1488 | // 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.
/// Represents an (immutable) configuration of a Go game.
public struct GameConfiguration {
/// The board size of the game.
public let size: Int
/// The points added to the score of the player with the white stones as compensation for playing
/// second.
public let komi: Float
/// The maximum number of board states to track.
///
/// This does not include the the current board.
public let maxHistoryCount: Int
/// If true, enables debugging information.
public let isVerboseDebuggingEnabled: Bool
public init(
size: Int,
komi: Float,
maxHistoryCount: Int = 7,
isVerboseDebuggingEnabled: Bool = false
) {
self.size = size
self.komi = komi
self.maxHistoryCount = maxHistoryCount
self.isVerboseDebuggingEnabled = isVerboseDebuggingEnabled
}
}
| apache-2.0 | 25c2a925fad0f4bc97492da594891656 | 33.604651 | 101 | 0.696909 | 4.428571 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.