repo_name
stringlengths 6
91
| path
stringlengths 8
968
| copies
stringclasses 210
values | size
stringlengths 2
7
| content
stringlengths 61
1.01M
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6
99.8
| line_max
int64 12
1k
| alpha_frac
float64 0.3
0.91
| ratio
float64 2
9.89
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
iwantooxxoox/CVCalendar
|
CVCalendar/CVCalendarManager.swift
|
8
|
8363
|
//
// CVCalendarManager.swift
// CVCalendar
//
// Created by E. Mozharovsky on 12/26/14.
// Copyright (c) 2014 GameApp. All rights reserved.
//
import UIKit
private let YearUnit = NSCalendarUnit.CalendarUnitYear
private let MonthUnit = NSCalendarUnit.CalendarUnitMonth
private let WeekUnit = NSCalendarUnit.CalendarUnitWeekOfMonth
private let WeekdayUnit = NSCalendarUnit.CalendarUnitWeekday
private let DayUnit = NSCalendarUnit.CalendarUnitDay
private let AllUnits = YearUnit | MonthUnit | WeekUnit | WeekdayUnit | DayUnit
public final class CVCalendarManager {
// MARK: - Private properties
private var components: NSDateComponents
private unowned let calendarView: CalendarView
public var calendar: NSCalendar
// MARK: - Public properties
public var currentDate: NSDate
// MARK: - Private initialization
public var starterWeekday: Int
public init(calendarView: CalendarView) {
self.calendarView = calendarView
currentDate = NSDate()
calendar = NSCalendar.currentCalendar()
components = calendar.components(MonthUnit | DayUnit, fromDate: currentDate)
starterWeekday = calendarView.firstWeekday.rawValue
calendar.firstWeekday = starterWeekday
}
// MARK: - Common date analysis
public func monthDateRange(date: NSDate) -> (countOfWeeks: NSInteger, monthStartDate: NSDate, monthEndDate: NSDate) {
let units = (YearUnit | MonthUnit | WeekUnit)
var components = calendar.components(units, fromDate: date)
// Start of the month.
components.day = 1
let monthStartDate = calendar.dateFromComponents(components)!
// End of the month.
components.month += 1
components.day -= 1
let monthEndDate = calendar.dateFromComponents(components)!
// Range of the month.
let range = calendar.rangeOfUnit(WeekUnit, inUnit: MonthUnit, forDate: date)
let countOfWeeks = range.length
return (countOfWeeks, monthStartDate, monthEndDate)
}
public static func dateRange(date: NSDate) -> (year: Int, month: Int, weekOfMonth: Int, day: Int) {
let components = componentsForDate(date)
let year = components.year
let month = components.month
let weekOfMonth = components.weekOfMonth
let day = components.day
return (year, month, weekOfMonth, day)
}
public func weekdayForDate(date: NSDate) -> Int {
let units = WeekdayUnit
let components = calendar.components(units, fromDate: date)
//println("NSDate: \(date), Weekday: \(components.weekday)")
let weekday = calendar.ordinalityOfUnit(units, inUnit: WeekUnit, forDate: date)
return Int(components.weekday)
}
// MARK: - Analysis sorting
public func weeksWithWeekdaysForMonthDate(date: NSDate) -> (weeksIn: [[Int : [Int]]], weeksOut: [[Int : [Int]]]) {
let countOfWeeks = self.monthDateRange(date).countOfWeeks
let totalCountOfDays = countOfWeeks * 7
let firstMonthDateIn = self.monthDateRange(date).monthStartDate
let lastMonthDateIn = self.monthDateRange(date).monthEndDate
let countOfDaysIn = Manager.dateRange(lastMonthDateIn).day
let countOfDaysOut = totalCountOfDays - countOfDaysIn
// Find all dates in.
var datesIn = [NSDate]()
for day in 1...countOfDaysIn {
let components = Manager.componentsForDate(firstMonthDateIn)
components.day = day
let date = calendar.dateFromComponents(components)!
datesIn.append(date)
}
// Find all dates out.
let firstMonthDateOut: NSDate? = {
let firstMonthDateInWeekday = self.weekdayForDate(firstMonthDateIn)
if firstMonthDateInWeekday == self.starterWeekday {
return firstMonthDateIn
}
let components = Manager.componentsForDate(firstMonthDateIn)
for _ in 1...7 {
components.day -= 1
let updatedDate = self.calendar.dateFromComponents(components)!
updatedDate
let updatedDateWeekday = self.weekdayForDate(updatedDate)
if updatedDateWeekday == self.starterWeekday {
updatedDate
return updatedDate
}
}
let diff = 7 - firstMonthDateInWeekday
for _ in diff..<7 {
components.day += 1
let updatedDate = self.calendar.dateFromComponents(components)!
let updatedDateWeekday = self.weekdayForDate(updatedDate)
if updatedDateWeekday == self.starterWeekday {
updatedDate
return updatedDate
}
}
return nil
}()
// Constructing weeks.
var firstWeekDates = [NSDate]()
var lastWeekDates = [NSDate]()
var firstWeekDate = (firstMonthDateOut != nil) ? firstMonthDateOut! : firstMonthDateIn
let components = Manager.componentsForDate(firstWeekDate)
components.day += 6
var lastWeekDate = calendar.dateFromComponents(components)!
func nextWeekDateFromDate(date: NSDate) -> NSDate {
let components = Manager.componentsForDate(date)
components.day += 7
let nextWeekDate = calendar.dateFromComponents(components)!
return nextWeekDate
}
for weekIndex in 1...countOfWeeks {
firstWeekDates.append(firstWeekDate)
lastWeekDates.append(lastWeekDate)
firstWeekDate = nextWeekDateFromDate(firstWeekDate)
lastWeekDate = nextWeekDateFromDate(lastWeekDate)
}
// Dictionaries.
var weeksIn = [[Int : [Int]]]()
var weeksOut = [[Int : [Int]]]()
let count = firstWeekDates.count
for i in 0..<count {
var weekdaysIn = [Int : [Int]]()
var weekdaysOut = [Int : [Int]]()
let firstWeekDate = firstWeekDates[i]
let lastWeekDate = lastWeekDates[i]
let components = Manager.componentsForDate(firstWeekDate)
for weekday in 1...7 {
let weekdate = calendar.dateFromComponents(components)!
components.day += 1
let day = Manager.dateRange(weekdate).day
func addDay(inout weekdays: [Int : [Int]]) {
var days = weekdays[weekday]
if days == nil {
days = [Int]()
}
days!.append(day)
weekdays.updateValue(days!, forKey: weekday)
}
if i == 0 && day > 20 {
addDay(&weekdaysOut)
} else if i == countOfWeeks - 1 && day < 10 {
addDay(&weekdaysOut)
} else {
addDay(&weekdaysIn)
}
}
if weekdaysIn.count > 0 {
weeksIn.append(weekdaysIn)
}
if weekdaysOut.count > 0 {
weeksOut.append(weekdaysOut)
}
}
return (weeksIn, weeksOut)
}
// MARK: - Util methods
public static func componentsForDate(date: NSDate) -> NSDateComponents {
let units = YearUnit | MonthUnit | WeekUnit | DayUnit
let components = NSCalendar.currentCalendar().components(units, fromDate: date)
return components
}
public static func dateFromYear(year: Int, month: Int, week: Int, day: Int) -> NSDate? {
let comps = Manager.componentsForDate(NSDate())
comps.year = year
comps.month = month
comps.weekOfMonth = week
comps.day = day
return NSCalendar.currentCalendar().dateFromComponents(comps)
}
}
|
mit
|
dec2941a48c64e3995295e049a6214f9
| 34.142857 | 121 | 0.571924 | 5.542081 | false | false | false | false |
ABTSoftware/SciChartiOSTutorial
|
v2.x/Showcase/SciChartShowcase/SciChartShowcaseDemo/MedicalExample/Controller/ECGChartController.swift
|
1
|
4744
|
//
// ECGSurfaceController.swift
// SciChartShowcaseDemo
//
// Created by Hrybeniuk Mykola on 2/23/17.
// Copyright © 2017 SciChart Ltd. All rights reserved.
//
import Foundation
import SciChart
class ECGChartController: BaseChartSurfaceController {
let wave1 : SCIFastLineRenderableSeries! = SCIFastLineRenderableSeries()
let wave2 : SCIFastLineRenderableSeries! = SCIFastLineRenderableSeries()
let data1 : SCIXyDataSeries! = SCIXyDataSeries(xType: .double, yType: .double)
let data2 : SCIXyDataSeries! = SCIXyDataSeries(xType: .double, yType: .double)
var newWave : SCIRenderableSeriesProtocol! = nil
var oldWave : SCIRenderableSeriesProtocol! = nil
var ecgData : SCIDataSeriesProtocol! = nil
var _currentDataIndex : Int32 = 0
var _totalDataIndex : Int32 = 0
let seriesColor : UIColor! = UIColor.green
let stroke : Float = 1.0
var fadeOutPalette : SwipingChartFadeOutPalette! = nil
var objcFadeOutPalette : MedicalFadeOutPaletteProvider! = nil
let fifoSize : Int32 = 4600
let dataSize : Int32 = 5000
override init(_ view: SCIChartSurface) {
super.init(view)
objcFadeOutPalette = MedicalFadeOutPaletteProvider(seriesColor: seriesColor, stroke: stroke)
let lineStyle : SCILineSeriesStyle = SCILineSeriesStyle()
let linePen : SCIPenStyle = SCISolidPenStyle(color: seriesColor, withThickness: stroke)
lineStyle.strokeStyle = linePen
wave1.style = lineStyle
wave2.style = lineStyle
data1.fifoCapacity = fifoSize
data2.fifoCapacity = fifoSize
wave1.dataSeries = data1
wave2.dataSeries = data2
wave1.paletteProvider = objcFadeOutPalette
wave2.paletteProvider = objcFadeOutPalette
var axisStyle = SCIAxisStyle()
axisStyle.drawLabels = false
axisStyle.drawMajorBands = false
axisStyle.drawMinorGridLines = false
axisStyle.drawMinorTicks = false
let xAxis : SCINumericAxis = SCINumericAxis()
xAxis.style = axisStyle
xAxis.autoRange = .never
xAxis.visibleRange = SCIDoubleRange(min: SCIGeneric(0), max: SCIGeneric(10))
// xAxis.growBy = SCIDoubleRange(min: SCIGeneric(0.05), max: SCIGeneric(0.05))
axisStyle = SCIAxisStyle()
axisStyle.drawLabels = false
axisStyle.drawMajorBands = false
axisStyle.drawMinorGridLines = false
axisStyle.drawMinorTicks = false
axisStyle.drawMajorTicks = false
axisStyle.drawMajorGridLines = false
let yAxis : SCINumericAxis = SCINumericAxis()
yAxis.style = axisStyle
yAxis.autoRange = .never
yAxis.visibleRange = SCIDoubleRange(min: SCIGeneric(0.78), max: SCIGeneric(0.95))
// yAxis.growBy = SCIDoubleRange(min: SCIGeneric(0.05), max: SCIGeneric(0.05))
chartSurface.xAxes.add(xAxis)
chartSurface.yAxes.add(yAxis)
chartSurface.renderableSeries.add(wave1)
chartSurface.renderableSeries.add(wave2)
newWave = wave1
oldWave = wave2
chartSurface.bottomAxisAreaForcedSize = 0.0
chartSurface.topAxisAreaForcedSize = 0.0
chartSurface.leftAxisAreaForcedSize = 0.0
chartSurface.rightAxisAreaForcedSize = 0.0
DispatchQueue.main.asyncAfter(deadline: .now() + 0.2, execute: {
DataManager.getHeartRateData { (dataSeries: SCIDataSeriesProtocol, errorMessage) in
self.ecgData = dataSeries
}
})
}
@objc func onTimerElapsed(timeInterval: Double) {
if (ecgData == nil) { return }
let sampleRate : Double = 400;
let countOfPoints = Int(400*timeInterval);
for _ in 0...countOfPoints {
appendPoint(sampleRate)
}
}
func appendPoint(_ sampleRate : Double) {
if (_currentDataIndex >= dataSize) {
_currentDataIndex = 0;
}
let value : Double = SCIGenericDouble( ecgData.yValues().value(at: _currentDataIndex) )
let time : Double = 10 * (Double(_currentDataIndex) / Double(dataSize))
(newWave.dataSeries as! SCIXyDataSeries).appendX(SCIGeneric(time), y: SCIGeneric(value))
(oldWave.dataSeries as! SCIXyDataSeries).appendX(SCIGeneric(time), y: SCIGeneric(Double.nan))
_currentDataIndex += 1
_totalDataIndex += 1
if (_totalDataIndex % dataSize == 0) {
let swap = oldWave
oldWave = newWave
newWave = swap
}
chartSurface.invalidateElement()
}
}
|
mit
|
6db1ea70b68f4224ff30551dea6ec71a
| 34.133333 | 101 | 0.638625 | 4.445173 | false | false | false | false |
sora0077/iTunesMusic
|
Sources/Entity/Entity.swift
|
1
|
1269
|
//
// Entity.swift
// iTunesMusic
//
// Created by 林達也 on 2016/07/31.
// Copyright © 2016年 jp.sora0077. All rights reserved.
//
import Foundation
import RealmSwift
@objc
final class _Media: RealmSwift.Object {
enum MediaType {
case track(Track)
case collection(Collection)
case artist(Artist)
}
@objc fileprivate(set) dynamic var track: _Track?
@objc fileprivate(set) dynamic var collection: _Collection?
@objc fileprivate(set) dynamic var artist: _Artist?
var type: MediaType {
switch (track, collection, artist) {
case (let track?, _, _): return .track(track)
case (_, let collection?, _): return .collection(collection)
case (_, _, let artist?): return .artist(artist)
default:
fatalError()
}
}
static func track(_ track: _Track) -> Self {
let media = self.init()
media.track = track
return media
}
static func collection(_ collection: _Collection) -> Self {
let media = self.init()
media.collection = collection
return media
}
static func artist(_ artist: _Artist) -> Self {
let media = self.init()
media.artist = artist
return media
}
}
|
mit
|
61f207586d11c8f02b29037af32e939b
| 24.2 | 68 | 0.595238 | 4.256757 | false | false | false | false |
Fenrikur/ef-app_ios
|
Eurofurence/Modules/Schedule/View/UIKit/ScheduleDayCollectionViewCell.swift
|
1
|
990
|
import UIKit
class ScheduleDayCollectionViewCell: UICollectionViewCell, ScheduleDayComponent {
@IBOutlet private weak var selectedDecorationView: UIView!
@IBOutlet private weak var dayTitleLabel: UILabel!
override var isSelected: Bool {
didSet {
updateSelectionStateAppearence()
}
}
override func awakeFromNib() {
super.awakeFromNib()
updateSelectionStateAppearence()
}
private func updateSelectionStateAppearence() {
selectedDecorationView.alpha = isSelected ? 1 : 0
let font: UIFont = {
let size = UIFont.preferredFont(forTextStyle: .footnote).pointSize
return isSelected ? UIFont.boldSystemFont(ofSize: size) : UIFont.systemFont(ofSize: size)
}()
dayTitleLabel.font = font
}
func setDayTitle(_ title: String) {
dayTitleLabel.text = title
dayTitleLabel.accessibilityHint = .restrictEventsAccessibilityHint(date: title)
}
}
|
mit
|
52ed5fc1c49f772256bb930628bb9b9a
| 27.285714 | 101 | 0.674747 | 5.294118 | false | false | false | false |
esttorhe/RxSwift
|
RxSwift/RxSwift/Observables/Implementations/Scan.swift
|
1
|
1955
|
//
// Scan.swift
// RxSwift
//
// Created by Krunoslav Zaher on 6/14/15.
// Copyright (c) 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
class ScanSink<ElementType, Accumulate, O: ObserverType where O.Element == Accumulate> : Sink<O>, ObserverType {
typealias Parent = Scan<ElementType, Accumulate>
typealias Element = ElementType
let parent: Parent
var accumulate: Accumulate
init(parent: Parent, observer: O, cancel: Disposable) {
self.parent = parent
self.accumulate = parent.seed
super.init(observer: observer, cancel: cancel)
}
func on(event: Event<ElementType>) {
switch event {
case .Next(let element):
self.parent.accumulator(self.accumulate, element).map { result -> Void in
self.accumulate = result
trySendNext(observer, result)
}.recover { error in
trySendError(self.observer, error)
self.dispose()
}
case .Error(let error):
trySendError(observer, error)
self.dispose()
case .Completed:
trySendCompleted(observer)
self.dispose()
}
}
}
class Scan<Element, Accumulate>: Producer<Accumulate> {
typealias Accumulator = (Accumulate, Element) -> RxResult<Accumulate>
let source: Observable<Element>
let seed: Accumulate
let accumulator: Accumulator
init(source: Observable<Element>, seed: Accumulate, accumulator: Accumulator) {
self.source = source
self.seed = seed
self.accumulator = accumulator
}
override func run<O : ObserverType where O.Element == Accumulate>(observer: O, cancel: Disposable, setSink: (Disposable) -> Void) -> Disposable {
let sink = ScanSink(parent: self, observer: observer, cancel: cancel)
setSink(sink)
return source.subscribeSafe(sink)
}
}
|
mit
|
8dcf8271a5cdb912a4cf314d63db4b51
| 30.047619 | 149 | 0.620972 | 4.632701 | false | false | false | false |
AliSoftware/Dip
|
Sources/TypeForwarding.swift
|
2
|
5746
|
//
// Dip
//
// Copyright (c) 2015 Olivier Halligon <[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.
//
protocol TypeForwardingDefinition: DefinitionType {
var implementingTypes: [Any.Type] { get }
func doesImplements(type aType: Any.Type) -> Bool
}
extension Definition {
/**
Registers definition for passed type.
If instance created by factory of definition on which method is called
does not implement type passed in a `type` parameter,
container will throw `DipError.DefinitionNotFound` error when trying to resolve that type.
- parameters:
- type: Type to register definition for
- tag: Optional tag to associate definition with. Default is `nil`.
- returns: definition on which `implements` was called
*/
@discardableResult public func implements<F>(_ type: F.Type, tag: DependencyTagConvertible? = nil) -> Definition {
precondition(container != nil, "Definition should be registered in the container.")
container!.register(self, type: type, tag: tag)
return self
}
/**
Registers definition for passed type.
If instance created by factory of definition on which method is called
does not implement type passed in a `type` parameter,
container will throw `DipError.DefinitionNotFound` error when trying to resolve that type.
- parameters:
- type: Type to register definition for
- tag: Optional tag to associate definition with. Default is `nil`.
- resolvingProperties: Optional block to be called to resolve instance property dependencies
- returns: definition on which `implements` was called
*/
@discardableResult public func implements<F>(_ type: F.Type, tag: DependencyTagConvertible? = nil, resolvingProperties: @escaping (DependencyContainer, F) throws -> ()) -> Definition {
precondition(container != nil, "Definition should be registered in the container.")
let forwardDefinition = container!.register(self, type: type, tag: tag)
forwardDefinition.resolvingProperties(resolvingProperties)
return self
}
///Registers definition for types passed as parameters
@discardableResult public func implements<A, B>(_ a: A.Type, _ b: B.Type) -> Definition {
return implements(a).implements(b)
}
///Registers definition for types passed as parameters
@discardableResult public func implements<A, B, C>(_ a: A.Type, _ b: B.Type, _ c: C.Type) -> Definition {
return implements(a).implements(b).implements(c)
}
///Registers definition for types passed as parameters
@discardableResult public func implements<A, B, C, D>(_ a: A.Type, _ b: B.Type, _ c: C.Type, _ d: D.Type) -> Definition {
return implements(a).implements(b).implements(c).implements(d)
}
}
extension DependencyContainer {
func _register<T, U, F>(definition aDefinition: Definition<T, U>, type: F.Type, tag: DependencyTagConvertible? = nil) -> Definition<F, U> {
let definition = aDefinition
precondition(definition.container === self, "Definition should be registered in the container.")
let key = DefinitionKey(type: F.self, typeOfArguments: U.self)
let forwardDefinition = DefinitionBuilder<F, U> {
$0.scope = definition.scope
let factory = definition.factory
$0.factory = { [unowned self] in
let resolved = try factory($0)
if let resolved = resolved as? F {
return resolved
}
else {
throw DipError.invalidType(resolved: resolved, key: key.tagged(with: self.context.tag))
}
}
$0.numberOfArguments = definition.numberOfArguments
$0.autoWiringFactory = definition.autoWiringFactory.map({ factory in
{ [unowned self] in
let resolved = try factory($0, $1)
if let resolved = resolved as? F {
return resolved
}
else {
throw DipError.invalidType(resolved: resolved, key: key.tagged(with: self.context.tag))
}
}
})
$0.forwardsTo = definition
}.build()
register(forwardDefinition, tag: tag)
return forwardDefinition
}
/// Searches for definition that forwards requested type
func typeForwardingDefinition(forKey key: DefinitionKey) -> KeyDefinitionPair? {
var forwardingDefinitions = self.definitions.map({ (key: $0.0, definition: $0.1) })
forwardingDefinitions = filter(definitions: forwardingDefinitions, byKey: key, byTypeOfArguments: true)
forwardingDefinitions = order(definitions: forwardingDefinitions, byTag: key.tag)
//we need to carry on original tag
return forwardingDefinitions.first.map({ ($0.key.tagged(with: key.tag), $0.definition) })
}
}
|
mit
|
72258db440a9e59e442f2084b966392d
| 39.181818 | 186 | 0.700487 | 4.450813 | false | false | false | false |
Norod/Filterpedia
|
Filterpedia/customFilters/ThirdPartyFilters.swift
|
1
|
2911
|
//
// ThirdPartyFilters.swift
// Filterpedia
//
// Created by Simon Gladman on 10/02/2016.
// Copyright © 2016 Simon Gladman. All rights reserved.
//
// Guest filters live here!
import CoreImage
// MARK: BayerDitherFilter
// Created by African Swift on 09/02/2016.
// https://twitter.com/SwiftAfricanus
class BayerDitherFilter: CIFilter
{
var inputImage: CIImage?
var inputIntensity = CGFloat(5.0)
var inputMatrix = CGFloat(8.0)
var inputPalette = CGFloat(0.0)
override var attributes: [String : Any]
{
return [
kCIAttributeFilterDisplayName: "Bayer Dither Filter",
"inputImage": [kCIAttributeIdentity: 0,
kCIAttributeClass: "CIImage",
kCIAttributeDisplayName: "Image",
kCIAttributeType: kCIAttributeTypeImage],
"inputIntensity": [kCIAttributeIdentity: 0,
kCIAttributeClass: "NSNumber",
kCIAttributeDescription: "Intensity: Range from 0.0 to 10.0",
kCIAttributeDefault: 5.0,
kCIAttributeDisplayName: "Intensity",
kCIAttributeMin: 0,
kCIAttributeSliderMin: 0,
kCIAttributeSliderMax: 10,
kCIAttributeType: kCIAttributeTypeScalar],
"inputMatrix": [kCIAttributeIdentity: 0,
kCIAttributeClass: "NSNumber",
kCIAttributeDescription: "Matrix: 2, 3, 4, 8",
kCIAttributeDefault: 8,
kCIAttributeDisplayName: "Matrix",
kCIAttributeMin: 2,
kCIAttributeSliderMin: 2,
kCIAttributeSliderMax: 8,
kCIAttributeType: kCIAttributeTypeScalar],
"inputPalette": [kCIAttributeIdentity: 0,
kCIAttributeClass: "NSNumber",
kCIAttributeDescription: "Palette: 0 = Binary, 1 = Commodore 64, 2 = Vic-20, 3 = Apple II, 4 = ZX Spectrum Bright, 5 = ZX Spectrum Dim, 6 = RGB",
kCIAttributeDefault: 0.0,
kCIAttributeDisplayName: "Palette",
kCIAttributeMin: 0,
kCIAttributeSliderMin: 0,
kCIAttributeSliderMax: 6,
kCIAttributeType: kCIAttributeTypeScalar]]
}
override var outputImage: CIImage!
{
let CIKernel_DitherBayer = Bundle.main.path(forResource: "DitherBayer", ofType: "cikernel")
guard let path = CIKernel_DitherBayer,
let code = try? String(contentsOfFile: path),
let ditherKernel = CIColorKernel(string: code) else { return nil }
guard let inputImage = inputImage else { return nil }
let extent = inputImage.extent
let arguments = [inputImage, inputIntensity, inputMatrix, inputPalette] as [Any]
return ditherKernel.apply(withExtent: extent, arguments: arguments)
}
}
|
gpl-3.0
|
6cade33bf5015bc8dfe140da0c35f99b
| 37.289474 | 161 | 0.602405 | 5.196429 | false | false | false | false |
qvacua/vimr
|
VimR/VimR/RxRedux.swift
|
1
|
5347
|
/**
* Tae Won Ha - http://taewon.de - @hataewon
* See LICENSE
*/
import Foundation
import RxSwift
protocol ReduxContextType {
/**
Type that holds the global app state
- Important:
This type must be typealias'ed in `ReduxTypes` or in an extension thereof.
*/
associatedtype StateType
/**
"The greatest common divisor" for all actions used in the app:
Assuming it is set to `ReduxTypes.ActionType` type, the following must be true for any action
```
assert(someAction is ReduxTypes.ActionType) // which means
let actionWithMinimumType: ReduxTypes.ActionType = anyAction
```
Most probably this type will be set to `Any`.
- Important:
This type must be typealias'ed in `ReduxTypes` or in an extension thereof.
*/
associatedtype ActionType
/**
We use tuple since SomeStruct<A, B> as? SomeStruct<A, Any> always fails,
but (A, B) as? (A, Any) succeeds.
*/
typealias ReduceTuple = (state: StateType, action: ActionType, modified: Bool)
typealias ReduceFunction = (ReduceTuple) -> ReduceTuple
}
/**
`typealias` `StateType` and `ActionType` either within the class definition or in an extension.
*/
final class ReduxTypes: ReduxContextType {}
protocol ReducerType {
associatedtype StateType
associatedtype ActionType
typealias ReduceTuple = (state: StateType, action: ActionType, modified: Bool)
typealias ActionTypeErasedReduceTuple = (
state: StateType,
action: ReduxTypes.ActionType,
modified: Bool
)
func typedReduce(_ tuple: ReduceTuple) -> ReduceTuple
}
extension ReducerType {
func reduce(_ tuple: ActionTypeErasedReduceTuple) -> ActionTypeErasedReduceTuple {
guard let typedTuple = tuple as? ReduceTuple else { return tuple }
let typedResult = self.typedReduce(typedTuple)
return (state: typedResult.state, action: typedResult.action, modified: typedResult.modified)
}
}
protocol MiddlewareType {
associatedtype StateType
associatedtype ActionType
typealias ReduceTuple = (state: StateType, action: ActionType, modified: Bool)
typealias ActionTypeErasedReduceTuple = (
state: StateType,
action: ReduxTypes.ActionType,
modified: Bool
)
typealias TypedActionReduceFunction = (ReduceTuple) -> ActionTypeErasedReduceTuple
typealias ActionTypeErasedReduceFunction = (ActionTypeErasedReduceTuple)
-> ActionTypeErasedReduceTuple
func typedApply(_ reduce: @escaping TypedActionReduceFunction) -> TypedActionReduceFunction
}
extension MiddlewareType {
func apply(_ reduce: @escaping ActionTypeErasedReduceFunction) -> ActionTypeErasedReduceFunction {
{ tuple in
guard let typedTuple = tuple as? ReduceTuple else { return reduce(tuple) }
let typedReduce: (ReduceTuple) -> ActionTypeErasedReduceTuple = { typedTuple in
// We know that we can cast the typed action to ReduxTypes.ActionType
reduce((state: typedTuple.state, action: typedTuple.action, modified: typedTuple.modified))
}
return self.typedApply(typedReduce)(typedTuple)
}
}
}
protocol EpicType: MiddlewareType {
associatedtype EmitActionType
init(emitter: ActionEmitter)
}
protocol UiComponent {
associatedtype StateType
init(source: Observable<StateType>, emitter: ActionEmitter, state: StateType)
}
final class ActionEmitter {
var observable: Observable<ReduxTypes.ActionType> {
self.subject.asObservable().observe(on: self.scheduler)
}
func typedEmit<T>() -> (T) -> Void {{ (action: T) in self.subject.onNext(action) } }
func terminate() { self.subject.onCompleted() }
deinit { self.subject.onCompleted() }
private let scheduler = SerialDispatchQueueScheduler(qos: .userInteractive)
private let subject = PublishSubject<ReduxTypes.ActionType>()
}
class ReduxContext {
let actionEmitter = ActionEmitter()
let stateSource: Observable<ReduxTypes.StateType>
convenience init(
initialState: ReduxTypes.StateType,
reducers: [ReduxTypes.ReduceFunction],
middlewares: [(@escaping ReduxTypes.ReduceFunction) -> ReduxTypes.ReduceFunction] = []
) {
self.init(initialState: initialState)
self.actionEmitter.observable
.map { (state: self.state, action: $0, modified: false) }
.reduce(by: reducers, middlewares: middlewares)
.filter { $0.modified }
.subscribe(onNext: { tuple in
self.state = tuple.state
self.stateSubject.onNext(tuple.state)
})
.disposed(by: self.disposeBag)
}
init(initialState: ReduxTypes.StateType) {
self.state = initialState
self.stateSource = self.stateSubject.asObservable().observe(on: self.stateScheduler)
}
func terminate() {
self.actionEmitter.terminate()
self.stateSubject.onCompleted()
}
var state: ReduxTypes.StateType
let stateSubject = PublishSubject<ReduxTypes.StateType>()
let stateScheduler = SerialDispatchQueueScheduler(qos: .userInteractive)
let disposeBag = DisposeBag()
}
extension Observable {
func reduce(
by reducers: [(Element) -> Element],
middlewares: [(@escaping (Element) -> Element) -> (Element) -> Element]
) -> Observable<Element> {
let dispatch = { pair in
reducers.reduce(pair) { result, reduceBody in reduceBody(result) }
}
let next = middlewares.reversed().reduce(dispatch) { result, middleware in middleware(result) }
return self.map(next)
}
}
|
mit
|
fb16ee69a565189e45832990c23c73bd
| 28.705556 | 100 | 0.724331 | 4.319063 | false | false | false | false |
cburrows/swift-protobuf
|
Tests/SwiftProtobufTests/Test_Timestamp.swift
|
1
|
18097
|
// Tests/SwiftProtobufTests/Test_Timestamp.swift - VerifyA well-known Timestamp type
//
// Copyright (c) 2014 - 2016 Apple Inc. and the project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See LICENSE.txt for license information:
// https://github.com/apple/swift-protobuf/blob/main/LICENSE.txt
//
// -----------------------------------------------------------------------------
///
/// Proto3 defines a standard Timestamp message type that represents a
/// single moment in time with nanosecond precision. The in-memory form
/// stores a count of seconds since the Unix epoch and a separate count
/// of nanoseconds. The binary serialized form is unexceptional. The JSON
/// serialized form represents the time as a string using an ISO8601 variant.
/// The implementation in the runtime library includes a variety of convenience
/// methods to simplify use, including arithmetic operations on timestamps
/// and durations.
///
// -----------------------------------------------------------------------------
import Foundation
import XCTest
import SwiftProtobuf
class Test_Timestamp: XCTestCase, PBTestHelpers {
typealias MessageTestType = Google_Protobuf_Timestamp
func testJSON() throws {
XCTAssertEqual("\"1970-01-01T00:00:00Z\"",
try Google_Protobuf_Timestamp().jsonString())
assertJSONEncode("\"1970-01-01T00:00:01.000000001Z\"") {
(o: inout MessageTestType) in
o.seconds = 1 // 1 second
o.nanos = 1
}
assertJSONEncode("\"1970-01-01T00:01:00.000000010Z\"") {
(o: inout MessageTestType) in
o.seconds = 60 // 1 minute
o.nanos = 10
}
assertJSONEncode("\"1970-01-01T01:00:00.000000100Z\"") {
(o: inout MessageTestType) in
o.seconds = 3600 // 1 hour
o.nanos = 100
}
assertJSONEncode("\"1970-01-02T00:00:00.000001Z\"") {
(o: inout MessageTestType) in
o.seconds = 86400 // 1 day
o.nanos = 1000
}
assertJSONEncode("\"1970-02-01T00:00:00.000010Z\"") {
(o: inout MessageTestType) in
o.seconds = 2678400 // 1 month
o.nanos = 10000
}
assertJSONEncode("\"1971-01-01T00:00:00.000100Z\"") {
(o: inout MessageTestType) in
o.seconds = 31536000 // 1 year
o.nanos = 100000
}
assertJSONEncode("\"1970-01-01T00:00:01.001Z\"") {
(o: inout MessageTestType) in
o.seconds = 1
o.nanos = 1000000
}
assertJSONEncode("\"1970-01-01T00:00:01.010Z\"") {
(o: inout MessageTestType) in
o.seconds = 1
o.nanos = 10000000
}
assertJSONEncode("\"1970-01-01T00:00:01.100Z\"") {
(o: inout MessageTestType) in
o.seconds = 1
o.nanos = 100000000
}
assertJSONEncode("\"1970-01-01T00:00:01Z\"") {
(o: inout MessageTestType) in
o.seconds = 1
o.nanos = 0
}
// Largest representable date
assertJSONEncode("\"9999-12-31T23:59:59.999999999Z\"") {
(o: inout MessageTestType) in
o.seconds = 253402300799
o.nanos = 999999999
}
// 10 billion seconds after Epoch
assertJSONEncode("\"2286-11-20T17:46:40Z\"") {
(o: inout MessageTestType) in
o.seconds = 10000000000
o.nanos = 0
}
// 1 billion seconds after Epoch
assertJSONEncode("\"2001-09-09T01:46:40Z\"") {
(o: inout MessageTestType) in
o.seconds = 1000000000
o.nanos = 0
}
// 1 million seconds after Epoch
assertJSONEncode("\"1970-01-12T13:46:40Z\"") {
(o: inout MessageTestType) in
o.seconds = 1000000
o.nanos = 0
}
// 1 thousand seconds after Epoch
assertJSONEncode("\"1970-01-01T00:16:40Z\"") {
(o: inout MessageTestType) in
o.seconds = 1000
o.nanos = 0
}
// 1 thousand seconds before Epoch
assertJSONEncode("\"1969-12-31T23:43:20Z\"") {
(o: inout MessageTestType) in
o.seconds = -1000
o.nanos = 0
}
// 1 million seconds before Epoch
assertJSONEncode("\"1969-12-20T10:13:20Z\"") {
(o: inout MessageTestType) in
o.seconds = -1000000
o.nanos = 0
}
// 1 billion seconds before Epoch
assertJSONEncode("\"1938-04-24T22:13:20Z\"") {
(o: inout MessageTestType) in
o.seconds = -1000000000
o.nanos = 0
}
// 10 billion seconds before Epoch
assertJSONEncode("\"1653-02-10T06:13:20Z\"") {
(o: inout MessageTestType) in
o.seconds = -10000000000
o.nanos = 0
}
// Earliest leap year
assertJSONEncode("\"0004-02-19T02:50:24Z\"") {
(o: inout MessageTestType) in
o.seconds = -62036744976
o.nanos = 0
}
// Earliest representable date
assertJSONEncode("\"0001-01-01T00:00:00Z\"") {
(o: inout MessageTestType) in
o.seconds = -62135596800
o.nanos = 0
}
// Truncated forms w/o timezone should not read past end of string
assertJSONDecodeFails("\"9999-12-31T00:00:00.00000000\"")
assertJSONDecodeFails("\"9999-12-31T00:00:00.0000000\"")
assertJSONDecodeFails("\"9999-12-31T00:00:00.000000\"")
assertJSONDecodeFails("\"9999-12-31T00:00:00.00000\"")
assertJSONDecodeFails("\"9999-12-31T00:00:00.0000\"")
assertJSONDecodeFails("\"9999-12-31T00:00:00.000\"")
assertJSONDecodeFails("\"9999-12-31T00:00:00.00\"")
assertJSONDecodeFails("\"9999-12-31T00:00:00.0\"")
assertJSONDecodeFails("\"9999-12-31T00:00:00.\"")
assertJSONDecodeFails("\"9999-12-31T00:00:00\"")
}
func testJSON_range() throws {
// Check that JSON timestamps round-trip correctly over a wide range.
// This checks about 15,000 dates scattered over a 10,000 year period
// to verify that our JSON encoder and decoder agree with each other.
// Combined with the above checks of specific known dates, this gives a
// pretty high confidence that our date calculations are correct.
let earliest: Int64 = -62135596800
let latest: Int64 = 253402300799
// Use a smaller increment to get more exhaustive testing. An
// increment of 12345 will test every single day in the entire
// 10,000 year range and require about 15 minutes to run.
// An increment of 12345678 will pick about one day out of
// every 5 months and require only a few seconds to run.
let increment: Int64 = 12345678
var t: Int64 = earliest
// If things are broken, this test can easily generate >10,000 failures.
// That many failures can break a lot of tools (Xcode, for example), so
// we do a little extra work here to only print out the first failure
// of each type and the total number of failures at the end.
var encodingFailures = 0
var decodingFailures = 0
var roundTripFailures = 0
while t < latest {
let start = Google_Protobuf_Timestamp(seconds: t)
do {
let encoded = try start.jsonString()
do {
let decoded = try Google_Protobuf_Timestamp(jsonString: encoded)
if decoded.seconds != t {
if roundTripFailures == 0 {
// Only the first round-trip failure will be reported here
XCTAssertEqual(decoded.seconds, t, "Round-trip failed for \(encoded): \(t) != \(decoded.seconds)")
}
roundTripFailures += 1
}
} catch {
if decodingFailures == 0 {
// Only the first decoding failure will be reported here
XCTFail("Could not decode \(encoded)")
}
decodingFailures += 1
}
} catch {
if encodingFailures == 0 {
// Only the first encoding failure will be reported here
XCTFail("Could not encode \(start)")
}
encodingFailures += 1
}
t += increment
}
// Report the total number of failures (but silence if there weren't any)
XCTAssertEqual(encodingFailures, 0)
XCTAssertEqual(decodingFailures, 0)
XCTAssertEqual(roundTripFailures, 0)
}
func testJSON_timezones() {
assertJSONDecodeSucceeds("\"1970-01-01T08:00:00+08:00\"") {$0.seconds == 0}
assertJSONDecodeSucceeds("\"1969-12-31T16:00:00-08:00\"") {$0.seconds == 0}
assertJSONDecodeFails("\"0001-01-01T00:00:00+23:59\"")
assertJSONDecodeFails("\"9999-12-31T23:59:59-23:59\"")
}
func testJSON_timestampField() throws {
do {
let valid = try ProtobufTestMessages_Proto3_TestAllTypesProto3(jsonString: "{\"optionalTimestamp\": \"0001-01-01T00:00:00Z\"}")
XCTAssertEqual(valid.optionalTimestamp, Google_Protobuf_Timestamp(seconds: -62135596800))
} catch {
XCTFail("Should have decoded correctly")
}
XCTAssertThrowsError(try ProtobufTestMessages_Proto3_TestAllTypesProto3(jsonString: "{\"optionalTimestamp\": \"10000-01-01T00:00:00Z\"}"))
XCTAssertThrowsError(try ProtobufTestMessages_Proto3_TestAllTypesProto3(jsonString: "{\"optionalTimestamp\": \"0001-01-01T00:00:00\"}"))
XCTAssertThrowsError(try ProtobufTestMessages_Proto3_TestAllTypesProto3(jsonString: "{\"optionalTimestamp\": \"0001-01-01 00:00:00Z\"}"))
XCTAssertThrowsError(try ProtobufTestMessages_Proto3_TestAllTypesProto3(jsonString: "{\"optionalTimestamp\": \"0001-01-01T00:00:00z\"}"))
XCTAssertThrowsError(try ProtobufTestMessages_Proto3_TestAllTypesProto3(jsonString: "{\"optionalTimestamp\": \"0001-01-01t00:00:00Z\"}"))
}
// A couple more test cases transcribed from conformance test
func testJSON_conformance() throws {
let t1 = Google_Protobuf_Timestamp(seconds: 0, nanos: 10000000)
var m1 = ProtobufTestMessages_Proto3_TestAllTypesProto3()
m1.optionalTimestamp = t1
let expected1 = "{\"optionalTimestamp\":\"1970-01-01T00:00:00.010Z\"}"
XCTAssertEqual(try m1.jsonString(), expected1)
let json2 = "{\"optionalTimestamp\": \"1970-01-01T00:00:00.010000000Z\"}"
let expected2 = "{\"optionalTimestamp\":\"1970-01-01T00:00:00.010Z\"}"
do {
let m2 = try ProtobufTestMessages_Proto3_TestAllTypesProto3(jsonString: json2)
do {
let recoded2 = try m2.jsonString()
XCTAssertEqual(recoded2, expected2)
} catch {
XCTFail()
}
} catch {
XCTFail()
}
// Extra spaces around all the tokens.
let json3 = " { \"repeatedTimestamp\" : [ \"0001-01-01T00:00:00Z\" , \"9999-12-31T23:59:59.999999999Z\" ] } "
let m3 = try ProtobufTestMessages_Proto3_TestAllTypesProto3(jsonString: json3)
let expected3 = [Google_Protobuf_Timestamp(seconds: -62135596800),
Google_Protobuf_Timestamp(seconds: 253402300799, nanos: 999999999)]
XCTAssertEqual(m3.repeatedTimestamp, expected3)
}
func testSerializationFailure() throws {
let maxOutOfRange = Google_Protobuf_Timestamp(seconds:-62135596800, nanos: -1)
XCTAssertThrowsError(try maxOutOfRange.jsonString())
let minInRange = Google_Protobuf_Timestamp(seconds:-62135596800)
XCTAssertNotNil(try minInRange.jsonString())
let maxInRange = Google_Protobuf_Timestamp(seconds:253402300799, nanos: 999999999)
XCTAssertNotNil(try maxInRange.jsonString())
let minOutOfRange = Google_Protobuf_Timestamp(seconds:253402300800)
XCTAssertThrowsError(try minOutOfRange.jsonString())
}
func testBasicArithmetic() throws {
let tn1_n1 = Google_Protobuf_Timestamp(seconds: -2, nanos: 999999999)
let t0 = Google_Protobuf_Timestamp()
let t1_1 = Google_Protobuf_Timestamp(seconds: 1, nanos: 1)
let t2_2 = Google_Protobuf_Timestamp(seconds: 2, nanos: 2)
let t3_3 = Google_Protobuf_Timestamp(seconds: 3, nanos: 3)
let t4_4 = Google_Protobuf_Timestamp(seconds: 4, nanos: 4)
let dn1_n1 = Google_Protobuf_Duration(seconds: -1, nanos: -1)
let d0 = Google_Protobuf_Duration()
let d1_1 = Google_Protobuf_Duration(seconds: 1, nanos: 1)
let d2_2 = Google_Protobuf_Duration(seconds: 2, nanos: 2)
let d3_3 = Google_Protobuf_Duration(seconds: 3, nanos: 3)
let d4_4 = Google_Protobuf_Duration(seconds: 4, nanos: 4)
// Durations can be added to or subtracted from timestamps
XCTAssertEqual(t1_1, t0 + d1_1)
XCTAssertEqual(t1_1, t1_1 + d0)
XCTAssertEqual(t2_2, t1_1 + d1_1)
XCTAssertEqual(t3_3, t1_1 + d2_2)
XCTAssertEqual(t1_1, t4_4 - d3_3)
XCTAssertEqual(tn1_n1, t3_3 - d4_4)
XCTAssertEqual(tn1_n1, t3_3 + -d4_4)
// Difference of two timestamps is a duration
XCTAssertEqual(d1_1, t4_4 - t3_3)
XCTAssertEqual(dn1_n1, t3_3 - t4_4)
}
func testArithmeticNormalizes() throws {
// Addition normalizes the result
let r1: Google_Protobuf_Timestamp = Google_Protobuf_Timestamp() + Google_Protobuf_Duration(seconds: 0, nanos: 2000000001)
XCTAssertEqual(r1.seconds, 2)
XCTAssertEqual(r1.nanos, 1)
// Subtraction normalizes the result
let r2: Google_Protobuf_Timestamp = Google_Protobuf_Timestamp() - Google_Protobuf_Duration(seconds: 0, nanos: 2000000001)
XCTAssertEqual(r2.seconds, -3)
XCTAssertEqual(r2.nanos, 999999999)
// Subtraction normalizes the result
let r3: Google_Protobuf_Duration = Google_Protobuf_Timestamp() - Google_Protobuf_Timestamp(seconds: 0, nanos: 2000000001)
XCTAssertEqual(r3.seconds, -2)
XCTAssertEqual(r3.nanos, -1)
let r4: Google_Protobuf_Duration = Google_Protobuf_Timestamp(seconds: 1) - Google_Protobuf_Timestamp(nanos: 2000000001)
XCTAssertEqual(r4.seconds, -1)
XCTAssertEqual(r4.nanos, -1)
let r5: Google_Protobuf_Duration = Google_Protobuf_Timestamp(seconds: -1) - Google_Protobuf_Timestamp(nanos: -2000000001)
XCTAssertEqual(r5.seconds, 1)
XCTAssertEqual(r5.nanos, 1)
let r6: Google_Protobuf_Duration = Google_Protobuf_Timestamp(seconds: -10) - Google_Protobuf_Timestamp(nanos: -2000000001)
XCTAssertEqual(r6.seconds, -7)
XCTAssertEqual(r6.nanos, -999999999)
let r7: Google_Protobuf_Duration = Google_Protobuf_Timestamp(seconds: 10) - Google_Protobuf_Timestamp(nanos: 2000000001)
XCTAssertEqual(r7.seconds, 7)
XCTAssertEqual(r7.nanos, 999999999)
}
// TODO: Should setter correct for out-of-range
// nanos and other minor inconsistencies?
func testInitializationByTimestamps() throws {
// Negative timestamp
let t1 = Google_Protobuf_Timestamp(timeIntervalSince1970: -123.456)
XCTAssertEqual(t1.seconds, -124)
XCTAssertEqual(t1.nanos, 544000000)
// Full precision
let t2 = Google_Protobuf_Timestamp(timeIntervalSince1970: -123.999999999)
XCTAssertEqual(t2.seconds, -124)
XCTAssertEqual(t2.nanos, 1)
// Round up
let t3 = Google_Protobuf_Timestamp(timeIntervalSince1970: -123.9999999994)
XCTAssertEqual(t3.seconds, -124)
XCTAssertEqual(t3.nanos, 1)
// Round down
let t4 = Google_Protobuf_Timestamp(timeIntervalSince1970: -123.9999999996)
XCTAssertEqual(t4.seconds, -124)
XCTAssertEqual(t4.nanos, 0)
let t5 = Google_Protobuf_Timestamp(timeIntervalSince1970: 0)
XCTAssertEqual(t5.seconds, 0)
XCTAssertEqual(t5.nanos, 0)
// Positive timestamp
let t6 = Google_Protobuf_Timestamp(timeIntervalSince1970: 123.456)
XCTAssertEqual(t6.seconds, 123)
XCTAssertEqual(t6.nanos, 456000000)
// Full precision
let t7 = Google_Protobuf_Timestamp(timeIntervalSince1970: 123.999999999)
XCTAssertEqual(t7.seconds, 123)
XCTAssertEqual(t7.nanos, 999999999)
// Round down
let t8 = Google_Protobuf_Timestamp(timeIntervalSince1970: 123.9999999994)
XCTAssertEqual(t8.seconds, 123)
XCTAssertEqual(t8.nanos, 999999999)
// Round up
let t9 = Google_Protobuf_Timestamp(timeIntervalSince1970: 123.9999999996)
XCTAssertEqual(t9.seconds, 124)
XCTAssertEqual(t9.nanos, 0)
}
func testInitializationByReferenceTimestamp() throws {
let t1 = Google_Protobuf_Timestamp(timeIntervalSinceReferenceDate: 123.456)
XCTAssertEqual(t1.seconds, 978307323)
XCTAssertEqual(t1.nanos, 456000000)
}
func testInitializationByDates() throws {
let t1 = Google_Protobuf_Timestamp(date: Date(timeIntervalSinceReferenceDate: 123.456))
XCTAssertEqual(t1.seconds, 978307323)
XCTAssertEqual(t1.nanos, 456000000)
}
func testTimestampGetters() throws {
let t1 = Google_Protobuf_Timestamp(seconds: 12345678, nanos: 12345678)
XCTAssertEqual(t1.seconds, 12345678)
XCTAssertEqual(t1.nanos, 12345678)
XCTAssertEqual(t1.timeIntervalSince1970, 12345678.012345678)
XCTAssertEqual(t1.timeIntervalSinceReferenceDate, -965961521.987654322)
let d = t1.date
XCTAssertEqual(d.timeIntervalSinceReferenceDate, -965961521.987654322)
}
}
|
apache-2.0
|
688016260f522ed9e041a69e9328d968
| 40.317352 | 146 | 0.611096 | 4.355475 | false | true | false | false |
Esri/arcgis-runtime-samples-ios
|
arcgis-ios-sdk-samples/Scenes/Choose camera controller/ChooseCameraControllerViewController.swift
|
1
|
5650
|
// Copyright 2019 Esri.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import UIKit
import ArcGIS
class ChooseCameraControllerViewController: UIViewController {
@IBOutlet private var sceneView: AGSSceneView! {
didSet {
sceneView.scene = makeScene()
let point = AGSPoint(x: -109.937516, y: 38.456714, spatialReference: .wgs84())
let camera = AGSCamera(lookAt: point, distance: 5500, heading: 150, pitch: 20, roll: 0)
sceneView.setViewpointCamera(camera)
}
}
@IBOutlet var cameraControllersBarButtonItem: UIBarButtonItem!
lazy var planeSymbol: AGSModelSceneSymbol = { [unowned self] in
let planeSymbol = AGSModelSceneSymbol(name: "Bristol", extension: "dae", scale: 100.0)
planeSymbol.load { _ in
DispatchQueue.main.async {
self.planeSymbolDidLoad()
}
}
return planeSymbol
}()
lazy var planeGraphic: AGSGraphic = {
let planePosition = AGSPoint(x: -109.937516, y: 38.456714, z: 5000, spatialReference: .wgs84())
let planeGraphic = AGSGraphic(geometry: planePosition, symbol: planeSymbol, attributes: nil)
return planeGraphic
}()
override func viewDidLoad() {
super.viewDidLoad()
(self.navigationItem.rightBarButtonItem as! SourceCodeBarButtonItem).filenames = ["ChooseCameraControllerViewController"]
// Add graphics overlay to the scene view.
sceneView.graphicsOverlays.add(makeGraphicsOverlay())
}
/// Called when the plane model scene symbol loads successfully or fails to load.
func planeSymbolDidLoad() {
if let error = planeSymbol.loadError {
presentAlert(error: error)
} else {
planeSymbol.heading = 45
cameraControllersBarButtonItem.isEnabled = true
}
}
/// Returns a scene with imagery basemap style and elevation data.
func makeScene() -> AGSScene {
let scene = AGSScene(basemapStyle: .arcGISImagery)
// Add base surface to the scene for elevation data.
let surface = AGSSurface()
let worldElevationServiceURL = URL(string: "https://elevation3d.arcgis.com/arcgis/rest/services/WorldElevation3D/Terrain3D/ImageServer")!
let elevationSource = AGSArcGISTiledElevationSource(url: worldElevationServiceURL)
surface.elevationSources.append(elevationSource)
scene.baseSurface = surface
return scene
}
/// Returns a graphics overlay containing the plane graphic.
func makeGraphicsOverlay() -> AGSGraphicsOverlay {
let graphicsOverlay = AGSGraphicsOverlay()
graphicsOverlay.sceneProperties?.surfacePlacement = .absolute
graphicsOverlay.graphics.add(planeGraphic)
return graphicsOverlay
}
/// Returns a controller that allows a scene view's camera to orbit the Upheaval Dome crater structure.
func makeOrbitLocationCameraController() -> AGSOrbitLocationCameraController {
let targetLocation = AGSPoint(x: -109.929589, y: 38.437304, z: 1700, spatialReference: .wgs84())
let cameraController = AGSOrbitLocationCameraController(targetLocation: targetLocation, distance: 5000)
cameraController.cameraPitchOffset = 3
cameraController.cameraHeadingOffset = 150
return cameraController
}
/// Returns a controller that allows a scene view's camera to orbit the plane.
func makeOrbitGeoElementCameraController() -> AGSOrbitGeoElementCameraController {
let cameraController = AGSOrbitGeoElementCameraController(targetGeoElement: planeGraphic, distance: 5000)
cameraController.cameraPitchOffset = 30
cameraController.cameraHeadingOffset = 150
return cameraController
}
// MARK: - Navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "CameraControllersPopover" {
guard let controller = segue.destination as? CameraControllerTableViewController else { return }
controller.delegate = self
controller.cameraControllers = [makeOrbitLocationCameraController(), makeOrbitGeoElementCameraController(), AGSGlobeCameraController()]
controller.selectedCameraController = sceneView.cameraController
// Popover presentation logic.
controller.presentationController?.delegate = self
controller.preferredContentSize = CGSize(width: 300, height: 130)
}
}
}
extension ChooseCameraControllerViewController: UIAdaptivePresentationControllerDelegate {
func adaptivePresentationStyle(for controller: UIPresentationController, traitCollection: UITraitCollection) -> UIModalPresentationStyle {
// For popover or non modal presentation.
return .none
}
}
extension ChooseCameraControllerViewController: CameraControllerTableViewControllerDelagate {
func selectedCameraControllerChanged(_ tableViewController: CameraControllerTableViewController) {
sceneView.cameraController = tableViewController.selectedCameraController
}
}
|
apache-2.0
|
524cc1b23d344827c6f0d06bc64b9927
| 41.80303 | 147 | 0.710265 | 5.113122 | false | false | false | false |
Detailscool/YHFanfou
|
YHFanfou/Pods/OAuthSwift/OAuthSwift/OAuthSwiftMultipartData.swift
|
7
|
1508
|
//
// OAuthSwiftMultipartData.swift
// OAuthSwift
//
// Created by Tomohiro Kawaji on 12/18/15.
// Copyright (c) 2015 Dongri Jin. All rights reserved.
//
import Foundation
public struct OAuthSwiftMultipartData {
public var name: String
public var data: NSData
public var fileName: String?
public var mimeType: String?
public init(name: String, data: NSData, fileName: String?, mimeType: String?) {
self.name = name
self.data = data
self.fileName = fileName
self.mimeType = mimeType
}
}
extension NSMutableData {
public func appendMultipartData(multipartData: OAuthSwiftMultipartData, encoding: NSStringEncoding, separatorData: NSData) {
var filenameClause = ""
if let filename = multipartData.fileName {
filenameClause = " filename=\"\(filename)\""
}
let contentDispositionString = "Content-Disposition: form-data; name=\"\(multipartData.name)\";\(filenameClause)r\n"
let contentDispositionData = contentDispositionString.dataUsingEncoding(encoding)!
self.appendData(contentDispositionData)
if let mimeType = multipartData.mimeType {
let contentTypeString = "Content-Type: \(mimeType)\r\n"
let contentTypeData = contentTypeString.dataUsingEncoding(encoding)!
self.appendData(contentTypeData)
}
self.appendData(separatorData)
self.appendData(multipartData.data)
self.appendData(separatorData)
}
}
|
mit
|
01277b02461b6446f91ff55e6e25dfdf
| 30.4375 | 128 | 0.680371 | 4.787302 | false | false | false | false |
oleander/bitbar
|
Sources/BitBar/Tray.swift
|
1
|
4446
|
import AppKit
import Cocoa
import BonMot
import Hue
import Parser
import Plugin
import OcticonsSwift
import SwiftyBeaver
class Tray: GUI, Trayable {
convenience required init(title: String, isVisible: Bool) {
self.init(title: title, isVisible: isVisible, id: "-")
}
internal let queue = Tray.newQueue(label: "Tray")
public let log = SwiftyBeaver.self
private var item: MenuBar?
init(title: String, isVisible displayed: Bool = false, id: String) {
// TODO: Remove
if App.isInTestMode() {
item = TestBar()
} else {
perform { [weak self] in
self?.item = NSStatusBar.system().statusItem(withLength: NSVariableStatusItemLength)
self?.item?.attributedTitle = self?.style(title)
self?.item?.tag = id
self?.menu = Title(prefs: [])
if displayed { self?.item?.show() } else { self?.item?.hide() }
}
}
}
public func has(child: Childable) -> Bool {
return item?.menu?.has(child: child) ?? false
}
public var attributedTitle: NSAttributedString? {
get { return item?.attributedTitle }
set {
perform { [weak self] in
self?.log.info("Tray title: \(newValue?.string.inspected() ?? "NO")")
self?.item?.attributedTitle = newValue
}
}
}
public var menu: NSMenu? {
get { return item?.menu }
set {
perform { [weak self] in
self?.item?.menu = newValue
}
}
}
/**
Hides item from menu bar
*/
public func hide() {
log.info("Hide tray")
perform { [weak self] in
self?.item?.hide()
}
}
/**
Display item in menu bar
*/
public func show() {
log.info("Show tray")
perform { [weak self] in
self?.item?.show()
}
}
public func set(error: Bool) {
if error {
showErrorIcons()
attributedTitle = nil
} else { hideErrorIcons() }
}
public func set(errors: [MenuError]) {
set(errors: errors.map(String.init(describing:)))
}
public func set(title: Immutable) {
hideErrorIcons()
attributedTitle = style(title)
}
public func set(title: String) {
set(title: title.immutable)
}
private func showErrorIcons() {
perform { [weak self] in
guard let this = self else { return }
let fontSize = Int(FontType.bar.size)
let size = CGSize(width: fontSize, height: fontSize)
let icon = OcticonsID.bug
this.image = NSImage(
octiconsID: icon,
iconColor: NSColor(hex: "#474747"),
size: size
)
this.alternateImage = NSImage(
octiconsID: icon,
backgroundColor: .white,
iconColor: .white,
iconScale: 1.0,
size: size
)
this.attributedTitle = nil
}
}
private func hideErrorIcons() {
image = nil
alternateImage = nil
}
func set(menus: [NSMenuItem]) {
guard let menu = menu else { return }
guard let aMenu = menu as? Title else { return }
aMenu.set(menus: menus)
}
func set(errors: [String]) {
showErrorIcons()
set(menus: errors.map { MenuItem(error: $0) })
}
func set(title: Text) {
attributedTitle = title.colorize(as: .bar)
}
func set(error: String) {
set(errors: [error])
}
func set(_ tails: [Parser.Menu.Tail]) {
set(menus: tails.map { $0.menuItem })
}
private var image: NSImage? {
set {
perform { [weak self] in
self?.button?.image = newValue
}
}
get { return button?.image }
}
private var isHighlightMode: Bool {
set {
perform { [weak self] in
self?.button?.highlight(newValue)
}
}
get { return false }
}
private var alternateImage: NSImage? {
set {
perform { [weak self] in
self?.button?.alternateImage = newValue
}
}
get { return button?.alternateImage }
}
private var button: NSButton? {
if let button = item?.button {
return button
}
return nil
}
private var tag: String? {
get { return item?.tag }
set {
perform { [weak self] in
self?.item?.tag = newValue
}
}
}
private func style(_ immutable: Immutable) -> Immutable {
return immutable.styled(with: .font(FontType.bar.font))
}
private func style(_ string: String) -> Immutable {
return string.styled(with: .font(FontType.bar.font))
}
deinit {
if let bar = item as? NSStatusItem {
NSStatusBar.system().removeStatusItem(bar)
}
}
}
|
mit
|
66e86d6fe98a564f4eaa18f2d1101d58
| 20.171429 | 92 | 0.594017 | 3.889764 | false | false | false | false |
ProfileCreator/ProfileCreator
|
ProfileCreator/ProfileCreator/Profile Settings/ProfileSettingsViewValues.swift
|
1
|
7642
|
//
// ProfileSettingsViewValues.swift
// ProfileCreator
//
// Created by Erik Berglund.
// Copyright © 2018 Erik Berglund. All rights reserved.
//
import Foundation
import ProfilePayloads
extension ProfileSettings {
// MARK: -
// MARK: Get
func viewValue(forSubkey subkey: PayloadSubkey, payloadIndex: Int) -> Any? {
self.viewValue(forKeyPath: subkey.keyPath, domainIdentifier: subkey.domainIdentifier, payloadType: subkey.payloadType, payloadIndex: payloadIndex)
}
func viewValue(forKeyPath keyPath: String, domainIdentifier: String, payloadType type: PayloadType, payloadIndex: Int) -> Any? {
guard let viewDomainSettings = self.viewSettings(forDomainIdentifier: domainIdentifier, payloadType: type, payloadIndex: payloadIndex) else { return nil }
return viewDomainSettings[keyPath: KeyPath(keyPath)]
}
func viewValue(forKey key: String, subkey: PayloadSubkey, payloadIndex: Int) -> Any? {
self.viewValue(forKey: key, keyPath: subkey.keyPath, domainIdentifier: subkey.domainIdentifier, payloadType: subkey.payloadType, payloadIndex: payloadIndex)
}
func viewValue(forKey key: String, keyPath: String, domainIdentifier: String, payloadType type: PayloadType, payloadIndex: Int) -> Any? {
guard let viewKeySettings = self.viewSettings(forKeyPath: keyPath, domainIdentifier: domainIdentifier, payloadType: type, payloadIndex: payloadIndex) else { return nil }
return viewKeySettings[key]
}
// MARK: -
// MARK: Set
func setViewValue(_ value: Any, forSubkey subkey: PayloadSubkey, payloadIndex: Int) {
self.setViewValue(value, forKeyPath: subkey.keyPath, domainIdentifier: subkey.domainIdentifier, payloadType: subkey.payloadType, payloadIndex: payloadIndex)
}
func setViewValue(_ value: Any, forKeyPath keyPath: String, domainIdentifier: String, payloadType type: PayloadType, payloadIndex: Int) {
var viewDomainSettings = self.viewSettings(forDomainIdentifier: domainIdentifier, payloadType: type, payloadIndex: payloadIndex) ?? [String: Any]()
viewDomainSettings[keyPath] = value
self.setViewSettings(viewDomainSettings, forDomainIdentifier: domainIdentifier, payloadType: type, payloadIndex: payloadIndex)
}
func setViewValue(_ value: Any, forKey key: String, subkey: PayloadSubkey, payloadIndex: Int) {
self.setViewValue(value, forKey: key, keyPath: subkey.keyPath, domainIdentifier: subkey.domainIdentifier, payloadType: subkey.payloadType, payloadIndex: payloadIndex)
}
func setViewValue(_ value: Any, forKey key: String, keyPath: String, domainIdentifier: String, payloadType type: PayloadType, payloadIndex: Int) {
var viewKeySettings = self.viewSettings(forKeyPath: keyPath, domainIdentifier: domainIdentifier, payloadType: type, payloadIndex: payloadIndex) ?? [String: Any]()
viewKeySettings[key] = value
self.setViewSettings(viewKeySettings, forKeyPath: keyPath, domainIdentifier: domainIdentifier, payloadType: type, payloadIndex: payloadIndex)
}
// MARK: -
// MARK: Enabled
// swiftlint:disable:next discouraged_optional_boolean
func viewValueEnabled(forSubkey subkey: PayloadSubkey, payloadIndex: Int) -> Bool? {
self.viewValueEnabled(forKeyPath: subkey.keyPath, domainIdentifier: subkey.domainIdentifier, payloadType: subkey.payloadType, payloadIndex: payloadIndex)
}
// swiftlint:disable:next discouraged_optional_boolean
func viewValueEnabled(forKeyPath keyPath: String, domainIdentifier: String, payloadType: PayloadType, payloadIndex: Int) -> Bool? {
self.viewValue(forKey: SettingsKey.enabled, keyPath: keyPath, domainIdentifier: domainIdentifier, payloadType: payloadType, payloadIndex: payloadIndex) as? Bool
}
func setViewValue(enabled: Bool, forSubkey subkey: PayloadSubkey, payloadIndex: Int) {
self.setViewValue(enabled: enabled, forKeyPath: subkey.keyPath, domainIdentifier: subkey.domainIdentifier, payloadType: subkey.payloadType, payloadIndex: payloadIndex)
}
func setViewValue(enabled: Bool, forKeyPath keyPath: String, domainIdentifier: String, payloadType: PayloadType, payloadIndex: Int) {
self.setViewValue(enabled, forKey: SettingsKey.enabled, keyPath: keyPath, domainIdentifier: domainIdentifier, payloadType: payloadType, payloadIndex: payloadIndex)
}
// MARK: -
// MARK: Hash
func viewValueHash(forDomainIdentifier domainIdentifier: String, payloadType: PayloadType, payloadIndex: Int) -> Int? {
self.viewValue(forKeyPath: SettingsKey.hash, domainIdentifier: domainIdentifier, payloadType: payloadType, payloadIndex: payloadIndex) as? Int
}
func setViewValue(hash: Int, forDomainIdentifier domainIdentifier: String, payloadType: PayloadType, payloadIndex: Int) {
self.setViewValue(hash, forKeyPath: SettingsKey.hash, domainIdentifier: domainIdentifier, payloadType: payloadType, payloadIndex: payloadIndex)
}
// MARK: -
// MARK: PayloadIndex
/*
func getPayloadIndex(domain: String, type: PayloadType) -> Int {
let viewDomainSettings = self.getViewDomainSettings(domain: domain, type: type)
if let payloadIndex = viewDomainSettings[SettingsKey.payloadIndex] as? Int {
return payloadIndex
} else { return 0 }
}
func setPayloadIndex(index: Int, domain: String, type: PayloadType) {
#if DEBUGSETTINGS
Log.shared.debug(message: "Setting payload index: \(index) for domain: \(domain) of type: \(type)", category: String(describing: self))
#endif
var viewDomainSettings = self.getViewDomainSettings(domain: domain, type: type)
viewDomainSettings[SettingsKey.payloadIndex] = index
self.setViewDomainSettings(settings: viewDomainSettings, domain: domain, type: type)
}
*/
func viewValuePayloadIndex(forDomainIdentifier domainIdentifier: String, payloadType type: PayloadType) -> Int {
guard
let viewDomainSettings = self.viewSettings(forDomainIdentifier: domainIdentifier, payloadType: type),
let index = viewDomainSettings.firstIndex(where: { $0[SettingsKey.payloadIndexSelected] as? Bool == true }) else {
return 0
}
return index < 0 ? 0 : index
}
func setViewValue(payloadIndex: Int, forDomainIdentifier domainIdentifier: String, payloadType type: PayloadType) {
let viewDomainSettings = self.viewSettings(forDomainIdentifier: domainIdentifier, payloadType: type) ?? [[String: Any]]()
var newDomainSettings = [[String: Any]]()
if viewDomainSettings.isEmpty {
for index in 0...payloadIndex {
if index == payloadIndex {
newDomainSettings.append([SettingsKey.payloadIndexSelected: true])
} else {
newDomainSettings.append([String: Any]())
}
}
} else {
for (index, var domainSettings) in viewDomainSettings.enumerated() {
if index == payloadIndex {
domainSettings[SettingsKey.payloadIndexSelected] = true
} else {
domainSettings.removeValue(forKey: SettingsKey.payloadIndexSelected)
}
newDomainSettings.append(domainSettings)
}
if viewDomainSettings.count == payloadIndex {
newDomainSettings.append([SettingsKey.payloadIndexSelected: true])
}
}
self.setViewSettings(newDomainSettings, forDomainIdentifier: domainIdentifier, payloadType: type)
}
}
|
mit
|
6ffe8a3088a2ca8fa1d9f3b61be59c31
| 49.602649 | 177 | 0.711556 | 4.523979 | false | false | false | false |
nghiaphunguyen/NKit
|
NKit/Demo/ThreeViewController.swift
|
1
|
5250
|
//
// ThreeViewController.swift
// NKit
//
// Created by Nghia Nguyen on 9/26/16.
// Copyright © 2016 Nghia Nguyen. All rights reserved.
//
import UIKit
class ThreeViewController: UIViewController {
enum ViewIdentifier: String, NKViewIdentifier {
case StackView
case FirstLabel
case SecondLabel
case ThirdLabel
case Button
}
@available(iOS 9.0, *)
var stackView: UIStackView {return ViewIdentifier.StackView.view(self) }
var firstLabel: UILabel {return ViewIdentifier.FirstLabel.view(self) }
var secondLabel: UILabel {return ViewIdentifier.SecondLabel.view(self) }
var thirdLabel: UILabel {return ViewIdentifier.ThirdLabel.view(self) }
var button: UIButton {return ViewIdentifier.Button.view(self) }
override func viewDidLoad() {
super.viewDidLoad()
self.button.rx.tap.bindNext {
//print("ok")
}.addDisposableTo(self.nk_disposeBag)
}
}
//MARK: Layout
extension ThreeViewController {
override func loadView() {
super.loadView()
self.view
.nk_config() {
$0.backgroundColor = UIColor.black
}
.nk_addSubview(UIView()) {
$0.nk_id = ""
$0
.nk_addSubview(UIView()) {
$0
.nk_addSubview(UIView()) {
$0.nk_id = ""
}
.nk_addSubview(UIView()) {
$0.nk_id = ""
}
}
.nk_addSubview(UIView()) {
$0
.nk_addSubview(UIView()) {
$0.nk_id = ""
}
}
}
.nk_addSubview(UIView()) {
$0.nk_id = ""
}.nk_mapIds()
// self.view > UIView() * {
// $0.nk_id = nil
// } > UIView() * {
// $0.nk_id = nil
// }
// self.view.nk_config {
// $0.backgroundColor = UIColor.yellowColor()
// }.add_subviews()UIStackView.nk_column().nk_id(ViewIdentifier.StackView) >>> {
// $0.distribution = .Fill
// $0.alignment = .Fill
//
// $0.snp.makeConstraints(closure: { (make) in
// make.top.equalToSuperview().inset(20)
// make.leading.trailing.bottom.equalToSuperview().inset(10)
// })
//
// $0
// <<< UILabel(text: 30.nk_dummyString, isSizeToFit: true, alignment: .Left).nk_id(ViewIdentifier.FirstLabel) >>> {
// $0.nka_height == $0.nka_width / 4
//
// $0.numberOfLines = 0
// $0.backgroundColor = UIColor.blueColor()
// }
//
// <<< UILabel(text: 200.nk_dummyString, isSizeToFit: true, alignment: .Left).nk_id(ViewIdentifier.SecondLabel) >>> {
// $0.nka_weight = 0.1
// $0.numberOfLines = 0
// $0.backgroundColor = UIColor.greenColor()
//
// }
//
// <<< (UILabel(text: 2000.nk_dummyString, isSizeToFit: true, alignment: .Left).nk_id(ViewIdentifier.ThirdLabel) >>> {
// $0.nka_weight = 0.55
// $0.numberOfLines = 0
// $0.backgroundColor = UIColor.redColor()
// }
//
// <<< (UIButton().nk_id(ViewIdentifier.Button)) >>> {
// $0.nka_weight = 0.1
// $0.setTitle("Ok nhe", forState: .Normal)
// $0.setBackgroundImage(UIImage.nk_fromColor(UIColor.blueColor()), forState: .Normal)
//
// }
// <<< (UIView()) >>> {
// $0.backgroundColor = UIColor.brownColor()
//
// $0.nk_addSubview(UIView().nk_id("TestHangHo")) { view in
// view.backgroundColor = UIColor.grayColor()
//
// view.snp.makeConstraints(closure: { (make) in
// make.top.leading.bottom.equalToSuperview()
// make.width.equalTo(view.superview!).dividedBy(4)
// })
// }.nk_addSubview(UIView()) { (view) in
// view.backgroundColor = UIColor.lightGrayColor()
// view.snp.makeConstraints(closure: { (make) in
// make.top.trailing.bottom.equalTo(view.superview!)
// make.leading.equalTo(view.superview!.nk_findViewById("TestHangHo").snp.trailing)
// })
//
// }
// }
}
}
|
mit
|
a34e5c4663994bb446de86e9b8312672
| 35.964789 | 137 | 0.422938 | 4.628748 | false | false | false | false |
emadhegab/GenericDataSource
|
Sources/DataSourceSelector.swift
|
1
|
8010
|
//
// DataSourceSelector.swift
// GenericDataSource
//
// Created by Mohamed Ebrahim Mohamed Afifi on 3/30/17.
// Copyright © 2017 mohamede1945. All rights reserved.
//
import Foundation
/// Represents the data source selectors that can be optional.
/// Each case corresponds to a selector in the DataSource.
@objc public enum DataSourceSelector: Int {
/// Represents the size selector.
case size
/*case shouldHighlight
case didHighlight
case didUnhighlight
case shouldSelect
case didSelect
case shouldDeselect
case didDeselect
case supplementaryViewOfKind
case sizeForSupplementaryViewOfKind
case willDisplaySupplementaryView
case didEndDisplayingSupplementaryView
case canMove
case move
case willDisplayCell
case didEndDisplayingCell*/
/// Represents the can edit selector.
case canEdit
/// Represents the commit editing selector.
case commitEditingStyle
/// Represents the editing style selector.
case editingStyle
/// Represents the title for delete confirmation button selector.
case titleForDeleteConfirmationButton
/// Represents the edit actions selector.
case editActions
/// Represents the should indent while editing selector.
case shouldIndentWhileEditing
/// Represents the will begin selector.
case willBeginEditing
/// Represents the did end editing selector.
case didEndEditing
/// Represents the should show menu for item selector.
case shouldShowMenuForItemAt
/// Represents the can perform action selector.
case canPerformAction
/// Represents the perform action selector.
case performAction
/// Represents the can focus item at index selector.
case canFocusItemAt
/// Represents the should update focus in selector.
case shouldUpdateFocusIn
/// Represents the did update focus in selector.
case didUpdateFocusIn
/// Represents the index path for preferred focused in view selector.
case indexPathForPreferredFocusedView
}
extension DataSourceSelector {
/// Whether or not the selector requires all data sources to respond to it.
/// Current implementation only `.size` requires all selectors and may change in the future.
/// It's always recommended if you want to implement a selector in your `BasicDataSource` subclass.
/// To do it in all classes that will be children of a `CompositeDataSource` or `SegmentedDataSource`.
public var mustAllRespondsToIt: Bool {
switch self {
case .size: return true
case .canEdit: return false
case .commitEditingStyle: return false
case .editingStyle: return false
case .titleForDeleteConfirmationButton: return false
case .editActions: return false
case .shouldIndentWhileEditing: return false
case .willBeginEditing: return false
case .didEndEditing: return false
case .shouldShowMenuForItemAt: return false
case .canPerformAction: return false
case .performAction: return false
case .canFocusItemAt: return false
case .shouldUpdateFocusIn: return false
case .didUpdateFocusIn: return false
case .indexPathForPreferredFocusedView: return false
}
}
}
let dataSourceSelectorToSelectorMapping: [DataSourceSelector: [Selector]] = {
var mapping: [DataSourceSelector: [Selector]] =
[.size: [
#selector(UITableViewDelegate.tableView(_:heightForRowAt:)),
#selector(UICollectionViewDelegateFlowLayout.collectionView(_:layout:sizeForItemAt:)),
#selector(DataSource.ds_collectionView(_:sizeForItemAt:))
],
.canEdit: [
#selector(UITableViewDataSource.tableView(_:canEditRowAt:)),
#selector(DataSource.ds_collectionView(_:canEditItemAt:))
],
.commitEditingStyle: [
#selector(UITableViewDataSource.tableView(_:commit:forRowAt:)),
#selector(DataSource.ds_collectionView(_:commit:forItemAt:))
],
.editingStyle: [
#selector(UITableViewDelegate.tableView(_:editingStyleForRowAt:)),
#selector(DataSource.ds_collectionView(_:editingStyleForItemAt:))
],
.titleForDeleteConfirmationButton: [
#selector(UITableViewDelegate.tableView(_:titleForDeleteConfirmationButtonForRowAt:)),
#selector(DataSource.ds_collectionView(_:titleForDeleteConfirmationButtonForItemAt:))
],
.editActions: [
#selector(UITableViewDelegate.tableView(_:editActionsForRowAt:)),
#selector(DataSource.ds_collectionView(_:editActionsForItemAt:))
],
.shouldIndentWhileEditing: [
#selector(UITableViewDelegate.tableView(_:shouldIndentWhileEditingRowAt:)),
#selector(DataSource.ds_collectionView(_:shouldIndentWhileEditingItemAt:))
],
.willBeginEditing: [
#selector(UITableViewDelegate.tableView(_:willBeginEditingRowAt:)),
#selector(DataSource.ds_collectionView(_:willBeginEditingItemAt:))
],
.didEndEditing: [
#selector(UITableViewDelegate.tableView(_:didEndEditingRowAt:)),
#selector(DataSource.ds_collectionView(_:didEndEditingItemAt:))
],
.shouldShowMenuForItemAt: [
#selector(UITableViewDelegate.tableView(_:shouldShowMenuForRowAt:)),
#selector(UICollectionViewDelegateFlowLayout.collectionView(_:shouldShowMenuForItemAt:)),
#selector(DataSource.ds_collectionView(_:shouldShowMenuForItemAt:))
],
.canPerformAction: [
#selector(UITableViewDelegate.tableView(_:canPerformAction:forRowAt:withSender:)),
#selector(UICollectionViewDelegateFlowLayout.collectionView(_:canPerformAction:forItemAt:withSender:)),
#selector(DataSource.ds_collectionView(_:canPerformAction:forItemAt:withSender:))
],
.performAction: [
#selector(UITableViewDelegate.tableView(_:performAction:forRowAt:withSender:)),
#selector(UICollectionViewDelegateFlowLayout.collectionView(_:performAction:forItemAt:withSender:)),
#selector(DataSource.ds_collectionView(_:performAction:forItemAt:withSender:))
]]
if #available(iOS 9.0, *) {
mapping[.canFocusItemAt] = [
#selector(UITableViewDelegate.tableView(_:canFocusRowAt:)),
#selector(UICollectionViewDelegateFlowLayout.collectionView(_:canFocusItemAt:)),
#selector(DataSource.ds_collectionView(_:canFocusItemAt:))
]
mapping[.shouldUpdateFocusIn] = [
#selector(UITableViewDelegate.tableView(_:shouldUpdateFocusIn:)),
#selector(UICollectionViewDelegateFlowLayout.collectionView(_:shouldUpdateFocusIn:)),
#selector(DataSource.ds_collectionView(_:shouldUpdateFocusIn:))
]
mapping[.didUpdateFocusIn] = [
#selector(UITableViewDelegate.tableView(_:didUpdateFocusIn:with:)),
#selector(UICollectionViewDelegateFlowLayout.collectionView(_:didUpdateFocusIn:with:)),
#selector(DataSource.ds_collectionView(_:didUpdateFocusIn:with:))
]
mapping[.indexPathForPreferredFocusedView] = [
#selector(UITableViewDelegate.indexPathForPreferredFocusedView(in:)),
#selector(UICollectionViewDelegateFlowLayout.indexPathForPreferredFocusedView(in:)),
#selector(DataSource.ds_indexPathForPreferredFocusedView(in:))
]
}
return mapping
}()
let selectorToDataSourceSelectorMapping: [Selector: DataSourceSelector] = {
var mapping: [Selector: DataSourceSelector] = [:]
for (key, value) in dataSourceSelectorToSelectorMapping {
for item in value {
precondition(mapping[item] == nil, "Use of selector \(item) multiple times")
mapping[item] = key
}
}
return mapping
}()
|
mit
|
f7e989a30812bf4377018ef653d79cd1
| 39.654822 | 115 | 0.687726 | 5.893304 | false | false | false | false |
shaps80/iMessageStyleReveal
|
Example/RevealableCell/ViewController+Revealable.swift
|
1
|
933
|
import UIKit
import RevealableCell
extension ViewController: UITableViewDelegateRevealable {
func tableView(_ tableView: UITableView, configurationForRevealableViewAt indexPath: IndexPath) -> RevealableViewConfiguration {
let message = messages[indexPath.item]
return RevealableViewConfiguration(type: TimestampView.self, style: message.style, dequeueSource: .nib) { view, indexPath in
view.date = message.date as Date
}
}
func tableView(_ tableView: UITableView, willDisplay revealableView: RevealableView, forRowAt indexPath: IndexPath) {
guard indexPath.item == 0 else { return }
print("will display revealable view")
}
func tableView(_ tableView: UITableView, didEndDisplaying revealableView: RevealableView, forRowAt indexPath: IndexPath) {
guard indexPath.item == 0 else { return }
print("did end displaying revealable view")
}
}
|
mit
|
6001b34254874c3e6df8efa57cb8a421
| 39.565217 | 132 | 0.723473 | 5.126374 | false | true | false | false |
chrishulbert/gondola-ios
|
gondola-ios/ViewControllers/MovieViewController.swift
|
1
|
5312
|
//
// MovieViewController.swift
// Gondola TVOS
//
// Created by Chris on 15/02/2017.
// Copyright © 2017 Chris Hulbert. All rights reserved.
//
// This shows the details of a movie and lets you play it.
import UIKit
class MovieViewController: UIViewController {
let movie: MovieMetadata
let image: UIImage?
init(movie: MovieMetadata, image: UIImage?) {
self.movie = movie
self.image = image
super.init(nibName: nil, bundle: nil)
title = movie.name
navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .play, target: self, action: #selector(tapPlay))
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
lazy var rootView = MovieView()
override func loadView() {
view = rootView
}
override func viewDidLoad() {
super.viewDidLoad()
rootView.overview.text = movie.overview
rootView.image.image = image
rootView.details.text = "Release date: \(movie.releaseDate)\nVote: \(movie.vote)"
rootView.background.alpha = 0
ServiceHelpers.imageRequest(path: movie.backdrop) { result in
DispatchQueue.main.async {
switch result {
case .success(let image):
self.rootView.background.image = image
UIView.animate(withDuration: 0.3) {
self.rootView.background.alpha = 1
}
case .failure(let error):
NSLog("error: \(error)")
}
}
}
}
override var preferredStatusBarStyle: UIStatusBarStyle {
return .lightContent
}
override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
return .portrait
}
@objc func tapPlay() {
pushPlayer(media: movie.media)
}
}
class MovieView: UIView {
let background = UIImageView()
let dim = UIView()
let overview = UILabel()
let image = UIImageView()
let details = UILabel()
init() {
super.init(frame: CGRect.zero)
backgroundColor = UIColor.black
background.contentMode = .scaleAspectFill
background.clipsToBounds = true
background.translatesAutoresizingMaskIntoConstraints = false
addSubview(background)
background.leadingAnchor.constraint(equalTo: leadingAnchor).isActive = true
background.trailingAnchor.constraint(equalTo: trailingAnchor).isActive = true
background.topAnchor.constraint(equalTo: topAnchor).isActive = true
background.bottomAnchor.constraint(equalTo: bottomAnchor).isActive = true
dim.backgroundColor = UIColor(white: 0, alpha: 0.6)
dim.translatesAutoresizingMaskIntoConstraints = false
addSubview(dim)
dim.leadingAnchor.constraint(equalTo: leadingAnchor).isActive = true
dim.trailingAnchor.constraint(equalTo: trailingAnchor).isActive = true
dim.topAnchor.constraint(equalTo: topAnchor).isActive = true
dim.bottomAnchor.constraint(equalTo: bottomAnchor).isActive = true
image.contentMode = .scaleAspectFit
image.translatesAutoresizingMaskIntoConstraints = false
addSubview(image)
image.leadingAnchor.constraint(equalTo: safeAreaLayoutGuide.leadingAnchor, constant: LayoutHelpers.sideMargins).isActive = true
image.topAnchor.constraint(equalTo: safeAreaLayoutGuide.topAnchor, constant: LayoutHelpers.vertMargins).isActive = true
image.widthAnchor.constraint(equalTo: widthAnchor, multiplier: 0.25, constant: 0).isActive = true
image.heightAnchor.constraint(equalTo: image.widthAnchor, multiplier: 16/9, constant: 0).isActive = true
image.heightAnchor.constraint(lessThanOrEqualTo: heightAnchor, multiplier: 0.5).isActive = true
details.textColor = UIColor(white: 1, alpha: 0.7)
details.numberOfLines = 0
details.font = UIFont.systemFont(ofSize: 11, weight: .light)
details.translatesAutoresizingMaskIntoConstraints = false
addSubview(details)
details.leadingAnchor.constraint(equalTo: image.leadingAnchor).isActive = true
details.trailingAnchor.constraint(equalTo: image.trailingAnchor).isActive = true
details.topAnchor.constraint(equalTo: image.bottomAnchor, constant: 10).isActive = true
overview.textColor = UIColor.white
overview.font = UIFont.systemFont(ofSize: 12, weight: .light)
overview.numberOfLines = 0
overview.translatesAutoresizingMaskIntoConstraints = false
addSubview(overview)
overview.leadingAnchor.constraint(equalTo: image.trailingAnchor, constant: LayoutHelpers.sideMargins).isActive = true
overview.trailingAnchor.constraint(equalTo: safeAreaLayoutGuide.trailingAnchor, constant: -LayoutHelpers.sideMargins).isActive = true
overview.topAnchor.constraint(equalTo: safeAreaLayoutGuide.topAnchor, constant: LayoutHelpers.vertMargins).isActive = true
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
|
mit
|
a0daa7fa19433b7aaa12c7409ceabe97
| 37.766423 | 141 | 0.6656 | 5.248024 | false | false | false | false |
hooman/swift
|
benchmark/single-source/Substring.swift
|
3
|
9578
|
//===--- Substring.swift --------------------------------------------------===//
//
// 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 TestsUtils
public let SubstringTest = [
BenchmarkInfo(name: "EqualStringSubstring", runFunction: run_EqualStringSubstring, tags: [.validation, .api, .String]),
BenchmarkInfo(name: "EqualSubstringString", runFunction: run_EqualSubstringString, tags: [.validation, .api, .String]),
BenchmarkInfo(name: "EqualSubstringSubstring", runFunction: run_EqualSubstringSubstring, tags: [.validation, .api, .String]),
BenchmarkInfo(name: "EqualSubstringSubstringGenericEquatable", runFunction: run_EqualSubstringSubstringGenericEquatable, tags: [.validation, .api, .String]),
BenchmarkInfo(name: "SubstringRemoveFirst1", runFunction: run_SubstringRemoveFirst1, tags: [.validation, .api, .String]),
BenchmarkInfo(name: "SubstringRemoveLast1", runFunction: run_SubstringRemoveLast1, tags: [.validation, .api, .String]),
BenchmarkInfo(name: "LessSubstringSubstring", runFunction: run_LessSubstringSubstring, tags: [.validation, .api, .String]),
BenchmarkInfo(name: "LessSubstringSubstringGenericComparable", runFunction: run_LessSubstringSubstringGenericComparable, tags: [.validation, .api, .String]),
BenchmarkInfo(name: "StringFromLongWholeSubstring", runFunction: run_StringFromLongWholeSubstring, tags: [.validation, .api, .String]),
BenchmarkInfo(name: "StringFromLongWholeSubstringGeneric", runFunction: run_StringFromLongWholeSubstringGeneric, tags: [.validation, .api, .String]),
BenchmarkInfo(name: "SubstringComparable", runFunction: run_SubstringComparable, tags: [.validation, .api, .String],
setUpFunction: { blackHole(_comparison) }),
BenchmarkInfo(name: "SubstringEqualString", runFunction: run_SubstringEqualString, tags: [.validation, .api, .String]),
BenchmarkInfo(name: "SubstringEquatable", runFunction: run_SubstringEquatable, tags: [.validation, .api, .String]),
BenchmarkInfo(name: "SubstringFromLongString", runFunction: run_SubstringFromLongString, tags: [.validation, .api, .String]),
BenchmarkInfo(name: "SubstringFromLongStringGeneric", runFunction: run_SubstringFromLongStringGeneric, tags: [.validation, .api, .String]),
BenchmarkInfo(name: "SubstringTrimmingASCIIWhitespace", runFunction: run_SubstringTrimmingASCIIWhitespace, tags: [.validation, .api, .String]),
]
// A string that doesn't fit in small string storage and doesn't fit in Latin-1
let longWide = "fὢasὢodὢijὢadὢolὢsjὢalὢsdὢjlὢasὢdfὢijὢliὢsdὢjøὢslὢdiὢalὢiὢ"
let (s1, ss1) = equivalentWithDistinctBuffers()
let (s2, ss2) = equivalentWithDistinctBuffers()
let quiteLong = String(repeating: "0", count: 10_000)[...]
@inline(never)
public func run_SubstringFromLongString(_ N: Int) {
var s = longWide
s += "!" // ensure the string has a real buffer
for _ in 1...N*500 {
blackHole(Substring(s))
}
}
func create<T : RangeReplaceableCollection, U : Collection>(
_: T.Type, from source: U
) where T.Element == U.Element {
blackHole(T(source))
}
@inline(never)
public func run_SubstringFromLongStringGeneric(_ N: Int) {
var s = longWide
s += "!" // ensure the string has a real buffer
for _ in 1...N*500 {
create(Substring.self, from: s)
}
}
@inline(never)
public func run_StringFromLongWholeSubstring(_ N: Int) {
var s0 = longWide
s0 += "!" // ensure the string has a real buffer
let s = Substring(s0)
for _ in 1...N*500 {
blackHole(String(s))
}
}
@inline(never)
public func run_StringFromLongWholeSubstringGeneric(_ N: Int) {
var s0 = longWide
s0 += "!" // ensure the string has a real buffer
let s = Substring(s0)
for _ in 1...N*500 {
create(String.self, from: s)
}
}
private func equivalentWithDistinctBuffers() -> (String, Substring) {
var s0 = longWide
withUnsafeMutablePointer(to: &s0) { blackHole($0) }
s0 += "!"
// These two should be equal but with distinct buffers, both refcounted.
let a = Substring(s0).dropFirst()
let b = String(a)
return (b, a)
}
@inline(never)
public func run_EqualStringSubstring(_ N: Int) {
let (a, b) = (s1, ss1)
for _ in 1...N*500 {
blackHole(a == b)
}
}
@inline(never)
public func run_EqualSubstringString(_ N: Int) {
let (a, b) = (s1, ss1)
for _ in 1...N*500 {
blackHole(b == a)
}
}
@inline(never)
public func run_EqualSubstringSubstring(_ N: Int) {
let (_, a) = (s1, ss1)
let (_, b) = (s2, ss2)
for _ in 1...N*500 {
blackHole(a == b)
}
}
@inline(never)
public func run_EqualSubstringSubstringGenericEquatable(_ N: Int) {
let (_, a) = (s1, ss1)
let (_, b) = (s2, ss2)
func check<T>(_ x: T, _ y: T) where T : Equatable {
blackHole(x == y)
}
for _ in 1...N*500 {
check(a, b)
}
}
@inline(never)
public func run_SubstringRemoveFirst1(_ N: Int) {
for _ in 1...N {
var s = quiteLong
s.removeFirst(1)
blackHole(s.first == "0")
}
}
@inline(never)
public func run_SubstringRemoveLast1(_ N: Int) {
for _ in 1...N {
var s = quiteLong
s.removeLast(1)
blackHole(s.first == "0")
}
}
/*
func checkEqual<T, U>(_ x: T, _ y: U)
where T : StringProtocol, U : StringProtocol {
blackHole(x == y)
}
@inline(never)
public func run _EqualStringSubstringGenericStringProtocol(_ N: Int) {
let (a, b) = (s1, ss1)
for _ in 1...N*500 {
checkEqual(a, b)
}
}
@inline(never)
public func run _EqualSubstringStringGenericStringProtocol(_ N: Int) {
let (a, b) = (s1, ss1)
for _ in 1...N*500 {
checkEqual(b, a)
}
}
@inline(never)
public func run _EqualSubstringSubstringGenericStringProtocol(_ N: Int) {
let (_, a) = (s1, ss1)
let (_, b) = (s2, ss2)
for _ in 1...N*500 {
checkEqual(a, b)
}
}
*/
//===----------------------------------------------------------------------===//
/*
@inline(never)
public func run _LessStringSubstring(_ N: Int) {
let (a, b) = (s1, ss1)
for _ in 1...N*500 {
blackHole(a < b)
}
}
@inline(never)
public func run _LessSubstringString(_ N: Int) {
let (a, b) = (s1, ss1)
for _ in 1...N*500 {
blackHole(b < a)
}
}
*/
@inline(never)
public func run_LessSubstringSubstring(_ N: Int) {
let (_, a) = (s1, ss1)
let (_, b) = (s2, ss2)
for _ in 1...N*500 {
blackHole(a < b)
}
}
@inline(never)
public func run_LessSubstringSubstringGenericComparable(_ N: Int) {
let (_, a) = (s1, ss1)
let (_, b) = (s2, ss2)
func check<T>(_ x: T, _ y: T) where T : Comparable {
blackHole(x < y)
}
for _ in 1...N*500 {
check(a, b)
}
}
@inline(never)
public func run_SubstringEquatable(_ N: Int) {
var string = "pen,pineapple,apple,pen"
string += ",✒️,🍍,🍏,✒️"
let substrings = string.split(separator: ",")
var count = 0
for _ in 1...N*500 {
for s in substrings {
if substrings.contains(s) { count = count &+ 1 }
}
}
CheckResults(count == 8*N*500)
}
@inline(never)
public func run_SubstringEqualString(_ N: Int) {
var string = "pen,pineapple,apple,pen"
string += ",✒️,🍍,🍏,✒️"
let substrings = string.split(separator: ",")
let pineapple = "pineapple"
let apple = "🍏"
var count = 0
for _ in 1...N*500 {
for s in substrings {
if s == pineapple || s == apple { count = count &+ 1 }
}
}
CheckResults(count == 2*N*500)
}
let _substrings = "pen,pineapple,apple,pen,✒️,🍍,🍏,✒️".split(separator: ",")
let _comparison = _substrings + ["PPAP"]
@inline(never)
public func run_SubstringComparable(_ N: Int) {
let substrings = _substrings // without this alias, there was 25% slowdown
let comparison = _comparison // due to increased retain/release traffic 🤷
var count = 0
for _ in 1...N*500 {
if substrings.lexicographicallyPrecedes(comparison) {
count = count &+ 1
}
}
CheckResults(count == N*500)
}
extension Character {
fileprivate var isASCIIWhitespace: Bool {
return self == " " || self == "\t" || self == "\r" || self == "\n" || self == "\r\n"
}
}
extension Substring {
fileprivate func trimWhitespace() -> Substring {
var me = self
while me.first?.isASCIIWhitespace == .some(true) {
me = me.dropFirst()
}
while me.last?.isASCIIWhitespace == .some(true) {
me = me.dropLast()
}
return me
}
}
let _trimmableSubstrings = "pineapple,🍍, pineapple\t,\r\n\r\n\r\n, 🍍 ,".split(separator: ",")
@inline(never)
public func run_SubstringTrimmingASCIIWhitespace(_ N: Int) {
let substrings = _trimmableSubstrings // bringing this alias from above
var count = 0
for _ in 1...N*100 {
for substring in substrings {
blackHole(substring.trimWhitespace())
}
}
}
/*
func checkLess<T, U>(_ x: T, _ y: U)
where T : StringProtocol, U : StringProtocol {
blackHole(x < y)
}
@inline(never)
public func run _LessStringSubstringGenericStringProtocol(_ N: Int) {
let (a, b) = (s1, ss1)
for _ in 1...N*500 {
checkLess(a, b)
}
}
@inline(never)
public func run _LessSubstringStringGenericStringProtocol(_ N: Int) {
let (a, b) = (s1, ss1)
for _ in 1...N*500 {
checkLess(b, a)
}
}
@inline(never)
public func run _LessSubstringSubstringGenericStringProtocol(_ N: Int) {
let (_, a) = (s1, ss1)
let (_, b) = (s2, ss2)
for _ in 1...N*500 {
checkLess(a, b)
}
}
*/
|
apache-2.0
|
faf7b086955a60b1b3653476a61d94e0
| 27.465465 | 159 | 0.647009 | 3.183009 | false | false | false | false |
samlaudev/DesignerNews
|
DesignerNews/LoginViewController.swift
|
1
|
2438
|
//
// LoginViewController.swift
// DesignerNews
//
// Created by Sam Lau on 3/12/15.
// Copyright (c) 2015 Sam Lau. All rights reserved.
//
import UIKit
protocol LoginViewControllerDelegate: class {
func loginViewControllerDidLogin(controller: LoginViewController)
}
class LoginViewController: UIViewController {
// MARK: - UI properties
@IBOutlet weak var dialogView: DesignableView!
@IBOutlet weak var emailImageView: SpringImageView!
@IBOutlet weak var passwordImageView: SpringImageView!
@IBOutlet weak var emailTextField: DesignableTextField!
@IBOutlet weak var passwordTextField: DesignableTextField!
// MARK: - Delegate
weak var delegate: LoginViewControllerDelegate?
// MARK: - View controller lifecycle
override func viewDidLoad() {
super.viewDidLoad()
// setup text field delegate
emailTextField.delegate = self
passwordTextField.delegate = self
}
@IBAction func loginButtonPressed(sender: AnyObject) {
DesignerNewsService.loginWithEmail(emailTextField.text, password: passwordTextField.text){
(token) -> () in
if let token = token {
LocalStore.saveToken(token)
self.dismissViewControllerAnimated(true, completion: nil)
self.delegate?.loginViewControllerDidLogin(self)
}else {
self.dialogView.animation = "shake"
self.dialogView.animate()
}
}
}
// MARK: - Respond to action
@IBAction func closeButtonDidTouch(sender: AnyObject) {
dismissViewControllerAnimated(true, completion: nil)
dialogView.animation = "zoomOut"
dialogView.animate()
}
}
// MARK: - TextField delegate
extension LoginViewController: UITextFieldDelegate {
func textFieldDidBeginEditing(textField: UITextField) {
if textField == emailTextField {
emailImageView.image = UIImage(named: "icon-mail-active")
emailImageView.animate()
}else if textField == passwordTextField {
passwordImageView.image = UIImage(named: "icon-password-active")
passwordImageView.animate()
}
}
func textFieldDidEndEditing(textField: UITextField) {
emailImageView.image = UIImage(named: "icon-mail")
passwordImageView.image = UIImage(named: "icon-password")
}
}
|
mit
|
6f26651cb57b7ae557e35fb995318e92
| 31.506667 | 98 | 0.658326 | 5.198294 | false | false | false | false |
J-Mendes/Bliss-Assignement
|
Bliss-Assignement/Bliss-Assignement/AppDelegate.swift
|
1
|
4698
|
//
// AppDelegate.swift
// Bliss-Assignement
//
// Created by Jorge Mendes on 12/10/16.
// Copyright © 2016 Jorge Mendes. All rights reserved.
//
import UIKit
import AlamofireNetworkActivityIndicator
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
private let urlScheme: String = "blissrecruitment"
var window: UIWindow?
private var networkUnreachableView: NetworkUnreachableView?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject : AnyObject]?) -> Bool {
NetworkActivityIndicatorManager.sharedManager.isEnabled = true
NetworkActivityIndicatorManager.sharedManager.startDelay = 0.1
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(self.networkIsReachable), name: BaseHTTPManager.networkReachable, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(self.networkIsUnreachable), name: BaseHTTPManager.networkUnreachable, object: nil)
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
NSNotificationCenter.defaultCenter().removeObserver(self)
}
func application(app: UIApplication, openURL url: NSURL, options: [String : AnyObject]) -> Bool {
if url.scheme != nil && url.scheme! == self.urlScheme {
if url.query != nil {
if url.host! == "questions" {
url.query!.componentsSeparatedByString("&").forEach {
let components: [String] = $0.componentsSeparatedByString("=")
if components.count == 2 && components.first != nil {
if components.first! == "question_filter" {
NSUserDefaults.standardUserDefaults().setObject(components.last == nil ? "" : components.last!, forKey: "filter")
NSUserDefaults.standardUserDefaults().synchronize()
} else if components.first! == "question_id" && components.last != nil {
NSUserDefaults.standardUserDefaults().setObject(components.last!, forKey: "id")
NSUserDefaults.standardUserDefaults().synchronize()
}
}
}
}
}
}
return true
}
// MARK: - Network reachability methods
internal func networkIsReachable() {
if self.networkUnreachableView != nil && (self.networkUnreachableView?.isShowing)! {
self.networkUnreachableView?.dismiss()
}
}
internal func networkIsUnreachable() {
if self.networkUnreachableView == nil || !(self.networkUnreachableView?.isShowing)! {
self.networkUnreachableView = NSBundle.mainBundle().loadNibNamed(String(NetworkUnreachableView), owner: self, options: nil)?.first as? NetworkUnreachableView
self.networkUnreachableView?.show()
}
}
}
|
lgpl-3.0
|
c524212df16675df9424e2b904fc5266
| 48.968085 | 285 | 0.67128 | 5.591667 | false | false | false | false |
google/iosched-ios
|
Source/IOsched/Screens/Search/AgendaSearchResultsProvider.swift
|
1
|
1712
|
//
// Copyright (c) 2017 Google Inc.
//
// 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
public class AgendaSearchResultsProvider: SearchResultProvider {
private let agendaItems = AgendaItem.allAgendaItems.flatMap({ return $0 })
private lazy var fuzzyMatcher = SearchResultsMatcher()
public var title: String {
return NSLocalizedString(
"Agenda",
comment: """
The title of the Agenda screen. May also be displayed in search results.
Good synonyms for this screen are 'itenerary', 'schedule'.
"""
)
}
public func matches(query: String) -> [SearchResult] {
return fuzzyMatcher.match(query: query, in: agendaItems)
}
public func display(searchResult: SearchResult, using navigator: RootNavigator) {
guard let agendaItem = searchResult.wrappedItem as? AgendaItem else { return }
navigator.navigateToAgendaItem(agendaItem)
}
}
extension AgendaSearchResultsProvider {
public func hash(into hasher: inout Hasher) {
title.hash(into: &hasher)
}
}
public func == (lhs: AgendaSearchResultsProvider, rhs: AgendaSearchResultsProvider) -> Bool {
return lhs.title == rhs.title
}
|
apache-2.0
|
a98fd937a799f8d38cc25f38ecf4fd47
| 29.571429 | 93 | 0.712033 | 4.290727 | false | false | false | false |
diejmon/Preferences
|
Sources/KeychainPreferences.swift
|
1
|
2091
|
import Foundation
import Security
public struct KeychainPreferences: Preferences {
private let accessGroup: String?
public init(accessGroup: String? = nil) {
self.accessGroup = accessGroup
}
public func get<Key>(_ key: Key) throws -> Key.PreferenceValueType? where Key: PreferenceKey {
var query = self.query(forKey: key.rawKey)
query[kSecReturnData] = kCFBooleanTrue
query[kSecMatchLimit] = kSecMatchLimitOne
var result: AnyObject?
let resultCode: OSStatus = withUnsafeMutablePointer(to: &result) {
SecItemCopyMatching(query as CFDictionary, UnsafeMutablePointer($0))
}
guard resultCode == noErr,
let data = result as? Data else {
return nil
}
return try decode(data)
}
public func set<Key, Value>(_ value: Value?, for key: Key) throws where Key: PreferenceKey, Value == Key.PreferenceValueType {
deleteItem(forKey: key.rawKey)
guard let value = value else {
return
}
let encodedData = try encode(value)
var query = self.query(forKey: key.rawKey)
query[kSecValueData] = encodedData
let _: OSStatus = SecItemAdd(query as CFDictionary, nil)
}
private func deleteItem(forKey key: String) {
var query: [CFString: Any] = [
kSecClass: kSecClassGenericPassword,
kSecAttrAccount : key
]
addAccessGroup(to: &query)
let _: OSStatus = SecItemDelete(query as CFDictionary)
}
private func query(forKey key: String) -> [CFString: Any] {
var query: [CFString: Any] = [
kSecClass: kSecClassGenericPassword,
kSecAttrAccount: key,
]
addAccessGroup(to: &query)
return query
}
private func addAccessGroup(to query: inout [CFString: Any]) {
if let accessGroup = accessGroup {
query[kSecAttrAccessGroup] = accessGroup
}
}
}
|
mit
|
10896bac7e5b0fc98bf81f52f8bb7713
| 29.304348 | 130 | 0.588714 | 5.293671 | false | false | false | false |
phakphumi/Chula-Expo-iOS-Application
|
Chula Expo 2017/Chula Expo 2017/Third_events/EventTableViewCell.swift
|
1
|
2198
|
//
// EventTableViewCell.swift
// Chula Expo 2017
//
// Created by NOT on 1/5/2560 BE.
// Copyright © 2560 Chula Computer Engineering Batch#41. All rights reserved.
//
import UIKit
class EventTableViewCell: UITableViewCell
{
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var timeLabel: UILabel!
@IBOutlet weak var locationLabel: UILabel!
var activityId: String?
var desc: String?
var bannerUrl: String?
var isHighlight: Bool?
var isFavorite: Bool?
var reservable: Bool?
var isReserve: Bool?
var toTags: NSSet?
var toFaculty: String?
var toImages: NSSet?
var toVideos: String?
var dateText: String?
var name: String?
{
didSet
{
updateUI()
}
}
var startTime: NSDate?
{
didSet
{
updateUI()
}
}
var endTime: NSDate?
{
didSet
{
updateUI()
}
}
var locationDesc: String?
{
didSet
{
updateUI()
}
}
private func updateUI()
{
//Reset
nameLabel.text = nil
timeLabel.text = nil
locationLabel.text = nil
if let eventName = name
{
nameLabel.text = eventName
}
if let eventStartTime = startTime
{
if let eventEndTime = endTime{
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "H:mm"
let sTime = dateFormatter.string(from: eventStartTime as Date)
let eTime = dateFormatter.string(from: eventEndTime as Date)
timeLabel.text = "\(sTime) - \(eTime)"
}
}
if let eventLocationDesc = locationDesc
{
locationLabel.text = eventLocationDesc
}
}
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
|
mit
|
6c6cf2c5a77add475cda995dea8d4faa
| 20.752475 | 78 | 0.538917 | 4.860619 | false | false | false | false |
grafiti-io/SwiftCharts
|
Examples/Examples/TargetExample.swift
|
1
|
3241
|
//
// TargetExample.swift
// SwiftCharts
//
// Created by ischuetz on 04/05/15.
// Copyright (c) 2015 ivanschuetz. All rights reserved.
//
import UIKit
import SwiftCharts
class TargetExample: UIViewController {
fileprivate var chart: Chart? // arc
override func viewDidLoad() {
super.viewDidLoad()
let labelSettings = ChartLabelSettings(font: ExamplesDefaults.labelFont)
let chartPoints: [ChartPoint] = [(2, 2), (4, 4), (7, 1), (8, 11), (12, 3)].map{ChartPoint(x: ChartAxisValueInt($0.0, labelSettings: labelSettings), y: ChartAxisValueInt($0.1))}
let xValues = chartPoints.map{$0.x}
let yValues = ChartAxisValuesStaticGenerator.generateYAxisValuesWithChartPoints(chartPoints, minSegmentCount: 10, maxSegmentCount: 20, multiple: 2, axisValueGenerator: {ChartAxisValueDouble($0, labelSettings: labelSettings)}, addPaddingSegmentIfEdge: false)
let xModel = ChartAxisModel(axisValues: xValues, axisTitleLabel: ChartAxisLabel(text: "Axis title", settings: labelSettings))
let yModel = ChartAxisModel(axisValues: yValues, axisTitleLabel: ChartAxisLabel(text: "Axis title", settings: labelSettings.defaultVertical()))
let chartFrame = ExamplesDefaults.chartFrame(view.bounds)
let chartSettings = ExamplesDefaults.chartSettingsWithPanZoom
let coordsSpace = ChartCoordsSpaceLeftBottomSingleAxis(chartSettings: chartSettings, chartFrame: chartFrame, xModel: xModel, yModel: yModel)
let (xAxisLayer, yAxisLayer, innerFrame) = (coordsSpace.xAxisLayer, coordsSpace.yAxisLayer, coordsSpace.chartInnerFrame)
let lineModel = ChartLineModel(chartPoints: chartPoints, lineColor: UIColor.red, animDuration: 0.5, animDelay: 0)
let targetGenerator = {(chartPointModel: ChartPointLayerModel, layer: ChartPointsLayer, chart: Chart, isTransform: Bool) -> UIView? in
if chartPointModel.index != 3 {
return nil
}
return ChartPointTargetingView(chartPoint: chartPointModel.chartPoint, screenLoc: chartPointModel.screenLoc, animDuration: isTransform ? 0 : 0.5, animDelay: isTransform ? 0 : 1, layer: layer, chart: chart)
}
let chartPointsTargetLayer = ChartPointsViewsLayer(xAxis: xAxisLayer.axis, yAxis: yAxisLayer.axis, chartPoints: chartPoints, viewGenerator: targetGenerator)
let chartPointsLineLayer = ChartPointsLineLayer(xAxis: xAxisLayer.axis, yAxis: yAxisLayer.axis, lineModels: [lineModel])
let settings = ChartGuideLinesDottedLayerSettings(linesColor: UIColor.black, linesWidth: ExamplesDefaults.guidelinesWidth)
let guidelinesLayer = ChartGuideLinesDottedLayer(xAxisLayer: xAxisLayer, yAxisLayer: yAxisLayer, settings: settings)
let chart = Chart(
frame: chartFrame,
innerFrame: innerFrame,
settings: chartSettings,
layers: [
xAxisLayer,
yAxisLayer,
guidelinesLayer,
chartPointsLineLayer,
chartPointsTargetLayer
]
)
view.addSubview(chart.view)
self.chart = chart
}
}
|
apache-2.0
|
ad278c97cb67f46af9e9a3badc15207b
| 46.661765 | 265 | 0.684974 | 5.549658 | false | false | false | false |
OctoberHammer/CoreDataCollViewFRC
|
Pods/SwiftyButton/SwiftyButton/PressableButton.swift
|
1
|
3677
|
//
// PressableButton.swift
// SwiftyButton
//
// Created by Lois Di Qual on 10/23/16.
// Copyright © 2016 TakeScoop. All rights reserved.
//
import UIKit
@IBDesignable
open class PressableButton: UIButton {
public enum Defaults {
public static var colors = ColorSet(
button: UIColor(red: 52.0/255.0, green:
152.0/255.0, blue: 219.0/255.0, alpha: 1.0)
,
shadow: UIColor(red: 41.0/255.0, green:
128.0/255.0, blue: 185.0/255.0, alpha: 1.0)
)
public static var disabledColors = ColorSet(
button: UIColor(red: 41.0/255.0, green:
128.0/255.0, blue: 185.0/255.0, alpha: 1.0),
shadow: UIColor(red: 127.0/255.0, green:
140.0/255.0, blue: 141.0/255.0, alpha: 1.0)
)
public static var shadowHeight: CGFloat = 3
public static var depth: Double = 0.7
public static var cornerRadius: CGFloat = 3
}
public struct ColorSet {
let button: UIColor
let shadow: UIColor
public init(button: UIColor, shadow: UIColor) {
self.button = button
self.shadow = shadow
}
}
public var colors: ColorSet = Defaults.colors {
didSet {
updateBackgroundImages()
}
}
public var disabledColors: ColorSet = Defaults.disabledColors {
didSet {
updateBackgroundImages()
}
}
@IBInspectable
public var shadowHeight: CGFloat = Defaults.shadowHeight {
didSet {
updateBackgroundImages()
updateTitleInsets()
}
}
@IBInspectable
public var depth: Double = Defaults.depth {
didSet {
updateBackgroundImages()
updateTitleInsets()
}
}
@IBInspectable
public var cornerRadius: CGFloat = Defaults.cornerRadius {
didSet {
updateBackgroundImages()
}
}
// MARK: - UIButton
public override init(frame: CGRect) {
super.init(frame: frame)
configure()
updateBackgroundImages()
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
configure()
updateBackgroundImages()
}
override open var isHighlighted: Bool {
didSet {
updateTitleInsets()
}
}
// MARK: - Internal methods
func configure() {
adjustsImageWhenDisabled = false
adjustsImageWhenHighlighted = false
}
func updateTitleInsets() {
let topPadding = isHighlighted ? shadowHeight * CGFloat(depth) : 0
let bottomPadding = isHighlighted ? shadowHeight * (1 - CGFloat(depth)) : shadowHeight
titleEdgeInsets = UIEdgeInsets(top: topPadding, left: 0, bottom: bottomPadding, right: 0)
}
fileprivate func updateBackgroundImages() {
let normalImage = Utils.buttonImage(color: colors.button, shadowHeight: shadowHeight, shadowColor: colors.shadow, cornerRadius: cornerRadius)
let highlightedImage = Utils.highlightedButtonImage(color: colors.button, shadowHeight: shadowHeight, shadowColor: colors.shadow, cornerRadius: cornerRadius, buttonPressDepth: depth)
let disabledImage = Utils.buttonImage(color: disabledColors.button, shadowHeight: shadowHeight, shadowColor: disabledColors.shadow, cornerRadius: cornerRadius)
setBackgroundImage(normalImage, for: .normal)
setBackgroundImage(highlightedImage, for: .highlighted)
setBackgroundImage(disabledImage, for: .disabled)
}
}
|
mit
|
dcf9f6a2c457534572874b556c54d336
| 29.380165 | 190 | 0.603917 | 4.761658 | false | false | false | false |
Frainbow/ShaRead.frb-swift
|
ShaRead/ShaRead/FavoriteViewController.swift
|
1
|
2135
|
//
// FavoriteViewController.swift
// ShaRead
//
// Created by martin on 2016/5/4.
// Copyright © 2016年 Frainbow. All rights reserved.
//
import UIKit
class FavoriteViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func viewDidAppear(animated: Bool) {
setTabBarVisible(true, animated: false)
}
override func viewWillDisappear(animated: Bool) {
setTabBarVisible(false, animated: false)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - TabBar
func setTabBarVisible(visible:Bool, animated:Bool) {
//* This cannot be called before viewDidLayoutSubviews(), because the frame is not set before this time
// bail if the current state matches the desired state
if (tabBarIsVisible() == visible) { return }
// get a frame calculation ready
let frame = self.tabBarController?.tabBar.frame
let height = frame?.size.height
let offsetY = (visible ? -height! : height)
// zero duration means no animation
let duration:NSTimeInterval = (animated ? 0.3 : 0.0)
// animate the tabBar
if frame != nil {
UIView.animateWithDuration(duration) {
self.tabBarController?.tabBar.frame = CGRectOffset(frame!, 0, offsetY!)
return
}
}
}
func tabBarIsVisible() ->Bool {
return self.tabBarController?.tabBar.frame.origin.y < CGRectGetMaxY(self.view.frame)
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
|
mit
|
a2f9a4e437c2109f630ec1c7469873f6
| 29.028169 | 111 | 0.628987 | 5.004695 | false | false | false | false |
programersun/HiChongSwift
|
HiChongSwift/MoePetHeaderReusable.swift
|
1
|
3348
|
//
// MoePetHeaderReusable.swift
// HiChongSwift
//
// Created by eagle on 14/12/24.
// Copyright (c) 2014年 多思科技. All rights reserved.
//
import UIKit
class MoePetHeaderReusable: UICollectionReusableView {
enum MoePetGender {
case Male
case Female
}
@IBOutlet private weak var signBackgroundView: UIView!
@IBOutlet private weak var avatarImageView: UIImageView!
@IBOutlet private weak var detailLabel: UILabel!
@IBOutlet private weak var genderImageView: UIImageView!
@IBOutlet private weak var nameLabel: UILabel!
@IBOutlet private var statusImageViews: [UIImageView]!
@IBOutlet private weak var signLabel: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
avatarImageView.roundCorner()
avatarImageView.layer.borderColor = UIColor.LCYTableLightBlue().CGColor
avatarImageView.layer.borderWidth = 2.0
detailLabel.backgroundColor = UIColor.LCYTableLightBlue()
detailLabel.layer.cornerRadius = 4.0
detailLabel.layer.masksToBounds = true
detailLabel.textColor = UIColor.LCYThemeDarkText()
signBackgroundView.backgroundColor = UIColor.LCYTableLightBlue()
signLabel.textColor = UIColor.LCYThemeDarkText()
}
var avatarImagePath: String? {
didSet {
if let urlPath = avatarImagePath {
avatarImageView.setImageWithURL(NSURL(string: urlPath))
} else {
avatarImageView.image = nil
}
}
}
var detailText: String? {
didSet {
detailLabel.text = detailText
}
}
var gender: MoePetGender = .Male {
didSet {
if oldValue != gender {
switch gender {
case .Male:
genderImageView.image = UIImage(named: "sqMale")
case .Female:
genderImageView.image = UIImage(named: "sqFemale")
}
}
}
}
var nameText: String? {
didSet {
nameLabel.text = nameText
}
}
func statusLable(#breeding: Bool, adopt: Bool, entrust: Bool) {
for statusImageView in statusImageViews {
statusImageView.image = nil
}
var index = 1
if breeding {
for breedingImageView in statusImageViews {
if breedingImageView.tag == index {
breedingImageView.image = UIImage(named: "petBredding")
break
}
}
index++
}
if adopt {
for breedingImageView in statusImageViews {
if breedingImageView.tag == index {
breedingImageView.image = UIImage(named: "petAdopt")
break
}
}
index++
}
if entrust {
for breedingImageView in statusImageViews {
if breedingImageView.tag == index {
breedingImageView.image = UIImage(named: "petEntrust")
break
}
}
}
}
var sign: String? {
didSet {
signLabel.text = sign
}
}
}
|
apache-2.0
|
82bebf221432c827a2969b4f8782968e
| 26.816667 | 79 | 0.544338 | 5.281646 | false | false | false | false |
Zewo/Epoch
|
Sources/Media/Media/DecodingMedia.swift
|
1
|
17063
|
import Core
import Venice
extension Decodable {
public init<Map : DecodingMedia>(
from map: Map,
userInfo: [CodingUserInfoKey: Any] = [:]
) throws {
let decoder = MediaDecoder<Map>(referencing: map, userInfo: userInfo)
try self.init(from: decoder)
}
}
extension DecodingMedia {
public static func decode<T : Decodable>(
_ type: T.Type,
from readable: Readable,
deadline: Deadline,
userInfo: [CodingUserInfoKey: Any] = [:]
) throws -> T {
let media = try self.init(from: readable, deadline: deadline)
return try T(from: media, userInfo: userInfo)
}
public init(from buffer: UnsafeRawBufferPointer, deadline: Deadline) throws {
let readable = ReadableBuffer(buffer)
try self.init(from: readable, deadline: deadline)
}
}
public protocol DecodingMedia {
static var mediaType: MediaType { get }
init(from readable: Readable, deadline: Deadline) throws
func keyCount() -> Int?
func allKeys<Key : CodingKey>(keyedBy: Key.Type) -> [Key]
func contains<Key : CodingKey>(_ key: Key) -> Bool
func keyedContainer() throws -> DecodingMedia
func unkeyedContainer() throws -> DecodingMedia
func singleValueContainer() throws -> DecodingMedia
func decodeIfPresent(_ type: DecodingMedia.Type, forKey key: CodingKey) throws -> DecodingMedia?
func decode(_ type: DecodingMedia.Type, forKey key: CodingKey) throws -> DecodingMedia
func decodeNil() -> Bool
func decode(_ type: Bool.Type) throws -> Bool
func decode(_ type: Int.Type) throws -> Int
func decode(_ type: Int8.Type) throws -> Int8
func decode(_ type: Int16.Type) throws -> Int16
func decode(_ type: Int32.Type) throws -> Int32
func decode(_ type: Int64.Type) throws -> Int64
func decode(_ type: UInt.Type) throws -> UInt
func decode(_ type: UInt8.Type) throws -> UInt8
func decode(_ type: UInt16.Type) throws -> UInt16
func decode(_ type: UInt32.Type) throws -> UInt32
func decode(_ type: UInt64.Type) throws -> UInt64
func decode(_ type: Float.Type) throws -> Float
func decode(_ type: Double.Type) throws -> Double
func decode(_ type: String.Type) throws -> String
// Optional
func keyedContainer(forKey key: CodingKey) throws -> DecodingMedia
func unkeyedContainer(forKey key: CodingKey) throws -> DecodingMedia
func decodeIfPresent(_ type: Bool.Type, forKey key: CodingKey) throws -> Bool?
func decodeIfPresent(_ type: Int.Type, forKey key: CodingKey) throws -> Int?
func decodeIfPresent(_ type: Int8.Type, forKey key: CodingKey) throws -> Int8?
func decodeIfPresent(_ type: Int16.Type, forKey key: CodingKey) throws -> Int16?
func decodeIfPresent(_ type: Int32.Type, forKey key: CodingKey) throws -> Int32?
func decodeIfPresent(_ type: Int64.Type, forKey key: CodingKey) throws -> Int64?
func decodeIfPresent(_ type: UInt.Type, forKey key: CodingKey) throws -> UInt?
func decodeIfPresent(_ type: UInt8.Type, forKey key: CodingKey) throws -> UInt8?
func decodeIfPresent(_ type: UInt16.Type, forKey key: CodingKey) throws -> UInt16?
func decodeIfPresent(_ type: UInt32.Type, forKey key: CodingKey) throws -> UInt32?
func decodeIfPresent(_ type: UInt64.Type, forKey key: CodingKey) throws -> UInt64?
func decodeIfPresent(_ type: Float.Type, forKey key: CodingKey) throws -> Float?
func decodeIfPresent(_ type: Double.Type, forKey key: CodingKey) throws -> Double?
func decodeIfPresent(_ type: String.Type, forKey key: CodingKey) throws -> String?
func decodeIfPresent(_ type: Bool.Type) throws -> Bool?
func decodeIfPresent(_ type: Int.Type) throws -> Int?
func decodeIfPresent(_ type: Int8.Type) throws -> Int8?
func decodeIfPresent(_ type: Int16.Type) throws -> Int16?
func decodeIfPresent(_ type: Int32.Type) throws -> Int32?
func decodeIfPresent(_ type: Int64.Type) throws -> Int64?
func decodeIfPresent(_ type: UInt.Type) throws -> UInt?
func decodeIfPresent(_ type: UInt8.Type) throws -> UInt8?
func decodeIfPresent(_ type: UInt16.Type) throws -> UInt16?
func decodeIfPresent(_ type: UInt32.Type) throws -> UInt32?
func decodeIfPresent(_ type: UInt64.Type) throws -> UInt64?
func decodeIfPresent(_ type: Float.Type) throws -> Float?
func decodeIfPresent(_ type: Double.Type) throws -> Double?
func decodeIfPresent(_ type: String.Type) throws -> String?
}
extension DecodingMedia {
public func keyedContainer(forKey key: CodingKey) throws -> DecodingMedia {
guard let map = try decodeIfPresent(Self.self, forKey: key) else {
throw DecodingError.keyNotFound(key, DecodingError.Context())
}
return try map.keyedContainer()
}
public func unkeyedContainer(forKey key: CodingKey) throws -> DecodingMedia {
guard let map = try decodeIfPresent(Self.self, forKey: key) else {
throw DecodingError.keyNotFound(key, DecodingError.Context())
}
return try map.unkeyedContainer()
}
public func decode<D : Decodable>(_ type: D.Type, forKey key: CodingKey) throws -> D {
guard let map = try decodeIfPresent(Self.self, forKey: key) as? Self else {
throw DecodingError.valueNotFound(type, DecodingError.Context())
}
return try D(from: map)
}
public func decode(_ type: Bool.Type, forKey key: CodingKey) throws -> Bool {
guard let map = try decodeIfPresent(Self.self, forKey: key) else {
throw DecodingError.valueNotFound(type, DecodingError.Context())
}
return try map.decode(type)
}
public func decode(_ type: Int.Type, forKey key: CodingKey) throws -> Int {
guard let map = try decodeIfPresent(Self.self, forKey: key) else {
throw DecodingError.valueNotFound(type, DecodingError.Context())
}
return try map.decode(type)
}
public func decode(_ type: Int8.Type, forKey key: CodingKey) throws -> Int8 {
guard let map = try decodeIfPresent(Self.self, forKey: key) else {
throw DecodingError.valueNotFound(type, DecodingError.Context())
}
return try map.decode(type)
}
public func decode(_ type: Int16.Type, forKey key: CodingKey) throws -> Int16 {
guard let map = try decodeIfPresent(Self.self, forKey: key) else {
throw DecodingError.valueNotFound(type, DecodingError.Context())
}
return try map.decode(type)
}
public func decode(_ type: Int32.Type, forKey key: CodingKey) throws -> Int32 {
guard let map = try decodeIfPresent(Self.self, forKey: key) else {
throw DecodingError.valueNotFound(type, DecodingError.Context())
}
return try map.decode(type)
}
public func decode(_ type: Int64.Type, forKey key: CodingKey) throws -> Int64 {
guard let map = try decodeIfPresent(Self.self, forKey: key) else {
throw DecodingError.valueNotFound(type, DecodingError.Context())
}
return try map.decode(type)
}
public func decode(_ type: UInt.Type, forKey key: CodingKey) throws -> UInt {
guard let map = try decodeIfPresent(Self.self, forKey: key) else {
throw DecodingError.valueNotFound(type, DecodingError.Context())
}
return try map.decode(type)
}
public func decode(_ type: UInt8.Type, forKey key: CodingKey) throws -> UInt8 {
guard let map = try decodeIfPresent(Self.self, forKey: key) else {
throw DecodingError.valueNotFound(type, DecodingError.Context())
}
return try map.decode(type)
}
public func decode(_ type: UInt16.Type, forKey key: CodingKey) throws -> UInt16 {
guard let map = try decodeIfPresent(Self.self, forKey: key) else {
throw DecodingError.valueNotFound(type, DecodingError.Context())
}
return try map.decode(type)
}
public func decode(_ type: UInt32.Type, forKey key: CodingKey) throws -> UInt32 {
guard let map = try decodeIfPresent(Self.self, forKey: key) else {
throw DecodingError.valueNotFound(type, DecodingError.Context())
}
return try map.decode(type)
}
public func decode(_ type: UInt64.Type, forKey key: CodingKey) throws -> UInt64 {
guard let map = try decodeIfPresent(Self.self, forKey: key) else {
throw DecodingError.valueNotFound(type, DecodingError.Context())
}
return try map.decode(type)
}
public func decode(_ type: Float.Type, forKey key: CodingKey) throws -> Float {
guard let map = try decodeIfPresent(Self.self, forKey: key) else {
throw DecodingError.valueNotFound(type, DecodingError.Context())
}
return try map.decode(type)
}
public func decode(_ type: Double.Type, forKey key: CodingKey) throws -> Double {
guard let map = try decodeIfPresent(Self.self, forKey: key) else {
throw DecodingError.valueNotFound(type, DecodingError.Context())
}
return try map.decode(type)
}
public func decode(_ type: String.Type, forKey key: CodingKey) throws -> String {
guard let map = try decodeIfPresent(Self.self, forKey: key) else {
throw DecodingError.valueNotFound(type, DecodingError.Context())
}
return try map.decode(type)
}
public func decodeIfPresent(_ type: Bool.Type, forKey key: CodingKey) throws -> Bool? {
guard let map = try decodeIfPresent(Self.self, forKey: key) else {
return nil
}
guard !map.decodeNil() else {
return nil
}
return try map.decode(type)
}
public func decodeIfPresent(_ type: Int.Type, forKey key: CodingKey) throws -> Int? {
guard let map = try decodeIfPresent(Self.self, forKey: key) else {
return nil
}
guard !map.decodeNil() else {
return nil
}
return try map.decode(type)
}
public func decodeIfPresent(_ type: Int8.Type, forKey key: CodingKey) throws -> Int8? {
guard let map = try decodeIfPresent(Self.self, forKey: key) else {
return nil
}
guard !map.decodeNil() else {
return nil
}
return try map.decode(type)
}
public func decodeIfPresent(_ type: Int16.Type, forKey key: CodingKey) throws -> Int16? {
guard let map = try decodeIfPresent(Self.self, forKey: key) else {
return nil
}
guard !map.decodeNil() else {
return nil
}
return try map.decode(type)
}
public func decodeIfPresent(_ type: Int32.Type, forKey key: CodingKey) throws -> Int32? {
guard let map = try decodeIfPresent(Self.self, forKey: key) else {
return nil
}
guard !map.decodeNil() else {
return nil
}
return try map.decode(type)
}
public func decodeIfPresent(_ type: Int64.Type, forKey key: CodingKey) throws -> Int64? {
guard let map = try decodeIfPresent(Self.self, forKey: key) else {
return nil
}
guard !map.decodeNil() else {
return nil
}
return try map.decode(type)
}
public func decodeIfPresent(_ type: UInt.Type, forKey key: CodingKey) throws -> UInt? {
guard let map = try decodeIfPresent(Self.self, forKey: key) else {
return nil
}
guard !map.decodeNil() else {
return nil
}
return try map.decode(type)
}
public func decodeIfPresent(_ type: UInt8.Type, forKey key: CodingKey) throws -> UInt8? {
guard let map = try decodeIfPresent(Self.self, forKey: key) else {
return nil
}
guard !map.decodeNil() else {
return nil
}
return try map.decode(type)
}
public func decodeIfPresent(_ type: UInt16.Type, forKey key: CodingKey) throws -> UInt16? {
guard let map = try decodeIfPresent(Self.self, forKey: key) else {
return nil
}
guard !map.decodeNil() else {
return nil
}
return try map.decode(type)
}
public func decodeIfPresent(_ type: UInt32.Type, forKey key: CodingKey) throws -> UInt32? {
guard let map = try decodeIfPresent(Self.self, forKey: key) else {
return nil
}
guard !map.decodeNil() else {
return nil
}
return try map.decode(type)
}
public func decodeIfPresent(_ type: UInt64.Type, forKey key: CodingKey) throws -> UInt64? {
guard let map = try decodeIfPresent(Self.self, forKey: key) else {
return nil
}
guard !map.decodeNil() else {
return nil
}
return try map.decode(type)
}
public func decodeIfPresent(_ type: Float.Type, forKey key: CodingKey) throws -> Float? {
guard let map = try decodeIfPresent(Self.self, forKey: key) else {
return nil
}
guard !map.decodeNil() else {
return nil
}
return try map.decode(type)
}
public func decodeIfPresent(_ type: Double.Type, forKey key: CodingKey) throws -> Double? {
guard let map = try decodeIfPresent(Self.self, forKey: key) else {
return nil
}
guard !map.decodeNil() else {
return nil
}
return try map.decode(type)
}
public func decodeIfPresent(_ type: String.Type, forKey key: CodingKey) throws -> String? {
guard let map = try decodeIfPresent(Self.self, forKey: key) else {
return nil
}
guard !map.decodeNil() else {
return nil
}
return try map.decode(type)
}
public func decodeIfPresent(_ type: Bool.Type) throws -> Bool? {
guard !decodeNil() else {
return nil
}
return try decode(type)
}
public func decodeIfPresent(_ type: Int.Type) throws -> Int? {
guard !decodeNil() else {
return nil
}
return try decode(type)
}
public func decodeIfPresent(_ type: Int8.Type) throws -> Int8? {
guard !decodeNil() else {
return nil
}
return try decode(type)
}
public func decodeIfPresent(_ type: Int16.Type) throws -> Int16? {
guard !decodeNil() else {
return nil
}
return try decode(type)
}
public func decodeIfPresent(_ type: Int32.Type) throws -> Int32? {
guard !decodeNil() else {
return nil
}
return try decode(type)
}
public func decodeIfPresent(_ type: Int64.Type) throws -> Int64? {
guard !decodeNil() else {
return nil
}
return try decode(type)
}
public func decodeIfPresent(_ type: UInt.Type) throws -> UInt? {
guard !decodeNil() else {
return nil
}
return try decode(type)
}
public func decodeIfPresent(_ type: UInt8.Type) throws -> UInt8? {
guard !decodeNil() else {
return nil
}
return try decode(type)
}
public func decodeIfPresent(_ type: UInt16.Type) throws -> UInt16? {
guard !decodeNil() else {
return nil
}
return try decode(type)
}
public func decodeIfPresent(_ type: UInt32.Type) throws -> UInt32? {
guard !decodeNil() else {
return nil
}
return try decode(type)
}
public func decodeIfPresent(_ type: UInt64.Type) throws -> UInt64? {
guard !decodeNil() else {
return nil
}
return try decode(type)
}
public func decodeIfPresent(_ type: Float.Type) throws -> Float? {
guard !decodeNil() else {
return nil
}
return try decode(type)
}
public func decodeIfPresent(_ type: Double.Type) throws -> Double? {
guard !decodeNil() else {
return nil
}
return try decode(type)
}
public func decodeIfPresent(_ type: String.Type) throws -> String? {
guard !decodeNil() else {
return nil
}
return try decode(type)
}
}
|
mit
|
f9e72d01906ce37c47e2c5251e50dcd7
| 32.196498 | 100 | 0.589931 | 4.649319 | false | false | false | false |
dclelland/AudioKit
|
AudioKit/Common/Nodes/Effects/Filters/Band Reject Butterworth Filter/AKBandRejectButterworthFilter.swift
|
1
|
4736
|
//
// AKBandRejectButterworthFilter.swift
// AudioKit
//
// Created by Aurelius Prochazka, revision history on Github.
// Copyright (c) 2016 Aurelius Prochazka. All rights reserved.
//
import AVFoundation
/// These filters are Butterworth second-order IIR filters. They offer an almost
/// flat passband and very good precision and stopband attenuation.
///
/// - parameter input: Input node to process
/// - parameter centerFrequency: Center frequency. (in Hertz)
/// - parameter bandwidth: Bandwidth. (in Hertz)
///
public class AKBandRejectButterworthFilter: AKNode, AKToggleable {
// MARK: - Properties
internal var internalAU: AKBandRejectButterworthFilterAudioUnit?
internal var token: AUParameterObserverToken?
private var centerFrequencyParameter: AUParameter?
private var bandwidthParameter: AUParameter?
/// Ramp Time represents the speed at which parameters are allowed to change
public var rampTime: Double = AKSettings.rampTime {
willSet {
if rampTime != newValue {
internalAU?.rampTime = newValue
internalAU?.setUpParameterRamp()
}
}
}
/// Center frequency. (in Hertz)
public var centerFrequency: Double = 3000 {
willSet {
if centerFrequency != newValue {
if internalAU!.isSetUp() {
centerFrequencyParameter?.setValue(Float(newValue), originator: token!)
} else {
internalAU?.centerFrequency = Float(newValue)
}
}
}
}
/// Bandwidth. (in Hertz)
public var bandwidth: Double = 2000 {
willSet {
if bandwidth != newValue {
if internalAU!.isSetUp() {
bandwidthParameter?.setValue(Float(newValue), originator: token!)
} else {
internalAU?.bandwidth = Float(newValue)
}
}
}
}
/// Tells whether the node is processing (ie. started, playing, or active)
public var isStarted: Bool {
return internalAU!.isPlaying()
}
// MARK: - Initialization
/// Initialize this filter node
///
/// - parameter input: Input node to process
/// - parameter centerFrequency: Center frequency. (in Hertz)
/// - parameter bandwidth: Bandwidth. (in Hertz)
///
public init(
_ input: AKNode,
centerFrequency: Double = 3000,
bandwidth: Double = 2000) {
self.centerFrequency = centerFrequency
self.bandwidth = bandwidth
var description = AudioComponentDescription()
description.componentType = kAudioUnitType_Effect
description.componentSubType = 0x62746272 /*'btbr'*/
description.componentManufacturer = 0x41754b74 /*'AuKt'*/
description.componentFlags = 0
description.componentFlagsMask = 0
AUAudioUnit.registerSubclass(
AKBandRejectButterworthFilterAudioUnit.self,
asComponentDescription: description,
name: "Local AKBandRejectButterworthFilter",
version: UInt32.max)
super.init()
AVAudioUnit.instantiateWithComponentDescription(description, options: []) {
avAudioUnit, error in
guard let avAudioUnitEffect = avAudioUnit else { return }
self.avAudioNode = avAudioUnitEffect
self.internalAU = avAudioUnitEffect.AUAudioUnit as? AKBandRejectButterworthFilterAudioUnit
AudioKit.engine.attachNode(self.avAudioNode)
input.addConnectionPoint(self)
}
guard let tree = internalAU?.parameterTree else { return }
centerFrequencyParameter = tree.valueForKey("centerFrequency") as? AUParameter
bandwidthParameter = tree.valueForKey("bandwidth") as? AUParameter
token = tree.tokenByAddingParameterObserver {
address, value in
dispatch_async(dispatch_get_main_queue()) {
if address == self.centerFrequencyParameter!.address {
self.centerFrequency = Double(value)
} else if address == self.bandwidthParameter!.address {
self.bandwidth = Double(value)
}
}
}
internalAU?.centerFrequency = Float(centerFrequency)
internalAU?.bandwidth = Float(bandwidth)
}
// MARK: - Control
/// Function to start, play, or activate the node, all do the same thing
public func start() {
self.internalAU!.start()
}
/// Function to stop or bypass the node, both are equivalent
public func stop() {
self.internalAU!.stop()
}
}
|
mit
|
d410e501b2bc4064c1541d706cee70ca
| 32.588652 | 102 | 0.61951 | 5.481481 | false | false | false | false |
pocketworks/Spring
|
SpringApp/SpringViewController.swift
|
2
|
7984
|
//
// SpringViewController.swift
// DesignerNewsApp
//
// Created by Meng To on 2015-01-02.
// Copyright (c) 2015 Meng To. All rights reserved.
//
import UIKit
import Spring
class SpringViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource, OptionsViewControllerDelegate {
@IBOutlet weak var delayLabel: UILabel!
@IBOutlet weak var durationLabel: UILabel!
@IBOutlet weak var forceLabel: UILabel!
@IBOutlet weak var delaySlider: UISlider!
@IBOutlet weak var durationSlider: UISlider!
@IBOutlet weak var forceSlider: UISlider!
@IBOutlet weak var ballView: SpringView!
@IBOutlet weak var animationPicker: UIPickerView!
var selectedRow: Int = 0
var selectedEasing: Int = 0
var selectedForce: CGFloat = 1
var selectedDuration: CGFloat = 1
var selectedDelay: CGFloat = 0
var selectedDamping: CGFloat = 0.7
var selectedVelocity: CGFloat = 0.7
var selectedScale: CGFloat = 1
var selectedX: CGFloat = 0
var selectedY: CGFloat = 0
var selectedRotate: CGFloat = 0
@IBAction func forceSliderChanged(sender: AnyObject) {
selectedForce = sender.valueForKey("value") as CGFloat
animateView()
forceLabel.text = String(format: "Force: %.1f", Double(selectedForce))
}
@IBAction func durationSliderChanged(sender: AnyObject) {
selectedDuration = sender.valueForKey("value") as CGFloat
animateView()
durationLabel.text = String(format: "Duration: %.1f", Double(selectedDuration))
}
@IBAction func delaySliderChanged(sender: AnyObject) {
selectedDelay = sender.valueForKey("value") as CGFloat
animateView()
delayLabel.text = String(format: "Delay: %.1f", Double(selectedDelay))
}
func dampingSliderChanged(sender: AnyObject) {
selectedDamping = sender.valueForKey("value") as CGFloat
animateView()
}
func velocitySliderChanged(sender: AnyObject) {
selectedVelocity = sender.valueForKey("value") as CGFloat
animateView()
}
func scaleSliderChanged(sender: AnyObject) {
selectedScale = sender.valueForKey("value") as CGFloat
animateView()
}
func xSliderChanged(sender: AnyObject) {
selectedX = sender.valueForKey("value") as CGFloat
animateView()
}
func ySliderChanged(sender: AnyObject) {
selectedY = sender.valueForKey("value") as CGFloat
animateView()
}
func rotateSliderChanged(sender: AnyObject) {
selectedRotate = sender.valueForKey("value") as CGFloat
animateView()
}
func animateView() {
setOptions()
ballView.animate()
}
func setOptions() {
ballView.force = selectedForce
ballView.duration = selectedDuration
ballView.delay = selectedDelay
ballView.damping = selectedDamping
ballView.velocity = selectedVelocity
ballView.scaleX = selectedScale
ballView.scaleY = selectedScale
ballView.x = selectedX
ballView.y = selectedY
ballView.rotate = selectedRotate
ballView.animation = data[0][selectedRow]
ballView.curve = data[1][selectedEasing]
}
func minimizeView(sender: AnyObject) {
spring(0.7, {
self.view.transform = CGAffineTransformMakeScale(0.935, 0.935)
})
UIApplication.sharedApplication().setStatusBarStyle(UIStatusBarStyle.LightContent, animated: true)
}
func maximizeView(sender: AnyObject) {
spring(0.7, {
self.view.transform = CGAffineTransformMakeScale(1, 1)
})
UIApplication.sharedApplication().setStatusBarStyle(UIStatusBarStyle.Default, animated: true)
}
var data = [[
"shake",
"pop",
"morph",
"squeeze",
"wobble",
"swing",
"flipX",
"flipY",
"fall",
"squeezeLeft",
"squeezeRight",
"squeezeDown",
"squeezeUp",
"slideLeft",
"slideRight",
"slideDown",
"slideUp",
"fadeIn",
"fadeOut",
"fadeInLeft",
"fadeInRight",
"fadeInDown",
"fadeInUp",
"zoomIn",
"zoomOut",
"flash",
], ["spring", "linear", "easeIn", "easeOut", "easeInOut","easeInSine","easeOutSine","easeInOutSine","easeInQuad","easeOutQuad","easeInOutQuad","easeInCubic","easeOutCubic","easeInOutCubic","easeInQuart","easeOutQuart","easeInOutQuart","easeInQuint","easeOutQuint","easeInOutQuint","easeInExpo","easeOutExpo","easeInOutExpo","easeInCirc","easeOutCirc","easeInOutCirc","easeInBack","easeOutBack","easeInOutBack"]]
override func viewDidLoad() {
super.viewDidLoad()
animationPicker.delegate = self
animationPicker.dataSource = self
animationPicker.showsSelectionIndicator = true
}
@IBAction func ballButtonPressed(sender: AnyObject) {
UIView.animateWithDuration(0.1, animations: {
self.ballView.backgroundColor = UIColor(hex: "69DBFF")
}, completion: { finished in
UIView.animateWithDuration(0.5, animations: {
self.ballView.backgroundColor = UIColor(hex: "#279CEB")
})
})
animateView()
}
var isBall = false
func changeBall() {
isBall = !isBall
let animation = CABasicAnimation()
let halfWidth = ballView.frame.width / 2
let cornerRadius: CGFloat = isBall ? halfWidth : 10
animation.keyPath = "cornerRadius"
animation.fromValue = isBall ? 10 : halfWidth
animation.toValue = cornerRadius
animation.duration = 0.2
ballView.layer.cornerRadius = cornerRadius
ballView.layer.addAnimation(animation, forKey: "radius")
}
@IBAction func shapeButtonPressed(sender: AnyObject) {
changeBall()
}
func resetButtonPressed(sender: AnyObject) {
selectedForce = 1
selectedDuration = 1
selectedDelay = 0
selectedDamping = 0.7
selectedVelocity = 0.7
selectedScale = 1
selectedX = 0
selectedY = 0
selectedRotate = 0
forceSlider.setValue(Float(selectedForce), animated: true)
durationSlider.setValue(Float(selectedDuration), animated: true)
delaySlider.setValue(Float(selectedDelay), animated: true)
forceLabel.text = String(format: "Force: %.1f", Double(selectedForce))
durationLabel.text = String(format: "Duration: %.1f", Double(selectedDuration))
delayLabel.text = String(format: "Delay: %.1f", Double(selectedDelay))
}
func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int {
return 2
}
func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return data[component].count
}
func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String! {
return data[component][row]
}
func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
switch component {
case 0:
selectedRow = row
animateView()
default:
selectedEasing = row
animateView()
}
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if let optionsViewController = segue.destinationViewController as? OptionsViewController {
optionsViewController.delegate = self
setOptions()
optionsViewController.data = ballView
}
else if let codeViewController = segue.destinationViewController as? CodeViewController {
setOptions()
codeViewController.data = ballView
}
}
}
|
mit
|
acb395a5b5a320c0ab4d67f5eca896de
| 31.995868 | 415 | 0.631012 | 5.027708 | false | false | false | false |
yariksmirnov/aerial
|
shared/InspectorRecord.swift
|
1
|
735
|
//
// InspectorRecord.swift
// Aerial
//
// Created by Yaroslav Smirnov on 26/03/2017.
// Copyright © 2017 Yaroslav Smirnov. All rights reserved.
//
import Foundation
import ObjectMapper
class InspectorRecord: NSObject, Mappable {
var title = ""
var value: Any = ""
init(title: String = "Test Title", value: Any = "") {
self.title = title
self.value = value
super.init()
}
required init?(map: Map) {
super.init()
}
func mapping(map: Map) {
title <- map["title"]
value <- map["value"]
}
}
extension InspectorRecord {
public static func ==(lhs: InspectorRecord, rhs: InspectorRecord) -> Bool {
return lhs.title == rhs.title
}
}
|
mit
|
a5d6b6e01555aa06f549b9369277bf78
| 18.315789 | 79 | 0.592643 | 3.863158 | false | false | false | false |
convergeeducacao/Charts
|
Source/ChartsRealm/Data/RealmCandleDataSet.swift
|
7
|
5200
|
//
// RealmCandleDataSet.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 RealmCandleDataSet: RealmLineScatterCandleRadarDataSet, ICandleChartDataSet
{
open override func initialize()
{
}
public required init()
{
super.init()
}
public init(results: RLMResults<RLMObject>?, xValueField: String, highField: String, lowField: String, openField: String, closeField: String, label: String?)
{
_highField = highField
_lowField = lowField
_openField = openField
_closeField = closeField
super.init(results: results, xValueField: xValueField, yValueField: "", label: label)
}
public convenience init(results: RLMResults<RLMObject>?, xValueField: String, highField: String, lowField: String, openField: String, closeField: String)
{
self.init(results: results, xValueField: xValueField, highField: highField, lowField: lowField, openField: openField, closeField: closeField, label: "DataSet")
}
public init(realm: RLMRealm?, modelName: String, resultsWhere: String, xValueField: String, highField: String, lowField: String, openField: String, closeField: String, label: String?)
{
_highField = highField
_lowField = lowField
_openField = openField
_closeField = closeField
super.init(realm: realm, modelName: modelName, resultsWhere: resultsWhere, xValueField: xValueField, yValueField: "", label: label)
}
// MARK: - Data functions and accessors
internal var _highField: String?
internal var _lowField: String?
internal var _openField: String?
internal var _closeField: String?
internal override func buildEntryFromResultObject(_ object: RLMObject, x: Double) -> ChartDataEntry
{
let entry = CandleChartDataEntry(
x: _xValueField == nil ? x : object[_xValueField!] as! Double,
shadowH: object[_highField!] as! Double,
shadowL: object[_lowField!] as! Double,
open: object[_openField!] as! Double,
close: object[_closeField!] as! Double)
return entry
}
open override func calcMinMax()
{
if _cache.count == 0
{
return
}
_yMax = -DBL_MAX
_yMin = DBL_MAX
_xMax = -DBL_MAX
_xMin = DBL_MAX
for e in _cache as! [CandleChartDataEntry]
{
if e.low < _yMin
{
_yMin = e.low
}
if e.high > _yMax
{
_yMax = e.high
}
if e.x < _xMin
{
_xMin = e.x
}
if e.x > _xMax
{
_xMax = e.x
}
}
}
// MARK: - Styling functions and accessors
/// the space between the candle entries
///
/// **default**: 0.1 (10%)
fileprivate var _barSpace = CGFloat(0.1)
/// the space that is left out on the left and right side of each candle,
/// **default**: 0.1 (10%), max 0.45, min 0.0
open var barSpace: CGFloat
{
set
{
if newValue < 0.0
{
_barSpace = 0.0
}
else if newValue > 0.45
{
_barSpace = 0.45
}
else
{
_barSpace = newValue
}
}
get
{
return _barSpace
}
}
/// should the candle bars show?
/// when false, only "ticks" will show
///
/// **default**: true
open var showCandleBar: Bool = true
/// the width of the candle-shadow-line in pixels.
///
/// **default**: 3.0
open var shadowWidth = CGFloat(1.5)
/// the color of the shadow line
open var shadowColor: NSUIColor?
/// use candle color for the shadow
open var shadowColorSameAsCandle = false
/// Is the shadow color same as the candle color?
open var isShadowColorSameAsCandle: Bool { return shadowColorSameAsCandle }
/// color for open == close
open var neutralColor: NSUIColor?
/// color for open > close
open var increasingColor: NSUIColor?
/// color for open < close
open var decreasingColor: NSUIColor?
/// Are increasing values drawn as filled?
/// increasing candlesticks are traditionally hollow
open var increasingFilled = false
/// Are increasing values drawn as filled?
open var isIncreasingFilled: Bool { return increasingFilled }
/// Are decreasing values drawn as filled?
/// descreasing candlesticks are traditionally filled
open var decreasingFilled = true
/// Are decreasing values drawn as filled?
open var isDecreasingFilled: Bool { return decreasingFilled }
}
|
apache-2.0
|
24f4424b1d787e15b65cb4f8a95f0127
| 27.108108 | 187 | 0.575385 | 4.605846 | false | false | false | false |
Aishwarya-Ramakrishnan/sparkios
|
Source/TeamMembership/TeamMembership.swift
|
1
|
2903
|
// Copyright 2016 Cisco Systems 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.
import Foundation
import ObjectMapper
/// TeamMembership contents.
public struct TeamMembership: Mappable, Equatable {
/// The id of this team membership.
public var id: String?
/// The id of the team.
public var teamId: String?
/// The id of the person.
public var personId: String?
/// The email address of the person.
public var personEmail: EmailAddress?
/// The display name of the person.
public var personDisplayName: String?
/// Moderator of a team.
public var isModerator: Bool?
/// The timestamp that the team membership being created.
public var created: Date?
/// TeamMembership constructor.
///
/// - note: for internal use only.
public init?(map: Map){
}
/// TeamMembership mapping from JSON.
///
/// - note: for internal use only.
public mutating func mapping(map: Map) {
id <- map["id"]
teamId <- map["teamId"]
personId <- map["personId"]
personEmail <- (map["personEmail"], EmailTransform())
personDisplayName <- map["personDisplayName"]
isModerator <- map["isModerator"]
created <- (map["created"], CustomDateFormatTransform(formatString: "yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ"))
}
}
/// TeamMembership Equatable implementation. Check if two team memberships are equal.
public func ==(lhs: TeamMembership, rhs: TeamMembership) -> Bool {
if lhs.id == rhs.id &&
lhs.personId == rhs.personId &&
lhs.personEmail == rhs.personEmail &&
lhs.personDisplayName == rhs.personDisplayName &&
lhs.teamId == rhs.teamId &&
lhs.isModerator == rhs.isModerator &&
lhs.created == rhs.created {
return true
}
return false
}
|
mit
|
0009c2dcb5fc947a9eb917b3a75285db
| 34.839506 | 110 | 0.675164 | 4.507764 | false | false | false | false |
maazsq/Algorithms_Example
|
MergeSort/Swift/MergeSort.swift
|
11
|
2711
|
//
// Mergesort.swift
//
//
// Created by Kelvin Lau on 2016-02-03.
//
//
func mergeSort<T: Comparable>(_ array: [T]) -> [T] {
guard array.count > 1 else { return array }
let middleIndex = array.count / 2
let leftArray = mergeSort(Array(array[0..<middleIndex]))
let rightArray = mergeSort(Array(array[middleIndex..<array.count]))
return merge(leftPile: leftArray, rightPile: rightArray)
}
func merge<T: Comparable>(leftPile: [T], rightPile: [T]) -> [T] {
var leftIndex = 0
var rightIndex = 0
var orderedPile: [T] = []
if orderedPile.capacity < leftPile.count + rightPile.count {
orderedPile.reserveCapacity(leftPile.count + rightPile.count)
}
while true {
guard leftIndex < leftPile.endIndex else {
orderedPile.append(contentsOf: rightPile[rightIndex..<rightPile.endIndex])
break
}
guard rightIndex < rightPile.endIndex else {
orderedPile.append(contentsOf: leftPile[leftIndex..<leftPile.endIndex])
break
}
if leftPile[leftIndex] < rightPile[rightIndex] {
orderedPile.append(leftPile[leftIndex])
leftIndex += 1
} else {
orderedPile.append(rightPile[rightIndex])
rightIndex += 1
}
}
return orderedPile
}
/*
This is an iterative bottom-up implementation. Instead of recursively splitting
up the array into smaller sublists, it immediately starts merging the individual
array elements.
As the algorithm works its way up, it no longer merges individual elements but
larger and larger subarrays, until eventually the entire array is merged and
sorted.
To avoid allocating many temporary array objects, it uses double-buffering with
just two arrays.
*/
func mergeSortBottomUp<T>(_ a: [T], _ isOrderedBefore: (T, T) -> Bool) -> [T] {
let n = a.count
var z = [a, a] // the two working arrays
var d = 0 // z[d] is used for reading, z[1 - d] for writing
var width = 1
while width < n {
var i = 0
while i < n {
var j = i
var l = i
var r = i + width
let lmax = min(l + width, n)
let rmax = min(r + width, n)
while l < lmax && r < rmax {
if isOrderedBefore(z[d][l], z[d][r]) {
z[1 - d][j] = z[d][l]
l += 1
} else {
z[1 - d][j] = z[d][r]
r += 1
}
j += 1
}
while l < lmax {
z[1 - d][j] = z[d][l]
j += 1
l += 1
}
while r < rmax {
z[1 - d][j] = z[d][r]
j += 1
r += 1
}
i += width*2
}
width *= 2 // in each step, the subarray to merge becomes larger
d = 1 - d // swap active array
}
return z[d]
}
|
apache-2.0
|
44ad4bbed6b7d871082f138e0f00429b
| 24.575472 | 84 | 0.578015 | 3.614667 | false | false | false | false |
PureSwift/SwiftFoundation
|
Sources/SwiftFoundation/URL.swift
|
1
|
3009
|
// URL.swift
// SwiftFoundation
//
// Created by Alsey Coleman Miller on 6/29/15.
// Copyright © 2015 PureSwift. All rights reserved.
//
/**
A URL is a type that can potentially contain the location of a resource on a remote server, the path of a local file on disk, or even an arbitrary piece of encoded data.
You can construct URLs and access their parts. For URLs that represent local files, you can also manipulate properties of those files directly, such as changing the file's last modification date. Finally, you can pass URLs to other APIs to retrieve the contents of those URLs. For example, you can use the URLSession classes to access the contents of remote resources, as described in URL Session Programming Guide.
URLs are the preferred way to refer to local files. Most objects that read data from or write data to a file have methods that accept a URL instead of a pathname as the file reference. For example, you can get the contents of a local file URL as `String` by calling `func init(contentsOf:encoding) throws`, or as a `Data` by calling `func init(contentsOf:options) throws`.
*/
public struct URL {
internal let stringValue: String
/// Initialize with string.
///
/// Returns `nil` if a `URL` cannot be formed with the string (for example, if the string contains characters that are illegal in a URL, or is an empty string).
public init?(string: String) {
// TODO: Validate URL string
guard string.isEmpty == false
else { return nil }
self.init(string: string)
}
/// Returns the absolute string for the URL.
public var absoluteString: String {
return stringValue
}
}
// MARK: - Equatable
extension URL: Equatable {
public static func == (lhs: URL, rhs: URL) -> Bool {
return lhs.stringValue == rhs.stringValue
}
}
// MARK: - Hashable
extension URL: Hashable {
public func hash(into hasher: inout Hasher) {
stringValue.hash(into: &hasher)
}
}
// MARK: - CustomStringConvertible
extension URL: CustomStringConvertible {
public var description: String {
return stringValue
}
}
// MARK: - CustomDebugStringConvertible
extension URL: CustomDebugStringConvertible {
public var debugDescription: String {
return description
}
}
// MARK: - Codable
extension URL: Codable {
public init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
let string = try container.decode(String.self)
guard let url = URL(string: string) else {
throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: decoder.codingPath,
debugDescription: "Invalid URL string."))
}
self = url
}
public func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
try container.encode(stringValue)
}
}
|
mit
|
9ad5ac93d219c0c775d6b5f4b4210a0d
| 32.797753 | 416 | 0.674867 | 4.72956 | false | false | false | false |
vimeo/VimeoNetworking
|
Sources/Shared/Requests/Request+ConnectedApp.swift
|
1
|
3369
|
//
// Request+ConnectedApp.swift
// VimeoNetworking
//
// Copyright © 2019 Vimeo. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
public extension Request where ModelType == [ConnectedApp] {
/// Returns a fetch request of all connected apps for the authenticated user.
static func connectedApps() -> Request {
return Request(path: .connectedAppsURI)
}
}
public extension Request where ModelType: ConnectedApp {
/// Returns a fetch request for a single connected app.
/// - Parameter appType: The `ConnectedAppType` to fetch data for.
static func connectedApp(_ appType: ConnectedAppType) -> Request {
return Request(path: .connectedAppsURI + appType.description)
}
/// Returns a `put` request for connecting the provided app type to the current authenticated user's account.
/// - Parameters:
/// - appType: The app platform for which the connection will be established.
/// - token: An authentication token from the provided platfrom, used to establish the connection.
static func connect(to appType: ConnectedAppType, with token: String) -> Request {
let uri: String = .connectedAppsURI + appType.description
var tokenKey: String
switch appType {
case .twitter:
tokenKey = .accessTokenSecret
case .facebook, .linkedin, .youtube:
tokenKey = .authCode
}
let parameters = [tokenKey: token]
return Request(method: .put, path: uri, parameters: parameters)
}
}
public extension Request where ModelType: VIMNullResponse {
/// Returns a request to `delete` the connection to the specified app.
/// - Parameter appType: The `ConnectedAppType` to disassociate from the authenticated user.
static func deleteConnectedApp(_ appType: ConnectedAppType) -> Request {
let uri: String = .connectedAppsURI + appType.description
return Request(method: .delete, path: uri)
}
}
private extension String {
static let appType = "app_type"
static let connectedAppsURI = "/me/connected_apps/"
/// Token request parameter key for Twitter.
static let accessTokenSecret = "access_token_secret"
/// Token request parameter key for Facebook, LinkedIn, and YouTube.
static let authCode = "auth_code"
}
|
mit
|
10c61323f42bac0369920b697492b270
| 41.632911 | 113 | 0.710511 | 4.490667 | false | false | false | false |
mobilabsolutions/jenkins-ios
|
JenkinsiOS/View/JobTableViewCell.swift
|
1
|
1210
|
//
// JobTableViewCell.swift
// JenkinsiOS
//
// Created by Robert on 20.07.18.
// Copyright © 2018 MobiLab Solutions. All rights reserved.
//
import UIKit
class JobTableViewCell: UITableViewCell {
@IBOutlet var containerView: UIView!
@IBOutlet var statusView: UIImageView!
@IBOutlet var healthView: UIImageView!
@IBOutlet var nameLabel: UILabel!
@IBOutlet var arrowView: UIImageView!
override func awakeFromNib() {
super.awakeFromNib()
containerView.layer.borderColor = Constants.UI.paleGreyColor.cgColor
containerView.layer.borderWidth = 1
}
func setup(with jobResult: JobListResult) {
nameLabel.text = jobResult.name
if let color = jobResult.color {
statusView?.image = UIImage(named: color.rawValue + "Circle")
}
if let icon = jobResult.data.healthReport.first?.iconClassName {
healthView.image = UIImage(named: icon)
} else if jobResult.color == .folder {
healthView.image = UIImage(named: "icon-health-folder")
} else {
healthView.image = UIImage(named: "icon-health-unknown")
}
containerView.layer.cornerRadius = 5
}
}
|
mit
|
3640b4a5aa69053d086fe7744d914b6f
| 28.487805 | 76 | 0.655087 | 4.364621 | false | false | false | false |
GitHubOfJW/JavenKit
|
JavenKit/JWAlertViewController/View/JWActionButton.swift
|
1
|
1049
|
//
// JWActionButton.swift
// JWAlertViewController_Demo
//
// Created by 朱建伟 on 2016/12/17.
// Copyright © 2016年 zhujianwei. All rights reserved.
//
import UIKit
class JWActionButton: UIButton {
let lineView:UIView = UIView()
var lineMargin:CGFloat = 0
//初始化
override init(frame: CGRect) {
super.init(frame: frame)
lineView.backgroundColor = UIColor(white: 0.85, alpha: 1)
addSubview(lineView)
}
override func layoutSubviews() {
super.layoutSubviews()
let lineW:CGFloat = self.bounds.size.width - 2 * self.lineMargin
let lineX:CGFloat = (self.bounds.size.width - lineW)/2
let lineY:CGFloat = 0
let lineH:CGFloat = 0.5
self.lineView.frame = CGRect(x: lineX, y: lineY, width: lineW, height: lineH)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
|
mit
|
f425d8f10699296fbf8a2b6cf22d6849
| 20.541667 | 85 | 0.571567 | 4.169355 | false | false | false | false |
SwiftORM/StORM
|
Sources/StORM/StORMRow.swift
|
1
|
1224
|
//
// StORMRow.swift
// StORM
//
// Created by Jonathan Guthrie on 2016-09-23.
//
//
import PerfectLib
fileprivate enum idTypeList {
case String
case Int
case UUID
}
/// The foundation container for a result row.
open class StORMRow {
/// The idInt is the container for an integer ID value.
var idInt = 0
/// The idUUID is the container for a UUID ID value.
var idUUID: UUID = UUID()
/// The idString is the container for a textual ID value.
var idString = ""
fileprivate var idType: idTypeList = .Int
/// The container for the row's data.
public var data = Dictionary<String, Any>()
/// Empty public initializer.
public init() {}
/// Used to set the id value of the row if an integer
public func id(_ val: Int) {
idType = .Int
idInt = val
}
/// Used to set the id value of the row if a UUID
public func id(_ val: UUID) {
idType = .UUID
idUUID = val
}
/// Used to set the id value of the row if a string
public func id(_ val: String) {
idType = .String
idString = val
}
/// Retrieves the value of the ID as set.
public func id() -> Any {
switch idType {
case .Int:
return idInt
case .UUID:
return idUUID
default:
return idString
}
}
}
|
apache-2.0
|
c00031e951b1302d380b19902a697cc6
| 17.268657 | 58 | 0.647059 | 3.029703 | false | false | false | false |
jpsachse/mensa-griebnitzsee
|
MensaKit/Menu.swift
|
1
|
4521
|
//
// Menu.swift
// Mensa Griebnitzsee
//
// Copyright © 2017 Jan Philipp Sachse. All rights reserved.
//
import Foundation
public struct MenuDish {
public let name: String
public let category: String
public let notes: [String]
public var description: String {
get {
return category + ": " + name + " (" + notes.joined(separator: ", ") + ")"
}
}
}
public struct MenuEntry {
public let date: Date
public let closed: Bool
public let dishes: [MenuDish]
}
public class Menu: NSObject, NSCoding {
public var entries: [MenuEntry] = []
private let dateFormatter = DateFormatter()
public override init() {
super.init()
dateFormatter.dateFormat = "yyyy-MM-dd"
}
public func encode(with aCoder: NSCoder) {
aCoder.encode(entries.count, forKey: "numberOfEntries")
for entryIndex in 0..<entries.count {
let entry = entries[entryIndex]
aCoder.encode(entry.date, forKey: "entry\(entryIndex)Date")
aCoder.encode(entry.closed, forKey: "entry\(entryIndex)Closed")
aCoder.encode(entry.dishes.count, forKey: "entry\(entryIndex)NumberOfDishes")
for dishIndex in 0..<entry.dishes.count {
let dish = entry.dishes[dishIndex]
aCoder.encode(dish.name, forKey: "entry\(entryIndex)Dish\(dishIndex)Name")
aCoder.encode(dish.category, forKey: "entry\(entryIndex)Dish\(dishIndex)Category")
aCoder.encode(dish.notes.count, forKey: "entry\(entryIndex)Dish\(dishIndex)NumberOfNotes")
for noteIndex in 0..<dish.notes.count {
let note = dish.notes[noteIndex]
aCoder.encode(note, forKey: "entry\(entryIndex)Dish\(dishIndex)Note\(noteIndex)")
}
}
}
}
public required convenience init?(coder aDecoder: NSCoder) {
self.init()
let numberOfEntries = aDecoder.decodeInteger(forKey: "numberOfEntries")
for entryIndex in 0..<numberOfEntries {
guard let date = aDecoder.decodeObject(forKey: "entry\(entryIndex)Date") as? Date else { break }
let closed = aDecoder.decodeBool(forKey: "entry\(entryIndex)Closed")
let numberOfDishes = aDecoder.decodeInteger(forKey: "entry\(entryIndex)NumberOfDishes")
var dishes: [MenuDish] = []
for dishIndex in 0..<numberOfDishes {
let nameKey = "entry\(entryIndex)Dish\(dishIndex)Name"
let categoryKey = "entry\(entryIndex)Dish\(dishIndex)Category"
let numberOfNotesKey = "entry\(entryIndex)Dish\(dishIndex)NumberOfNotes"
let numberOfNotes = aDecoder.decodeInteger(forKey: numberOfNotesKey)
guard let name = aDecoder.decodeObject(forKey: nameKey) as? String,
let category = aDecoder.decodeObject(forKey: categoryKey) as? String else {
break
}
var notes: [String] = []
for noteIndex in 0..<numberOfNotes {
let noteKey = "entry\(entryIndex)Dish\(dishIndex)Note\(noteIndex)"
if let note = aDecoder.decodeObject(forKey: noteKey) as? String {
notes.append(note)
}
}
dishes.append(MenuDish(name: name, category: category, notes: notes))
}
entries.append(MenuEntry(date: date, closed: closed, dishes: dishes))
}
}
public func addEntry(loadedData: Data?, at date: String, closed: Bool) {
guard let date = dateFormatter.date(from: date) else {
return
}
var dishes: [MenuDish] = []
if let dishData = loadedData {
do {
let dishObject = try JSONSerialization.jsonObject(with: dishData, options: .allowFragments)
if let dishInfos = dishObject as? [[String:Any]] {
for dishInfo in dishInfos {
if var name = dishInfo["name"] as? String, let category = dishInfo["category"] as? String,
let notes = dishInfo["notes"] as? [String] {
do {
let regex = try NSRegularExpression(pattern: "\\s+", options: [])
name = regex.stringByReplacingMatches(in: name,
options: [],
range: NSMakeRange(0, name.count),
withTemplate: " ")
} catch {}
let dish = MenuDish(name: name, category: category, notes: notes)
dishes.append(dish)
}
}
}
} catch {}
}
let entry = MenuEntry(date: date, closed: closed, dishes: dishes)
entries.append(entry)
}
}
|
mit
|
64779a8e5315b8617b435e3952bcd1e5
| 37.305085 | 104 | 0.610398 | 4.276254 | false | false | false | false |
jussiyu/bus-stop-ios-swift
|
BusStop/model/Stop.swift
|
1
|
3163
|
// Copyright (c) 2015 Solipaste Oy
//
// 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 CoreLocation
import SwiftyJSON
import XCGLogger
import RealmSwift
//
// MARK: - Stop
//
public class Stop : Object {
public dynamic var id: String = ""
public dynamic var name: String = ""
public dynamic var latitude: CLLocationDegrees = 0.0
public dynamic var longitude: CLLocationDegrees = 0.0
public dynamic var location: CLLocation {
get {
return CLLocation(latitude: latitude, longitude: longitude)
}
set {
latitude = newValue.coordinate.latitude
longitude = newValue.coordinate.longitude
}
}
public dynamic var favorite = false
public convenience init(id: String, name: String, location: CLLocation? = nil) {
self.init()
self.id = id
self.name = name
latitude = location?.coordinate.latitude ?? 0.0
longitude = location?.coordinate.longitude ?? 0.0
}
public func distanceFromUserLocation(userLocation: CLLocation) -> String {
if latitude != 0 && longitude != 0 &&
userLocation.coordinate.latitude != 0 && userLocation.coordinate.longitude != 0{
let dist = location.distanceFromLocation(userLocation)
if dist == 0 {
return NSLocalizedString("Exactly at your location", comment: "")
} else if dist < 1000 {
return NSString.localizedStringWithFormat(
NSLocalizedString("%d meter(s) from your location", comment: "distance in meters"), lround(dist)) as String
} else {
return NSString.localizedStringWithFormat(
NSLocalizedString("%d km(s) from your location", comment: "distance in km"), dist/1000) as String
}
} else {
return NSLocalizedString("--", comment: "unknown distance between user and the vehicle")
}
}
// MARK: - Realm Object class overrides
override public class func primaryKey() -> String? {
return "id"
}
override public class func ignoredProperties() -> [String] {
return ["location"]
}
// MARK: - Printable implementation
override public var description: String {
return name
}
}
|
mit
|
8be98f4594631c6de662b32fe9a6b5f5
| 34.144444 | 117 | 0.704711 | 4.720896 | false | false | false | false |
sky15179/swift-learn
|
data-Base-exercises/data-Base-exercises/Paser/Parser.swift
|
1
|
7311
|
//
// Parser.swift
// data-Base-exercises
//
// Created by 王智刚 on 2017/6/29.
// Copyright © 2017年 王智刚. All rights reserved.
//
import Foundation
//1.确定解析器的构造,由一个解析函数构成
struct Parser<A>{
typealias Stream = String.CharacterView
let parse:(Stream)-> (A,Stream)?
}
extension Parser{
//2.解析器的基本能力,这里只考虑解析字符串,方便查看结果的函数封装,对多个的处理,类型转换的基本能力
/// 将解析器结果重新包装成string,方便查看结果
///
/// - Parameter string: 要解析的zifuc
/// - Returns: 元组结果:(符合条件的字符串,剩余的字符串)
func run(_ string:String) -> (A,String)? {
guard let (result,remainder) = parse(string.characters) else { return nil}
return (result,String(remainder))
}
/// 多次执行解析器,并将结果封装到一个数组,有问题:对空字符串求解会崩溃
var many:Parser<[A]>{
return Parser<[A]>{ input in
var result:[A] = []
var remainder = input
while let (element,newRemainder) = self.parse(remainder) {
result.append(element)
remainder = newRemainder
}
return (result,remainder)
}
}
/// 函子操作,支持类结构体的改造从A类型->T类型
/// 应用:为了完成对拆分的数字字符串数组合并成一个完整的整数类型
/// - Parameter transform: 类型转换函数
/// - Returns: 新的类结构体的解析器
func map<T>(_ transform:@escaping (A)->T) -> Parser<T> {
return Parser<T>{ input in
guard let (result,remainder) = self.parse(input) else{ return nil }
return (transform(result),remainder)
}
}
//3.处理多个解析器的能力,顺序解析每个解析器的结果
/// 顺序合并解析器
/// 问题:存在不断嵌套元组的问题,因为每个解析器的返回结果类型不同
/// 解决方法:元组,数组,柯里化函数:“与其先将它们包裹在一个嵌套的多元组里然后再去计算,不如依次向每个解析器的结果传入一个可执行的函数,倘若如此做,我们就可以避免这个问题。”,这里的最优解就是柯里化函数
/// - Parameter other: 待合并的解析器
/// - Returns: 一个通过元组封装两个解析器结果的新的解析器
func follow<T>(by other:Parser<T>) -> Parser<(A,T)> {
return Parser<(A,T)>{ input in
guard let (result,remainder) = self.parse(input) else { return nil}
guard let (result2,remainder2) = other.parse(remainder) else { return nil}
return ((result,result2),remainder2)
}
}
//5.更多的解析运算支持,或,定义或运算符
/// 或运算解析器
///
/// - Parameter other: <#other description#>
/// - Returns: <#return value description#>
func or(_ other:Parser<A>) -> Parser<A> {
return Parser<A>{ input in
return self.parse(input) ?? other.parse(input)
}
}
//6.优化现有有问题函数,many在处理空字符串的时候会有问题,可选解析器的提供
/// 先执行一次,再通过柯里化合并结果,要好好理解curry 和 运算符的意义
var many1:Parser<[A]>{
return curry({ [$0] + $1 })<^>self<*>self.many
}
var optional:Parser<A?>{
return Parser<A?>{ input in
guard let (result,remainder) = self.parse(input) else {
return (nil,input)
}
return (result,remainder)
}
}
}
//4.运算符组合复杂功能,发现有重复的处理部分,可以优化抽象出一个顺序解析运算符,这也是一个适用函子
// let multiplication3 = p1.follow(by: character{$0 == "*"}).map{ f,op in f(op) }.follow(by: integer).map{ f,x in f(x) }
precedencegroup SequencePrecedence{
associativity: left
higherThan:AdditionPrecedence
}
infix operator <*>:SequencePrecedence
infix operator <^>:SequencePrecedence
infix operator *>:SequencePrecedence
infix operator <*:SequencePrecedence
infix operator <|>:SequencePrecedence
/// 顺序解析器运算符,简化柯里化后的函数,适用函子的一个典型
///
/// - Parameters:
/// - lhs: A->B 的柯里化转换函数
/// - rhs: 原解析器
/// - Returns: 转换成B的解析器
func <*><A,B>(lhs:Parser<(A)->B>,rhs:Parser<A>) -> Parser<B> {
return lhs.follow(by: rhs).map{ f,x in f(x)}
}
/// 简化顺序解析器的map操作
/// integer.map(curriedMultiply)
/// - Parameters:
/// - lhs: 转换函数
/// - rhs: 原解析器
/// - Returns: B解析器
func <^><A,B>(lhs:@escaping (A)->B,rhs:Parser<A>) -> Parser<B> {
return rhs.map(lhs)
}
/// 合并解析器,只保留左边的解析器结果
///
/// - Parameters:
/// - lhs: <#lhs description#>
/// - rhs: <#rhs description#>
/// - Returns: <#return value description#>
func <*<A,B>(lhs:Parser<A>,rhs:Parser<B>) -> Parser<A> {
return curry({ x,_ in x})<^>lhs<*>rhs
}
/// 合并解析器,只保留右边的解析器结果
///
/// - Parameters:
/// - lhs: <#lhs description#>
/// - rhs: <#rhs description#>
/// - Returns: <#return value description#>
func *><A,B>(lhs:Parser<A>,rhs:Parser<B>) -> Parser<B> {
return curry({ $1 })<^>lhs<*>rhs
}
/// 两个解析器的或结果
///
/// - Parameters:
/// - lhs: 优先
/// - rhs: 其次
/// - Returns: <#return value description#>
func <|><A>(lhs:Parser<A>,rhs:Parser<A>) -> Parser<A> {
return lhs.or(rhs)
}
/// 处理一般的字符串解析,但是只能处理单个字符串的解析器
///
/// - Parameter condition: 解析条件
/// - Returns: 解析器
func character(condition:@escaping (Character)->Bool) -> Parser<Character> {
return Parser<Character> { input in
guard let char = input.first, condition(char) else { return nil}
return (char,input.dropFirst())
}
}
/// 柯里化合并解析结果
///
/// - Parameter x: <#x description#>
/// - Returns: <#return value description#>
func curriedMultiply(_ x:Int) -> (Character) -> (Int) -> Int {
return {
op in
return {
y in
return x * y
}
}
}
func lazy<A>(_ parser:@escaping @autoclosure ()->Parser<A>) -> Parser<A> {
return Parser<A>{
parser().parse($0)
}
}
/// 匹配特定字符串
///
/// - Parameter string: <#string description#>
/// - Returns: <#return value description#>
func string(_ string:String) -> Parser<String> {
return Parser<String>{ input in
var remainder = input
for c in string.characters {
let parser = character { $0 == c }
guard let (_, newRemainder) = parser.parse(remainder) else { return nil }
remainder = newRemainder
}
return (string, remainder)
}
}
extension Parser{
/// 忽略括号
var parenthesized:Parser<A>{
return string("(")*>self<*string(")")
}
}
let digit = character{ CharacterSet.decimalDigits.contains($0) }
let integer = digit.many1.map{ Int(String($0))! }
let capitalLetter = character{ CharacterSet.uppercaseLetters.contains($0) }
|
apache-2.0
|
ef297514fad9363b02f6e6c859efa90d
| 25.192982 | 127 | 0.589417 | 3.179979 | false | false | false | false |
dannys42/DTSImage
|
Example/DTSImageExample/DTSImageExample/CollectionViewController.swift
|
1
|
7428
|
//
// CollectionViewController.swift
// DTSImageExample
//
// Created by Danny Sung on 12/02/2016.
// Copyright © 2016 Sung Heroes LLC. All rights reserved.
//
import UIKit
import DTSImage
private let reuseIdentifier = "imageCell"
class CollectionViewController: UICollectionViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Register cell classes
// self.collectionView!.register(UICollectionViewCell.self, forCellWithReuseIdentifier: reuseIdentifier)
// Do any additional setup after loading the view.
guard let originalImage = UIImage(named: "SmallImage") else { return }
self.originalImage = originalImage
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
self.rgbafScaled_0_5 = DTSImageRGBAF(image: self.originalImage, scaleFactor: 0.5)?.toUIImage()
self.timerHandler()
let timer = Timer(timeInterval: 0.1, target: self, selector: #selector(timerHandler), userInfo: nil, repeats: true)
RunLoop.current.add(timer, forMode: .commonModes)
}
override func viewWillDisappear(_ animated: Bool) {
// self.timer = nil
}
// MARK: UICollectionViewDataSource
override func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 5
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath)
// Configure the cell
let imageCell = cell as! ImageCell
self.setupImageCell(imageCell, cellForItemAt: indexPath)
return cell
}
func setupImageCell(_ cell: ImageCell, cellForItemAt indexPath: IndexPath) {
let backgroundColor = UIColor(white: 0.9, alpha: 1.0)
switch indexPath.row {
case 0:
cell.titleLabel.text = "Original Image"
cell.imageView.image = self.originalImage
cell.backgroundColor = backgroundColor
case 1:
cell.titleLabel.text = "RGBA8"
cell.imageView.image = self.rgba8Image
cell.backgroundColor = backgroundColor
case 2:
cell.titleLabel.text = "RGBAF"
cell.imageView.image = self.rgbafImage
cell.backgroundColor = backgroundColor
case 3:
cell.titleLabel.text = "RGBAF w/ mask"
cell.imageView.image = self.rgbafImageWithMask
cell.backgroundColor = backgroundColor
case 4:
cell.titleLabel.text = "RGBAF x0.5"
cell.imageView.image = self.rgbafScaled_0_5
cell.backgroundColor = backgroundColor
default:
cell.titleLabel.text = "(unknown)"
cell.backgroundColor = UIColor.orange
}
}
// MARK: UICollectionViewDelegate
/*
// Uncomment this method to specify if the specified item should be highlighted during tracking
override func collectionView(_ collectionView: UICollectionView, shouldHighlightItemAt indexPath: IndexPath) -> Bool {
return true
}
*/
/*
// Uncomment this method to specify if the specified item should be selected
override func collectionView(_ collectionView: UICollectionView, shouldSelectItemAt indexPath: IndexPath) -> Bool {
return true
}
*/
/*
// Uncomment these methods to specify if an action menu should be displayed for the specified item, and react to actions performed on the item
override func collectionView(_ collectionView: UICollectionView, shouldShowMenuForItemAt indexPath: IndexPath) -> Bool {
return false
}
override func collectionView(_ collectionView: UICollectionView, canPerformAction action: Selector, forItemAt indexPath: IndexPath, withSender sender: Any?) -> Bool {
return false
}
override func collectionView(_ collectionView: UICollectionView, performAction action: Selector, forItemAt indexPath: IndexPath, withSender sender: Any?) {
}
*/
// MARK: Private methods
var originalImage: UIImage!
var rgba8Image: UIImage?
var rgbafImage: UIImage?
var rgbafImageWithMask: UIImage?
var rgbafScaled_0_5: UIImage?
// A simple way to make changes, allowing for visual inspection of changes
func timerHandler() {
DispatchQueue.main.async {
self.updateImages()
}
}
var offset: Int = 0
func updateImages() {
guard let originalImage = self.originalImage else { return }
self.rgba8Image = self.createRGBA8Image(offset: self.offset)?.toUIImage()
if let rgbafImage = self.createRGBAFImage(offset: self.offset) {
self.rgbafImage = rgbafImage.toUIImage()
self.rgbafImageWithMask = self.createRGBAFImageWithMask(floatImage: rgbafImage,
offset: self.offset).toUIImage()
}
self.collectionView!.reloadData()
self.offset += 1
if self.offset >= Int(originalImage.size.height/2) || self.offset >= Int(originalImage.size.width/2) {
self.offset = 0
}
}
// MARK: Image Generators
func createRGBA8Image(offset: Int) -> DTSImageRGBA8? {
guard let originalImage = self.originalImage else { return nil }
guard var dtsImage = DTSImageRGBA8(image: originalImage) else { print("Error creating image"); return nil }
let red = DTSPixelRGBA8(red: 1.0, green: 0.5, blue: 0.5, alpha: 1.0)
for y in 0..<dtsImage.height {
dtsImage.setPixel(x: y - offset, y: y + offset, pixel: red)
}
return dtsImage
}
func createRGBAFImage(offset: Int) -> DTSImageRGBAF? {
guard let originalImage = self.originalImage else { return nil }
guard var dtsImage = DTSImageRGBAF(image: originalImage) else { print("Error creating image"); return nil }
let blue = DTSPixelRGBAF(red: 0.2, green: 0.15, blue: 1.0, alpha: 1.0)
dtsImage.setPixel(x: 0, y: 0, pixel: blue)
dtsImage.setPixel(x: 1, y: 1, pixel: blue)
for y in 0..<dtsImage.width {
dtsImage.setPixel(x: y + offset, y: y - offset, pixel: blue)
}
return dtsImage
}
func createFloatMask(offset: Int, width: Int, height: Int) -> DTSImagePlanarF {
var dtsImage = DTSImagePlanarF(width: width, height: height)
let white = DTSPixelF(1)
for x in width/10 ..< width * 9 / 10 {
for y in 0..<30 {
dtsImage.setPixel(x: x, y: y+offset, pixel: white)
}
}
return dtsImage
}
func createRGBAFImageWithMask(floatImage: DTSImageRGBAF, offset: Int) -> DTSImageRGBAF {
let mask = createFloatMask(offset: offset*2, width: floatImage.width, height: floatImage.height)
let newImage = floatImage.applying(mask: mask)
return newImage
}
}
|
mit
|
22de4e05d1e349e58755cf5a3fde29f5
| 35.406863 | 170 | 0.641039 | 4.724555 | false | false | false | false |
EgeTart/MedicineDMW
|
DWM/SettingController.swift
|
1
|
2615
|
//
// SettingController.swift
// DWM
//
// Created by MacBook on 9/25/15.
// Copyright © 2015 EgeTart. All rights reserved.
//
import UIKit
class SettingController: UIViewController {
@IBOutlet weak var settingTableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
self.title = "设置"
settingTableView.tableFooterView = UIView()
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
self.navigationController?.navigationBarHidden = false
self.navigationController?.navigationBar.backItem?.title = ""
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
self.navigationController?.navigationBarHidden = true
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
extension SettingController: UITableViewDataSource {
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 2
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 1
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var reusedID = ""
if indexPath.section == 0 {
reusedID = "modifyCell"
}
else {
reusedID = "receiveCell"
}
let cell = tableView.dequeueReusableCellWithIdentifier(reusedID, forIndexPath: indexPath) as UITableViewCell
return cell
}
}
extension SettingController: UITableViewDelegate {
func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
if section == 0 {
return 0
}
return 8
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 40
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
if indexPath.section == 0 {
self.performSegueWithIdentifier("modify", sender: self)
}
}
}
|
mit
|
f228327f8beda7606f594ed856b7bff4
| 25.907216 | 116 | 0.638697 | 5.553191 | false | false | false | false |
CD1212/Doughnut
|
Pods/FeedKit/Sources/FeedKit/Models/Namespaces/Syndication/SyndicationNamespace.swift
|
2
|
2967
|
//
// SyndicationNamespace.swift
//
// Copyright (c) 2017 Nuno Manuel Dias
//
// 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
/// Provides syndication hints to aggregators and others picking up this RDF Site
/// Summary (RSS) feed regarding how often it is updated. For example, if you
/// updated your file twice an hour, updatePeriod would be "hourly" and
/// updateFrequency would be "2". The syndication module borrows from Ian Davis's
/// Open Content Syndication (OCS) directory format. It supercedes the RSS 0.91
/// skipDay and skipHour elements.
///
/// See http://web.resource.org/rss/1.0/modules/syndication/
public class SyndicationNamespace {
/// Describes the period over which the channel format is updated. Acceptable
/// values are: hourly, daily, weekly, monthly, yearly. If omitted, daily is
/// assumed.
public var syUpdatePeriod: SyndicationUpdatePeriod?
/// Used to describe the frequency of updates in relation to the update period.
/// A positive integer indicates how many times in that period the channel is
/// updated. For example, an updatePeriod of daily, and an updateFrequency of
/// 2 indicates the channel format is updated twice daily. If omitted a value
/// of 1 is assumed.
public var syUpdateFrequency: Int?
/// Defines a base date to be used in concert with updatePeriod and
/// updateFrequency to calculate the publishing schedule. The date format takes
/// the form: yyyy-mm-ddThh:mm
public var syUpdateBase: Date?
}
// MARK: - Equatable
extension SyndicationNamespace: Equatable {
public static func ==(lhs: SyndicationNamespace, rhs: SyndicationNamespace) -> Bool {
return
lhs.syUpdatePeriod == rhs.syUpdatePeriod &&
lhs.syUpdateFrequency == rhs.syUpdateFrequency &&
lhs.syUpdateBase == rhs.syUpdateBase
}
}
|
gpl-3.0
|
9184efc4ece6818cd8d6088af173c72c
| 43.283582 | 89 | 0.721267 | 4.34407 | false | false | false | false |
calkinssean/TIY-Assignments
|
Day 39/matchbox20FanClub/matchbox20FanClub/ViewController.swift
|
1
|
4915
|
//
// ViewController.swift
// matchbox20FanClub
//
// Created by Sean Calkins on 3/24/16.
// Copyright © 2016 Sean Calkins. All rights reserved.
//
import UIKit
import Firebase
class ViewController: UIViewController {
// var usersArray = [User]()
var eventsArray = [Event]()
var timeSlotArray = [TimeSlot]()
var userRef = Firebase(url: "https://matchbox20fanclub.firebaseio.com/users")
var eventRef = Firebase(url: "https://matchbox20fanclub.firebaseio.com/events")
var timeSlotRef = Firebase(url: "https://matchbox20fanclub.firebaseio.com/timeslot")
override func viewDidLoad() {
super.viewDidLoad()
observeUsers()
observeEvents()
observeTimeSlots()
// seedTimeSlot()
// seedUser()
// seedEvent()
}
func seedTimeSlot() {
let t = TimeSlot()
let formatter = NSDateFormatter()
formatter.dateFormat = "MMM/dd/yyyy"
if let created = formatter.dateFromString("Apr/20/1969") {
t.startDate = created
}
if let endDate = formatter.dateFromString("Jul/18/2016") {
t.endDate = endDate
}
t.name = "9:15"
t.saveTimeslot()
}
// func seedUser() {
//
// let u = User()
// let formatter = NSDateFormatter()
// formatter.dateFormat = "MMM/dd/yyyy"
// if let created = formatter.dateFromString("Dec/21/1969") {
// u.created = created
// }
//
// u.email = "[email protected]"
// u.password = "coolGuyPassword"
// u.save()
//
// }
func seedEvent() {
let e = Event()
let formatter = NSDateFormatter()
formatter.dateFormat = "MMM/dd/yyyy"
if let created = formatter.dateFromString("Apr/20/1969") {
e.startDate = created
}
if let endDate = formatter.dateFromString("Jul/18/2016") {
e.endDate = endDate
}
e.name = "Coachella"
e.genre = "Trip Hop"
e.save()
}
func observeUsers() {
// Add observer for Events
self.timeSlotRef.observeEventType(.Value, withBlock: { snapshot in
print(snapshot.value)
// self.usersArray.removeAll()
if let snapshots = snapshot.children.allObjects as? [FDataSnapshot] {
for snap in snapshots {
if let dict = snap.value as? [String: AnyObject] {
let key = snap.key
let timeSlot = TimeSlot(key: key, dict: dict)
self.timeSlotArray.insert(timeSlot, atIndex: 0)
print(self.timeSlotArray.count)
}
}
}
})
}
func observeTimeSlots() {
// Add observer for Events
self.userRef.observeEventType(.Value, withBlock: { snapshot in
print(snapshot.value)
//self.usersArray.removeAll()
if let snapshots = snapshot.children.allObjects as? [FDataSnapshot] {
for snap in snapshots {
if let dict = snap.value as? [String: AnyObject] {
let key = snap.key
//let user = User(key: key, dict: dict)
// Add the event to our eventsArray
//self.usersArray.insert(user, atIndex: 0)
// print(self.usersArray.count)
}
}
}
})
}
func observeEvents() {
// Add observer for Events
self.eventRef.observeEventType(.Value, withBlock: { snapshot in
print(snapshot.value)
self.eventsArray.removeAll()
if let snapshots = snapshot.children.allObjects as? [FDataSnapshot] {
for snap in snapshots {
if let dict = snap.value as? [String: AnyObject] {
let key = snap.key
let event = Event(key: key, dict: dict)
// Add the event to our eventsArray
self.eventsArray.insert(event, atIndex: 0)
print(self.eventsArray.count)
}
}
}
})
}
}
|
cc0-1.0
|
bc4b05bc908d1643eb5aa3ff8b2ff79c
| 27.404624 | 88 | 0.45584 | 5.189018 | false | false | false | false |
hooman/swift
|
test/stdlib/MultipliedFullWidth.swift
|
13
|
6824
|
//===--- MultipliedFullWidth.swift ----------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2019 - 2020 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
// RUN: %target-run-simple-swift
// REQUIRES: executable_test
// UNSUPPORTED: back_deployment_runtime
import StdlibUnittest
var tests = TestSuite("MultipliedFullWidth")
func testCase<T: FixedWidthInteger>(
_ x: T, _ y: T, high: T, low: T.Magnitude, line: UInt = #line
) {
let result = x.multipliedFullWidth(by: y)
expectEqual(high, result.high, line: line)
expectEqual(low, result.low, line: line)
}
func specialValues<T: FixedWidthInteger & SignedInteger>(_ type: T.Type) {
let umin = T.Magnitude(truncatingIfNeeded: T.min)
testCase(T.min, .min, high: -(.min >> 1), low: 0)
testCase(T.min, -1, high: 0, low: umin)
testCase(T.min, 0, high: 0, low: 0)
testCase(T.min, 1, high: -1, low: umin)
testCase(T.min, .max, high: .min >> 1, low: umin)
testCase(T(-1), .min, high: 0, low: umin)
testCase(T(-1), -1, high: 0, low: 1)
testCase(T(-1), 0, high: 0, low: 0)
testCase(T(-1), 1, high: -1, low: .max)
testCase(T(-1), .max, high: -1, low: umin + 1)
testCase(T(0), .min, high: 0, low: 0)
testCase(T(0), -1, high: 0, low: 0)
testCase(T(0), 0, high: 0, low: 0)
testCase(T(0), 1, high: 0, low: 0)
testCase(T(0), .max, high: 0, low: 0)
testCase(T(1), .min, high: -1, low: umin)
testCase(T(1), -1, high: -1, low: .max)
testCase(T(1), 0, high: 0, low: 0)
testCase(T(1), 1, high: 0, low: 1)
testCase(T(1), .max, high: 0, low: .max >> 1)
testCase(T.max, .min, high: .min >> 1, low: umin)
testCase(T.max, -1, high: -1, low: umin + 1)
testCase(T.max, 0, high: 0, low: 0)
testCase(T.max, 1, high: 0, low: .max >> 1)
testCase(T.max, .max, high: (.max >> 1), low: 1)
}
func specialValues<T: FixedWidthInteger & UnsignedInteger>(_ type: T.Type) {
testCase(T(0), 0, high: 0, low: 0)
testCase(T(0), 1, high: 0, low: 0)
testCase(T(0), .max, high: 0, low: 0)
testCase(T(1), 0, high: 0, low: 0)
testCase(T(1), 1, high: 0, low: 1)
testCase(T(1), .max, high: 0, low: .max)
testCase(T.max, 0, high: 0, low: 0)
testCase(T.max, 1, high: 0, low: .max)
testCase(T.max, .max, high: .max-1, low: 1)
}
tests.test("Special Values") {
specialValues(Int.self)
specialValues(Int64.self)
specialValues(Int32.self)
specialValues(Int16.self)
specialValues(Int8.self)
specialValues(UInt.self)
specialValues(UInt64.self)
specialValues(UInt32.self)
specialValues(UInt16.self)
specialValues(UInt8.self)
}
tests.test("Random Values") {
// Some extra coverage for the 64b integers, since they are the only users
// of the default implementation (only on 32b systems):
testCase(Int64(-5837700935641288840), -1537421853862307457, high: 486536212510185592, low: 3055263144559363208)
testCase(Int64(1275671358463268836), 7781435829978284036, high: 538119614841437377, low: 14789118443021950864)
testCase(Int64(4911382318934676967), -5753361984332212917, high: -1531812888571062585, low: 1722298197364104621)
testCase(Int64(6581943526282064299), -8155192887281934825, high: -2909837032245044682, low: 16706127436327993437)
testCase(Int64(4009108071534959395), 7605188192539249328, high: 1652867370329384990, low: 3839516780320392720)
testCase(Int64(-1272471934452731280), -7713709059189882656, high: 532098144210826160, low: 4919265615377605120)
testCase(Int64(-1290602245486355209), -6877877092931971073, high: 481201646472028302, low: 4015257672509033225)
testCase(Int64(1966873427191941886), -7829903732960672311, high: -834858960925259072, low: 12998587081554941806)
testCase(Int64(5459471085932887725), 7323207134727813062, high: 2167365549637832126, low: 5826569093894448334)
testCase(Int64(-5681348775805725880), -6546051581806832250, high: 2016095739825622823, low: 7531931343377498032)
testCase(Int64(3528630718229643203), 6780383198781339163, high: 1297002242834103876, low: 16845851682892995473)
testCase(Int64(4386302929483327645), 756139473360675718, high: 179796324698125913, low: 13652654049648998702)
testCase(Int64(-2864416372170195291), 5089997120359086926, high: -790376395292167927, low: 8341529919881354566)
testCase(Int64(-252886279681789793), 1113918432442210295, high: -15270699648874904, low: 4582052466224525929)
testCase(Int64(-7821806154093904666), -678157520322455918, high: 287553003647030877, low: 6476241133902266156)
testCase(Int64(-7739162216163589826), 3946867172269483361, high: -1655871907247741938, low: 13863106094322986622)
testCase(UInt64(4052776605025255999), 17841868768407320997, high: 3919884617339462744, low: 486827993115916699)
testCase(UInt64(6242835766066895539), 14960190906716810460, high: 5062899690398282642, low: 14718350117826688468)
testCase(UInt64(17427627038899386484), 13127734187148388607, high: 12402473540330496943, low: 11581729162526677900)
testCase(UInt64(14992872905705044844), 12933105414992193421, high: 10511578899141219143, low: 7252341782600986236)
testCase(UInt64(12642327504267244590), 10708397907431293358, high: 7338914274020844379, low: 8873679764824466756)
testCase(UInt64(18257718462988034339), 17327659287939371125, high: 17150101049683916791, low: 14387647780301477119)
testCase(UInt64(5589411463208969260), 14342285504591657788, high: 4345749834640583520, low: 12301233398332628560)
testCase(UInt64(14319626538136147986), 2140855187369381019, high: 1661878466620705928, low: 2387587391530298086)
testCase(UInt64(12737453267169023056), 10991462038848276938, high: 7589590526017326520, low: 4333382898129426208)
testCase(UInt64(13832741301927421318), 7713698894698105596, high: 5784305396386691701, low: 6880744869607156712)
testCase(UInt64(5299309970076755930), 12147554660789977612, high: 3489702967025088672, low: 8435073470527345208)
testCase(UInt64(3775627568330760013), 12573993794040378591, high: 2573609598696611841, low: 11258650814777796627)
testCase(UInt64(10163828939432769169), 11406425048812406036, high: 6284737975620258563, low: 8064735036375816276)
testCase(UInt64(10553402338235046132), 16330771020588292162, high: 9342851854245941300, low: 7535126182307876584)
testCase(UInt64(17113612905570890777), 11972779332523394977, high: 11107516322766487141, low: 955396679557657273)
testCase(UInt64(10933450006210087838), 18204962163032170108, high: 10790145018498752040, low: 692054466472649864)
}
runAllTests()
|
apache-2.0
|
c56ee314b0facd3cface854473c0784d
| 52.3125 | 117 | 0.73432 | 2.702574 | false | true | false | false |
powerytg/Accented
|
Accented/UI/Details/Sections/DetailDescriptionSectionView.swift
|
1
|
12218
|
//
// DetailDescriptionSectionView.swift
// Accented
//
// Essential info section in detail page, consists the photo title, description and timestamp
//
// Created by Tiangong You on 8/1/16.
// Copyright © 2016 Tiangong You. All rights reserved.
//
import UIKit
import TTTAttributedLabel
import RMessage
class DetailDescriptionSectionView: DetailSectionViewBase, TTTAttributedLabelDelegate {
private var titleLabel = UILabel()
private var dateLabel = UILabel()
private var descLabel = TTTAttributedLabel(frame: CGRect.zero)
private var voteButton : UIButton!
private let titleFont = UIFont(name: "HelveticaNeue-Thin", size: 34)
private let dateFont = UIFont(name: "HelveticaNeue", size: 14)
private let descFont = ThemeManager.sharedInstance.currentTheme.descFont
private let descColor = ThemeManager.sharedInstance.currentTheme.descTextColor
private let linkColor = ThemeManager.sharedInstance.currentTheme.linkColor
private let linkPressColor = ThemeManager.sharedInstance.currentTheme.linkHighlightColor
private let titleTopPadding : CGFloat = 12
private let titleRightPadding : CGFloat = 70
private let dateRightPadding : CGFloat = 120
private let descRightPadding : CGFloat = 30
private let gap : CGFloat = 10
private var formattedDescText : NSAttributedString?
private var descSize : CGSize?
override func initialize() {
super.initialize()
// Title label
titleLabel.font = titleFont
titleLabel.textColor = ThemeManager.sharedInstance.currentTheme.titleTextColor
titleLabel.numberOfLines = 0
titleLabel.lineBreakMode = .byWordWrapping
contentView.addSubview(titleLabel)
// Date label
dateLabel.font = dateFont
dateLabel.textColor = ThemeManager.sharedInstance.currentTheme.standardTextColor
contentView.addSubview(dateLabel)
// Desc label
descLabel.font = descFont
descLabel.delegate = self
descLabel.textColor = ThemeManager.sharedInstance.currentTheme.descTextColor
descLabel.numberOfLines = 0
descLabel.lineBreakMode = .byWordWrapping
descLabel.linkAttributes = [NSForegroundColorAttributeName : linkColor, NSUnderlineStyleAttributeName : NSUnderlineStyle.styleNone.rawValue]
descLabel.activeLinkAttributes = [NSForegroundColorAttributeName : linkPressColor, NSUnderlineStyleAttributeName : NSUnderlineStyle.styleNone.rawValue]
contentView.addSubview(descLabel)
// Vote button
// Note: Xcode crashes due to sigbart if seeing this:
// let icon = photo.voted ? "DownVote" : "UpVote"
var icon : String
if photo.voted == true {
icon = "DownVote"
} else {
icon = "UpVote"
}
voteButton = UIButton(type: .custom)
voteButton.setImage(UIImage(named : icon), for: .normal)
voteButton.sizeToFit()
contentView.addSubview(voteButton)
voteButton.addTarget(self, action: #selector(voteButtonDidTap(_:)), for: .touchUpInside)
// Vote/unvote is only available for registered users
// A user cannot like his/her own photo
if let currentUser = StorageService.sharedInstance.currentUser {
if photo.user.userId == currentUser.userId {
voteButton.isHidden = true
} else {
voteButton.isHidden = false
}
} else {
voteButton.isHidden = true
}
// Events
NotificationCenter.default.addObserver(self, selector: #selector(photoVoteDidUpdate(_:)), name: StorageServiceEvents.photoVoteDidUpdate, object: nil)
}
deinit {
NotificationCenter.default.removeObserver(self)
}
override func layoutSubviews() {
super.layoutSubviews()
var nextY : CGFloat = contentTopPadding
// Title
titleLabel.text = photo.title
var f = titleLabel.frame
f.origin.x = contentLeftPadding
f.origin.y = nextY
f.size.width = width - contentLeftPadding - titleRightPadding
titleLabel.frame = f
titleLabel.text = photo.title
titleLabel.sizeToFit()
nextY += titleLabel.frame.size.height
// Creation date
if let dateString = displayDateString(photo) {
nextY += gap
dateLabel.isHidden = false
f = dateLabel.frame
f.origin.x = contentLeftPadding
f.origin.y = nextY
f.size.width = width - contentLeftPadding - dateRightPadding
dateLabel.frame = f
dateLabel.text = dateString
dateLabel.sizeToFit()
nextY += dateLabel.frame.size.height
} else{
dateLabel.isHidden = true
}
// Descriptions
if formattedDescText != nil && descSize != nil {
nextY += gap
dateLabel.isHidden = false
descLabel.setText(formattedDescText)
f = descLabel.frame
f.origin.x = contentLeftPadding
f.origin.y = nextY
f.size.width = descSize!.width
f.size.height = descSize!.height
descLabel.frame = f
} else {
descLabel.isHidden = true
}
// Vote button
f = voteButton.frame
f.origin.x = titleLabel.frame.maxX + 25
f.origin.y = titleLabel.frame.midY - f.size.height / 2
voteButton.frame = f
}
// MARK: - Measurments
override func calculateContentHeight(maxWidth: CGFloat) -> CGFloat {
var measuredHeight : CGFloat = contentTopPadding
// Title
let maxTitleWidth = width - contentLeftPadding - titleRightPadding
let titleHeight = NSString(string : photo.title).boundingRect(with: CGSize(width: maxTitleWidth,
height: CGFloat.greatestFiniteMagnitude),
options: .usesLineFragmentOrigin,
attributes: [NSFontAttributeName: titleFont!],
context: nil).size.height
measuredHeight += titleHeight
// Date
if let date = displayDateString(photo) {
let maxDateWidth = width - contentLeftPadding - dateRightPadding
let dateHeight = NSString(string : date).boundingRect(with: CGSize(width: maxDateWidth, height: CGFloat.greatestFiniteMagnitude),
options: .usesLineFragmentOrigin,
attributes: [NSFontAttributeName: dateFont!],
context: nil).size.height
measuredHeight += dateHeight + gap
}
// Descriptions
if photo.desc != nil {
let maxDescWidth = width - contentLeftPadding - descRightPadding
formattedDescText = formattedDescriptionString(photo)
if formattedDescText != nil {
descSize = formattedDescText!.boundingRect(with: CGSize(width: maxDescWidth, height: CGFloat.greatestFiniteMagnitude),
options: .usesLineFragmentOrigin,
context: nil).size
measuredHeight += descSize!.height
}
}
return measuredHeight
}
// MARK: - Private
private func formattedDescriptionString(_ photo : PhotoModel) -> NSAttributedString? {
guard let desc = photo.desc else { return nil }
let descColor = ThemeManager.sharedInstance.currentTheme.descTextColorHex
let descStringWithStyles = NSString(format:"<span style=\"color: \(descColor); font-family: \(descFont.fontName); font-size: \(descFont.pointSize)\">%@</span>" as NSString, desc) as String
guard let data = descStringWithStyles.data(using: String.Encoding.utf8) else { return nil }
let options : [String : Any] = [NSDocumentTypeDocumentAttribute:NSHTMLTextDocumentType,
NSCharacterEncodingDocumentAttribute:String.Encoding.utf8.rawValue]
var formattedDesc : NSAttributedString?
do {
formattedDesc = try NSAttributedString(data: data, options: options, documentAttributes: nil)
} catch let error as NSError {
print(error.localizedDescription)
formattedDesc = nil
}
return formattedDesc
}
private func displayDateString(_ photo : PhotoModel) -> String? {
if photo.creationDate == nil {
return nil
}
let dateFormatter = DateFormatter()
dateFormatter.dateStyle = .medium
dateFormatter.timeStyle = .none
return dateFormatter.string(from: photo.creationDate! as Date)
}
override func entranceAnimationWillBegin() {
titleLabel.alpha = 0
dateLabel.alpha = 0
descLabel.alpha = 0
voteButton.alpha = 0
titleLabel.transform = CGAffineTransform(translationX: 0, y: 30)
dateLabel.transform = CGAffineTransform(translationX: 0, y: 30)
descLabel.transform = CGAffineTransform(translationX: 0, y: 30)
voteButton.transform = CGAffineTransform(translationX: 0, y: 30)
}
override func performEntranceAnimation() {
UIView .addKeyframe(withRelativeStartTime: 0.3, relativeDuration: 1, animations: { [weak self] in
self?.titleLabel.alpha = 1
self?.titleLabel.transform = CGAffineTransform.identity
self?.voteButton.alpha = 1
self?.voteButton.transform = CGAffineTransform.identity
})
UIView .addKeyframe(withRelativeStartTime: 0.5, relativeDuration: 1, animations: { [weak self] in
self?.dateLabel.alpha = 1
self?.dateLabel.transform = CGAffineTransform.identity
})
UIView .addKeyframe(withRelativeStartTime: 0.7, relativeDuration: 1, animations: { [weak self] in
self?.descLabel.alpha = 1
self?.descLabel.transform = CGAffineTransform.identity
})
}
@objc private func voteButtonDidTap(_ tap : UITapGestureRecognizer) {
voteButton.alpha = 0.5
voteButton.isUserInteractionEnabled = false
if photo.voted == true {
APIService.sharedInstance.deleteVote(photoId: photo.photoId, success: nil, failure: { [weak self] (errorMessage) in
self?.voteButton.alpha = 1
self?.voteButton.isUserInteractionEnabled = true
})
} else {
APIService.sharedInstance.votePhoto(photoId: photo.photoId, success: nil, failure: { [weak self] (errorMessage) in
self?.voteButton.alpha = 1
self?.voteButton.isUserInteractionEnabled = true
})
}
}
// Events
@objc private func photoVoteDidUpdate(_ notification : Notification) {
let updatedPhoto = notification.userInfo![StorageServiceEvents.photo] as! PhotoModel
guard updatedPhoto.photoId == photo.photoId else { return }
photo.voted = updatedPhoto.voted
voteButton.alpha = 1
voteButton.isUserInteractionEnabled = true
if photo.voted == true {
voteButton.setImage(UIImage(named: "DownVote"), for: .normal)
} else {
voteButton.setImage(UIImage(named: "UpVote"), for: .normal)
}
}
// MARK: - TTTAttributedLabelDelegate
func attributedLabel(_ label: TTTAttributedLabel!, didSelectLinkWith url: URL!) {
if UIApplication.shared.canOpenURL(url) {
UIApplication.shared.open(url, options: [:], completionHandler: nil)
}
}
}
|
mit
|
2b2f607e941eb84f988deebc6535ff1d
| 40.413559 | 196 | 0.606614 | 5.533062 | false | false | false | false |
androidx/androidx
|
benchmark/benchmark-darwin-xcode/iosAppUnitTests/main/Benchmarks.swift
|
3
|
1569
|
/*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import Foundation
import XCTest
import AndroidXDarwinBenchmarks
class BenchmarkTest: XCTestCase {
var testCase: TestCase? = nil
override func setUpWithError() throws {
testCase!.setUp()
}
override class var defaultTestSuite: XCTestSuite {
let suite = XCTestSuite(forTestCaseClass: BenchmarkTest.self)
let testCases = TestCases.shared.benchmarkTests()
for testCase in testCases {
let test = BenchmarkTest(selector: #selector(runBenchmark))
test.testCase = testCase
suite.addTest(test)
}
return suite
}
@objc func runBenchmark() {
// https://masilotti.com/xctest-name-readability/
XCTContext.runActivity(named: testCase!.testDescription()) { _ -> Void in
// Run the actual benchmark
let context = TestCaseContextWrapper(context: self)
testCase?.benchmark(context: context)
}
}
}
|
apache-2.0
|
ffd8243e2eb72021f77a79566b7288aa
| 33.108696 | 81 | 0.681963 | 4.642012 | false | true | false | false |
banxi1988/BXCityPicker
|
Example/Pods/BXForm/Pod/Classes/View/IconLabel.swift
|
2
|
3088
|
//
// IconLabel.swift
//
// Created by Haizhen Lee on 15/12/20.
//
import UIKit
import PinAuto
// -IconLabel:v
// icon[l0,y]:i
// text[l8,t0,b0](f15,cdt)
open class IconLabel : UIView{
open let iconImageView = UIImageView(frame:CGRect.zero)
open let textLabel = UILabel(frame:CGRect.zero)
public override init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
override open func awakeFromNib() {
super.awakeFromNib()
commonInit()
}
var allOutlets :[UIView]{
return [iconImageView,textLabel]
}
var allUIImageViewOutlets :[UIImageView]{
return [iconImageView]
}
var allUILabelOutlets :[UILabel]{
return [textLabel]
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
func commonInit(){
for childView in allOutlets{
addSubview(childView)
childView.translatesAutoresizingMaskIntoConstraints = false
}
installConstaints()
setupAttrs()
}
open var iconLeadingConstraint:NSLayoutConstraint!
var iconPaddingConstraint:NSLayoutConstraint!
open var iconPadding : CGFloat{
set{
iconPaddingConstraint.constant = newValue
}get{
return iconPaddingConstraint.constant
}
}
func installConstaints(){
translatesAutoresizingMaskIntoConstraints = false
iconImageView.pa_centerY.install() //pa_centerY.install()
iconLeadingConstraint = iconImageView.pa_leading.eq(0).install() // pa_leading.eq(0)
textLabel.pa_bottom.eq(0).install()
iconPaddingConstraint = textLabel.pa_after(iconImageView, offset: 6).install() // textLabel.pinLeadingToSibling(iconImageView, margin: 6)
textLabel.pa_top.eq(0).install()
textLabel.pa_trailing.eq(0).install()
}
open override class var requiresConstraintBasedLayout : Bool{
return true
}
open override var intrinsicContentSize : CGSize {
let iconSize = iconImageView.intrinsicContentSize
let textSize = textLabel.intrinsicContentSize
let width = iconSize.width + iconPadding + textSize.width
let height = max(iconSize.height,textSize.height)
return CGSize(width: width, height: height)
}
func setupAttrs(){
textLabel.textAlignment = .left
textLabel.setContentHuggingPriority(240, for: .horizontal)
textLabel.textColor = UIColor.darkText
textLabel.font = UIFont.systemFont(ofSize: 15)
isUserInteractionEnabled = false
}
//MARK: Getter And Setter
open var text:String?{
get{
return textLabel.text
}set{
textLabel.text = newValue
invalidateIntrinsicContentSize()
}
}
open var icon:UIImage?{
get{
return iconImageView.image
}set{
iconImageView.image = newValue
invalidateIntrinsicContentSize()
}
}
open var textColor:UIColor?{
get{
return textLabel.textColor
}set{
textLabel.textColor = newValue
}
}
open var font:UIFont{
get{
return textLabel.font
}set{
textLabel.font = newValue
invalidateIntrinsicContentSize()
}
}
}
|
mit
|
2f3bc7444c11ae08596380db9ee5d165
| 21.540146 | 142 | 0.681995 | 4.527859 | false | false | false | false |
nathawes/swift
|
stdlib/private/StdlibUnittest/SymbolLookup.swift
|
5
|
1691
|
//===--- SymbolLookup.swift -----------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2019 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
//
//===----------------------------------------------------------------------===//
#if canImport(Darwin)
import Darwin
#elseif canImport(Glibc)
import Glibc
#elseif os(Windows)
import MSVCRT
import WinSDK
#else
#error("Unsupported platform")
#endif
#if canImport(Darwin) || os(OpenBSD)
let RTLD_DEFAULT = UnsafeMutableRawPointer(bitPattern: -2)
#elseif os(Linux)
let RTLD_DEFAULT = UnsafeMutableRawPointer(bitPattern: 0)
#elseif os(Android)
#if arch(arm) || arch(i386)
let RTLD_DEFAULT = UnsafeMutableRawPointer(bitPattern: 0xffffffff as UInt)
#elseif arch(arm64) || arch(x86_64)
let RTLD_DEFAULT = UnsafeMutableRawPointer(bitPattern: 0)
#else
#error("Unsupported platform")
#endif
#elseif os(Windows)
let hStdlibCore: HMODULE = GetModuleHandleA("swiftCore.dll")!
#elseif os(WASI)
// WASI doesn't support dynamic linking yet.
#else
#error("Unsupported platform")
#endif
public func pointerToSwiftCoreSymbol(name: String) -> UnsafeMutableRawPointer? {
#if os(Windows)
return unsafeBitCast(GetProcAddress(hStdlibCore, name),
to: UnsafeMutableRawPointer?.self)
#elseif os(WASI)
fatalError("\(#function) is not supported on WebAssembly/WASI")
#else
return dlsym(RTLD_DEFAULT, name)
#endif
}
|
apache-2.0
|
e757192834cda981474991d8c024977b
| 30.90566 | 80 | 0.676523 | 4.185644 | false | false | false | false |
garricn/GGNLocationPicker
|
GGNLocationPicker/Classes/SearchService.swift
|
1
|
1043
|
// GGNLocationPicker
//
// SearchService.swift
//
// Created by Garric Nahapetian on 9/9/16.
//
//
import MapKit
struct SearchService {
func search(with text: String, and location: MKUserLocation, with completion: @escaping (MKLocalSearchResponse) -> Void) {
let request = MKLocalSearchRequest()
request.naturalLanguageQuery = text
request.region = region(from: location)
let search = MKLocalSearch(request: request)
search.start { respone, error in
guard
let response = respone, response.mapItems.count > 0
else { return }
DispatchQueue.main.async {
completion(response)
}
}
}
func region(from location: MKUserLocation) -> MKCoordinateRegion {
let center = CLLocationCoordinate2DMake(location.coordinate.latitude, location.coordinate.longitude)
let span = MKCoordinateSpanMake(0.5, 0.5)
let region = MKCoordinateRegionMake(center, span)
return region
}
}
|
mit
|
699697621d61d26aea5329cb22db58bd
| 29.676471 | 126 | 0.639501 | 4.615044 | false | false | false | false |
JeffJin/ios9_notification
|
twilio/Services/Models/Dto/EventDto.swift
|
2
|
557
|
//
// AppointmentDto.swift
// AppointmentManagement
//
// Created by Zhengyuan Jin on 2015-03-14.
// Copyright (c) 2015 eWorkspace Solutions Inc. All rights reserved.
//
import Foundation
public class EventDto {
var id:Int64
var description:NSString
var dateFrom:NSDate
var dateTo:NSDate
var imageLink:NSString = ""
var note:NSString = ""
init(id:Int64, desc:NSString, start:NSDate, end:NSDate){
self.id = id
self.description = desc
self.dateFrom = start
self.dateTo = end
}
}
|
apache-2.0
|
a0bb0d777416cfca1540ea0ed5180883
| 20.423077 | 69 | 0.642729 | 3.713333 | false | false | false | false |
crazypoo/PTools
|
Pods/SwifterSwift/Sources/SwifterSwift/Foundation/FileManagerExtensions.swift
|
1
|
3793
|
//
// FileManagerExtensions.swift
// SwifterSwift
//
// Created by Jason Jon E. Carreos on 05/02/2018.
// Copyright © 2018 SwifterSwift
//
#if canImport(Foundation)
import Foundation
public extension FileManager {
/// SwifterSwift: Read from a JSON file at a given path.
///
/// - Parameters:
/// - path: JSON file path.
/// - readingOptions: JSONSerialization reading options.
/// - Returns: Optional dictionary.
/// - Throws: Throws any errors thrown by Data creation or JSON serialization.
func jsonFromFile(
atPath path: String,
readingOptions: JSONSerialization.ReadingOptions = .allowFragments) throws -> [String: Any]? {
let data = try Data(contentsOf: URL(fileURLWithPath: path), options: .mappedIfSafe)
let json = try JSONSerialization.jsonObject(with: data, options: readingOptions)
return json as? [String: Any]
}
#if !os(Linux)
/// SwifterSwift: Read from a JSON file with a given filename.
///
/// - Parameters:
/// - filename: File to read.
/// - bundleClass: Bundle where the file is associated.
/// - readingOptions: JSONSerialization reading options.
/// - Returns: Optional dictionary.
/// - Throws: Throws any errors thrown by Data creation or JSON serialization.
func jsonFromFile(
withFilename filename: String,
at bundleClass: AnyClass? = nil,
readingOptions: JSONSerialization.ReadingOptions = .allowFragments) throws -> [String: Any]? {
// https://stackoverflow.com/questions/24410881/reading-in-a-json-file-using-swift
// To handle cases that provided filename has an extension
let name = filename.components(separatedBy: ".")[0]
let bundle = bundleClass != nil ? Bundle(for: bundleClass!) : Bundle.main
if let path = bundle.path(forResource: name, ofType: "json") {
let data = try Data(contentsOf: URL(fileURLWithPath: path), options: .mappedIfSafe)
let json = try JSONSerialization.jsonObject(with: data, options: readingOptions)
return json as? [String: Any]
}
return nil
}
#endif
/// SwifterSwift: Creates a unique directory for saving temporary files. The directory can be used to create multiple temporary files used for a common purpose.
///
/// let tempDirectory = try fileManager.createTemporaryDirectory()
/// let tempFile1URL = tempDirectory.appendingPathComponent(ProcessInfo().globallyUniqueString)
/// let tempFile2URL = tempDirectory.appendingPathComponent(ProcessInfo().globallyUniqueString)
///
/// - Returns: A URL to a new directory for saving temporary files.
/// - Throws: An error if a temporary directory cannot be found or created.
func createTemporaryDirectory() throws -> URL {
#if !os(Linux)
let temporaryDirectoryURL: URL
if #available(OSX 10.12, tvOS 10.0, watchOS 3.0, *) {
temporaryDirectoryURL = temporaryDirectory
} else {
temporaryDirectoryURL = URL(fileURLWithPath: NSTemporaryDirectory(), isDirectory: true)
}
return try url(for: .itemReplacementDirectory,
in: .userDomainMask,
appropriateFor: temporaryDirectoryURL,
create: true)
#else
let envs = ProcessInfo.processInfo.environment
let env = envs["TMPDIR"] ?? envs["TEMP"] ?? envs["TMP"] ?? "/tmp"
let dir = "/\(env)/file-temp.XXXXXX"
var template = [UInt8](dir.utf8).map({ Int8($0) }) + [Int8(0)]
guard mkdtemp(&template) != nil else { throw CocoaError.error(.featureUnsupported) }
return URL(fileURLWithPath: String(cString: template))
#endif
}
}
#endif
|
mit
|
dba71d1469f6b5708d46603033ddac05
| 40.217391 | 164 | 0.647679 | 4.710559 | false | false | false | false |
frapperino/MultiPlayerMemory
|
MultiPlayer Memory/MultiPlayer Memory/Brick.swift
|
1
|
1382
|
//
// Brick.swift
// MultiPlayer Memory
//
// Created by Magnus Huttu on 2016-10-10.
// Copyright © 2016 Magnus Huttu. All rights reserved.
//
import UIKit
class Brick: UICollectionViewCell {
@IBOutlet weak var cardView: UIView!
@IBOutlet weak var imageView: UIImageView!
var frontImage : UIImage?
var backgroundImage : UIImage = #imageLiteral(resourceName: "Image")
var color : UIColor?
var open : Bool = false
var id : Int = 0
var brickMatchId : Int = 0
public func click() {
if !self.isOpen() {
self.open = true
let newImageView = UIImageView(frame: cardView.bounds)
newImageView.image = frontImage!
UIView.transition(from: imageView!, to: newImageView, duration: 1, options: .transitionFlipFromRight, completion: nil)
self.imageView = newImageView
}
}
public func close() {
self.open = false
let newImageView = UIImageView(frame: cardView.bounds)
newImageView.image = backgroundImage
UIView.transition(from: imageView!, to: newImageView, duration: 1, options: .transitionFlipFromLeft, completion: nil)
self.imageView = newImageView
}
public func isOpen() -> Bool {
return open
}
public func isMatch() {
self.isUserInteractionEnabled = false
}
}
|
apache-2.0
|
cf7a7a54a8cb6e60f1a45a266f2c5b52
| 27.770833 | 130 | 0.630702 | 4.58804 | false | false | false | false |
Marquis103/FitJourney
|
FitJourney/DiaryEntryTextView.swift
|
1
|
1279
|
//
// DiaryEntryTextView.swift
// FitJourney
//
// Created by Marquis Dennis on 4/26/16.
// Copyright © 2016 Marquis Dennis. All rights reserved.
//
import UIKit
import QuartzCore
@IBDesignable
class DiaryEntryTextView: UITextView {
@IBInspectable
var borderWidth:CGFloat = 2.0 {
didSet {
layer.borderWidth = borderWidth
setNeedsDisplay()
}
}
@IBInspectable
var borderColor:UIColor = UIColor.lightGrayColor() {
didSet {
layer.borderColor = borderColor.CGColor
setNeedsDisplay()
}
}
@IBInspectable
var cornerRadius:CGFloat = 5.0 {
didSet {
layer.cornerRadius = cornerRadius
setNeedsDisplay()
}
}
func configureTextView() {
layoutManager.delegate = self
layer.borderWidth = 2.0
layer.borderColor = UIColor.lightGrayColor().CGColor
layer.cornerRadius = 5
/*entryTextField.layer.masksToBounds = false
entryTextField.layer.shadowColor = UIColor.blackColor().CGColor
entryTextField.layer.shadowOffset = CGSize(width: 1.0, height: 1.0)
entryTextField.layer.shadowRadius = 1.0*/
}
}
extension DiaryEntryTextView:NSLayoutManagerDelegate {
func layoutManager(layoutManager: NSLayoutManager, lineSpacingAfterGlyphAtIndex glyphIndex: Int, withProposedLineFragmentRect rect: CGRect) -> CGFloat {
return 10
}
}
|
gpl-3.0
|
d9894cc9cd21bb233ea1b52d3ae2ab6d
| 21.034483 | 153 | 0.742567 | 3.861027 | false | false | false | false |
DrGo/LearningSwift
|
PLAYGROUNDS/LSB_C007_Map.playground/section-2.swift
|
2
|
996
|
import UIKit
/*
// Map
//
// Suggested Reading:
// http://www.objc.io/snippets/9.html
/===================================*/
/*------------------------------------/
// Map on Arrays
/------------------------------------*/
var ints = [1,2,3,4,5]
var resultInts = ints.map { $0 + 1 }
resultInts
ints // it's immutable
/*------------------------------------/
// Map, the global func
/------------------------------------*/
resultInts = map(ints) { $0 + 2 }
resultInts
ints // still immutable
/*------------------------------------/
// Map on an Optional
/------------------------------------*/
var optName: String?
var greeting: String? = ""
optName = "George"
if let name = optName {
greeting = "Hi, \(name)"
}
greeting!
// Can detect a nil with a much nicer syntax
optName = "Fred"
greeting = optName.map { "Hello, \($0)" }
greeting!
// And return nil if map unsuccessful
optName = nil
greeting = map(optName) { "Hello, \($0)" }
if greeting == nil {
"greeting is nil"
}
|
gpl-3.0
|
ca55d08213f4bcacdf94afdbe9bc8c89
| 16.473684 | 44 | 0.455823 | 3.648352 | false | false | false | false |
airspeedswift/swift
|
test/IRGen/prespecialized-metadata/struct-outmodule-resilient-1argument-1distinct_use-struct-inmodule.swift
|
3
|
1351
|
// RUN: %empty-directory(%t)
// RUN: %target-build-swift -Xfrontend -prespecialize-generic-metadata -target %module-target-future %S/Inputs/struct-public-nonfrozen-1argument.swift -emit-library -o %t/%target-library-name(Generic) -emit-module -module-name Generic -emit-module-path %t/Generic.swiftmodule -enable-library-evolution
// RUN: %swift -prespecialize-generic-metadata -target %module-target-future -emit-ir %s -L %t -I %t -lGeneric -lArgument | %FileCheck %s -DINT=i%target-ptrsize -DALIGNMENT=%target-alignment
// REQUIRES: OS=macosx || OS=ios || OS=tvos || OS=watchos || OS=linux-gnu
// UNSUPPORTED: CPU=i386 && OS=ios
// UNSUPPORTED: CPU=armv7 && OS=ios
// UNSUPPORTED: CPU=armv7s && OS=ios
// CHECK-NOT: @"$s7Generic11OneArgumentVy4main03TheC0VGMN" =
@inline(never)
func consume<T>(_ t: T) {
withExtendedLifetime(t) { t in
}
}
import Generic
struct TheArgument {
let value: Int
}
// CHECK: define hidden swiftcc void @"$s4main4doityyF"() #{{[0-9]+}} {
// CHECK: [[METADATA:%[0-9]+]] = call %swift.type* @__swift_instantiateConcreteTypeFromMangledName({ i32, i32 }* @"$s7Generic11OneArgumentVy4main03TheC0VGMD")
// CHECK: call swiftcc void @"$s4main7consumeyyxlF"(%swift.opaque* noalias nocapture {{%[0-9]+}}, %swift.type* [[METADATA]])
// CHECK: }
func doit() {
consume( OneArgument(TheArgument(value: 13)) )
}
doit()
|
apache-2.0
|
e8bed769cd4d2ef0a7fc2e2351305864
| 42.580645 | 301 | 0.706884 | 3.239808 | false | false | false | false |
rain2540/RGAppTools
|
Sources/Extensions/Basic/Array+RGAppTools.swift
|
1
|
1809
|
//
// Array+RGAppTools.swift
// RGAppTools
//
// Created by RAIN on 2019/1/7.
// Copyright © 2019 Smartech. All rights reserved.
//
import Foundation
extension Array {
/// 获取数组特定位置的元素 / 设置数组特定元素的值
/// - Parameters:
/// - first: 第一个特定元素的下标
/// - second: 第二个特定元素的下标
/// - others: 其他特定元素的下标
public subscript(first: Int, second: Int, others: Int...) -> ArraySlice<Element> {
get {
var indexes: [Int] = []
indexes.append(contentsOf: [first, second])
indexes.append(contentsOf: others)
var result = ArraySlice<Element>()
for i in indexes {
assert(i < self.count, "Index is out of range")
result.append(self[i])
}
return result
}
set {
var indexes: [Int] = []
indexes.append(contentsOf: [first, second])
indexes.append(contentsOf: others)
for (index, i) in indexes.enumerated() {
assert(i < self.count, "Index is out of range")
self[i] = newValue[index]
}
}
}
/// 获取数组特定位置的元素 / 设置数组特定元素的值
/// - Parameter input: 特定元素的下标组成的数组
public subscript(input: [Int]) -> ArraySlice<Element> {
get {
var result = ArraySlice<Element>()
for i in input {
assert(i < self.count, "Index is out of range")
result.append(self[i])
}
return result
}
set {
for (index, i) in input.enumerated() {
assert(i < self.count, "Index is out of range")
self[i] = newValue[index]
}
}
}
public subscript(guarded idx: Int) -> Element? {
guard (startIndex ..< endIndex).contains(idx) else { return nil }
return self[idx]
}
}
|
mpl-2.0
|
a20c333695930bc642651cd8c3a927e2
| 22.797101 | 84 | 0.582217 | 3.577342 | false | false | false | false |
banjun/NorthLayout
|
Example/NorthLayout-ios/ViewController.swift
|
1
|
7690
|
//
// ViewController.swift
// NorthLayout
//
// Created by BAN Jun on 5/9/15.
// Copyright (c) 2015 banjun. All rights reserved.
//
import UIKit
import NorthLayout
func colorImage(_ color: UIColor) -> UIImage {
UIGraphicsBeginImageContext(CGSize(width: 1, height: 1))
color.set()
UIRectFill(CGRect(x: 0, y: 0, width: 1, height: 1))
let image = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
return image
}
private let iconWidth: CGFloat = 32
class ViewController: UIViewController {
let headerView = HeaderView()
let iconView: UIImageView = {
let v = UIImageView(image: colorImage(UIColor(red: 0.63, green: 0.9, blue: 1, alpha: 1)))
v.layer.cornerRadius = iconWidth / 2
v.clipsToBounds = true
return v
}()
let nameLabel: UILabel = {
let l = UILabel()
l.text = "Name"
return l
}()
let dateLabel: UILabel = {
let l = UILabel()
l.text = "1 min ago"
l.font = UIFont.systemFont(ofSize: 12)
l.textColor = .lightGray
l.textAlignment = .right
l.setContentHuggingPriority(.required, for: .horizontal)
return l
}()
let textLabel: UILabel = {
let l = UILabel()
l.text = "Some text go here"
return l
}()
let favButton: UIButton = {
let b = UIButton(type: .system)
b.setTitle("⭐️", for: [])
b.backgroundColor = UIColor(red: 0.17, green: 0.29, blue: 0.45, alpha: 1.0)
b.setTitleColor(.white, for: [])
b.layer.cornerRadius = 4
b.clipsToBounds = true
b.addTarget(self, action: #selector(fav), for: .touchUpInside)
return b
}()
let navToggleButton: UIButton = {
let b = UIButton(type: .system)
b.setTitle("Nav Bar", for: [])
b.backgroundColor = UIColor(red: 0.17, green: 0.29, blue: 0.45, alpha: 1.0)
b.setTitleColor(.white, for: [])
b.layer.cornerRadius = 4
b.clipsToBounds = true
b.addTarget(self, action: #selector(nav), for: .touchUpInside)
return b
}()
let simpleExampleButton: UIButton = {
let b = UIButton(type: .system)
b.setTitle("Simple Layout Example >", for: [])
b.backgroundColor = UIColor(red: 0.17, green: 0.29, blue: 0.45, alpha: 1.0)
b.setTitleColor(.white, for: [])
b.layer.cornerRadius = 4
b.clipsToBounds = true
b.addTarget(self, action: #selector(showSimpleExample), for: .touchUpInside)
return b
}()
let safeAreaExampleButton: UIButton = {
let b = UIButton(type: .system)
b.setTitle("Safe Area Example >", for: [])
b.backgroundColor = UIColor(red: 0.17, green: 0.29, blue: 0.45, alpha: 1.0)
b.setTitleColor(.white, for: [])
b.layer.cornerRadius = 4
b.clipsToBounds = true
b.addTarget(self, action: #selector(showViewLevelSafeAreaExample), for: .touchUpInside)
return b
}()
override func loadView() {
super.loadView()
view.backgroundColor = .white
// view controller level autolayout respecting safe area layout guides (or top/bottom layout guides for iOS 10 and before)
let autolayout = northLayoutFormat(["p": 8, "iconWidth": iconWidth], [
"header": headerView,
"icon": iconView,
"name": nameLabel,
"date": dateLabel,
"text": textLabel,
"fav": favButton,
"navToggle": navToggleButton,
"simpleExample": simpleExampleButton,
"safeAreaExample": safeAreaExampleButton])
autolayout("H:|[header]|")
autolayout("V:|[header(<=192)]")
autolayout("H:||[icon(==iconWidth)]-p-[name]-p-[date]||")
autolayout("H:||[text]||")
autolayout("H:||[navToggle]-p-[fav(==navToggle)]||")
autolayout("H:||[simpleExample]||")
autolayout("H:||[safeAreaExample]||")
autolayout("V:[header]-p-[icon(==iconWidth)]-p-[text]")
autolayout("V:[header]-p-[name(==icon)]")
autolayout("V:[header]-p-[date]")
autolayout("V:[text]-p-[fav]")
autolayout("V:[text]-p-[navToggle]-(>=p)-[simpleExample]-p-[safeAreaExample]-p-||")
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
NSLog("%@", "view.layoutMargins = \(view.layoutMargins)")
NSLog("%@", "view._autolayoutTrace = \(String(describing: view.value(forKey: "_autolayoutTrace")))")
}
@objc func nav() {
// show/hide navigation bar with animations
guard let nc = navigationController else { return }
nc.setNavigationBarHidden(!nc.isNavigationBarHidden, animated: true)
UIView.animate(withDuration: TimeInterval(UINavigationController.hideShowBarDuration)) {
self.view.setNeedsUpdateConstraints() // not all the layout changes cause updating constraints
self.view.layoutIfNeeded() // re-layout within the animation block
}
}
@objc func fav() {
headerView.bioLabel.text = (headerView.bioLabel.text ?? "") + "\n⭐️"
}
@objc func showSimpleExample() {
show(SimpleExampleViewController(nibName: nil, bundle: nil), sender: nil)
}
@objc func showViewLevelSafeAreaExample() {
show(ViewLevelSafeAreaExampleViewController(nibName: nil, bundle: nil), sender: nil)
}
}
// Example for view level autolayout with respecting safe area layout guides
final class HeaderView: UIView {
let leftColumn: UIView = {
let v = MinView() // non -1 intrinsic size for compact layout
v.backgroundColor = .darkGray
return v
}()
let rightColumn: UIView = {
let v = MinView() // non -1 intrinsic size for compact layout
v.backgroundColor = .lightGray
return v
}()
let iconView: UIView = {
let v = UIView(frame: .zero)
v.backgroundColor = UIColor(red: 0.63, green: 0.9, blue: 1, alpha: 1)
v.clipsToBounds = true
v.layer.cornerRadius = 32
return v
}()
let nameLabel: UILabel = {
let l = UILabel(frame: .zero)
l.text = "@screenname" // @"s" // for short
l.textColor = .white
l.textAlignment = .center
return l
}()
let bioLabel: UILabel = {
let l = UILabel(frame: .zero)
l.text = "some text"
l.textColor = .black
l.backgroundColor = .white
l.numberOfLines = 0
return l
}()
init() {
super.init(frame: .zero)
let autolayout = northLayoutFormat([:], ["left": leftColumn, "right": rightColumn])
autolayout("H:|[left][right]|")
autolayout("V:|[left]|")
autolayout("V:|[right]|")
rightColumn.setContentHuggingPriority(.fittingSizeLevel, for: .horizontal)
let leftLayout = leftColumn.northLayoutFormat([:], [
"icon": iconView,
"name": nameLabel])
leftLayout("H:||-(>=0)-[icon(==64)]-(>=0)-||")
leftLayout("H:||-(>=0)-[name]-(>=0)-||")
leftLayout("V:||[icon(==64)]-[name]-(>=0)-||")
leftColumn.layoutMarginsGuide.centerXAnchor.constraint(equalTo: iconView.centerXAnchor).isActive = true
leftColumn.layoutMarginsGuide.centerXAnchor.constraint(equalTo: nameLabel.centerXAnchor).isActive = true
let rightLayout = rightColumn.northLayoutFormat([:], [
"bio": bioLabel])
rightLayout("H:||[bio]||")
rightLayout("V:||[bio]-(>=0)-||")
setContentHuggingPriority(.required, for: .vertical)
}
required init?(coder aDecoder: NSCoder) {super.init(coder: aDecoder)}
}
|
mit
|
4c7b2be137918158e4194e006db1970a
| 33.142222 | 130 | 0.594637 | 4.179543 | false | false | false | false |
neilpa/Termios
|
Termios/LocalFlags.swift
|
1
|
2265
|
//
// LocalFlags.swift
// Termios
//
// Created by Neil Pankey on 3/20/15.
// Copyright (c) 2015 Neil Pankey. All rights reserved.
//
import Darwin.POSIX.termios
/// Local flag values in a `termios` structure.
public struct LocalFlags : RawOptionSetType {
public var rawValue: UInt
public init(_ value: UInt) {
rawValue = value
}
public init(rawValue value: UInt) {
rawValue = value
}
public init(nilLiteral: ()) {
rawValue = 0
}
public static var allZeros: LocalFlags {
return self(0)
}
/// visual erase for line kill
public static let ECHOKE = LocalFlags(UInt(Darwin.ECHOKE))
/// visually erase chars
public static let ECHOE = LocalFlags(UInt(Darwin.ECHOE))
/// echo NL after line kill
public static let ECHOK = LocalFlags(UInt(Darwin.ECHOK))
/// enable echoing
public static let ECHO = LocalFlags(UInt(Darwin.ECHO))
/// echo NL even if ECHO is off
public static let ECHONL = LocalFlags(UInt(Darwin.ECHONL))
/// visual erase mode for hardcopy
public static let ECHOPRT = LocalFlags(UInt(Darwin.ECHOPRT))
/// echo control chars as ^(Char)
public static let ECHOCTL = LocalFlags(UInt(Darwin.ECHOCTL))
/// enable signals INTR, QUIT, [D]SUSP
public static let ISIG = LocalFlags(UInt(Darwin.ISIG))
/// canonicalize input lines
public static let ICANON = LocalFlags(UInt(Darwin.ICANON))
/// use alternate WERASE algorithm
public static let ALTWERASE = LocalFlags(UInt(Darwin.ALTWERASE))
/// enable DISCARD and LNEXT
public static let IEXTEN = LocalFlags(UInt(Darwin.IEXTEN))
/// external processing
public static let EXTPROC = LocalFlags(UInt(Darwin.EXTPROC))
/// stop background jobs from output
public static let TOSTOP = LocalFlags(UInt(Darwin.TOSTOP))
/// output being flushed (state)
public static let FLUSHO = LocalFlags(UInt(Darwin.FLUSHO))
/// no kernel output from VSTATUS
public static let NOKERNINFO = LocalFlags(UInt(Darwin.NOKERNINFO))
/// XXX retype pending input (state)
public static let PENDIN = LocalFlags(UInt(Darwin.PENDIN))
/// don't flush after interrupt
public static let NOFLSH = LocalFlags(UInt(Darwin.NOFLSH))
}
|
mit
|
6829707d4398a00895b05c4e4a04d507
| 26.962963 | 70 | 0.679029 | 3.813131 | false | false | false | false |
Cananito/Swim
|
SwimCore/SwimCore/Interpreter.swift
|
1
|
5484
|
//
// Interpreter.swift
// swim
//
// Created by Rogelio Gudino on 8/12/14.
// Copyright (c) 2014 Cananito. All rights reserved.
//
public class Interpreter {
var globalEnvironment = Environment()
public init() {
}
public func interpretProgram(program program: String) -> String {
populateGlobalEnvironment()
var tokens = tokenizeString(string: program)
let parsedTokens = parseTokens(tokens: &tokens)
if let value = evaluateParsedTokens(parsedTokens: parsedTokens, environment: self.globalEnvironment) {
let stringValue = convertValueToString(value: value)
return stringValue
}
return ""
}
private func populateGlobalEnvironment() {
self.globalEnvironment.setValue(value: "+", forKey: "+")
self.globalEnvironment.setValue(value: "-", forKey: "-")
self.globalEnvironment.setValue(value: "*", forKey: "*")
self.globalEnvironment.setValue(value: "/", forKey: "/")
// TODO: Implement the rest
//'not':op.not_,
//'>':op.gt
//'<':op.lt
//'>=':op.ge
//'<=':op.le
//'=':op.eq
self.globalEnvironment.setValue(value: "equal?", forKey: "equal?")
//'eq?':op.is_
self.globalEnvironment.setValue(value: "length", forKey: "length")
//'cons':lambda x,y:[x]+y
//'car':lambda x:x[0]
//'cdr':lambda x:x[1:]
//'append':op.add
//'list':lambda *x:list(x)
//'list?': lambda x:isa(x,list)
//'null?':lambda x:x==[]
//'symbol?':lambda x: isa(x, Symbol)
}
private func tokenizeString(string string: String) -> [String] {
var newString = string.stringByReplacingCharacter(character: "(", withString: " ( ")
newString = newString.stringByReplacingCharacter(character: ")", withString: " ) ")
return split(newString.characters) { $0 == " " }.map { String($0) }
}
private func parseTokens(inout tokens tokens: [String]) -> Any {
if tokens.count == 0 {
return ""
}
let token = tokens.removeAtIndex(0)
if token == "(" {
var list = [Any]()
while tokens.first! != ")" {
list.append(parseTokens(tokens: &tokens))
}
tokens.removeAtIndex(0)
return list
} else if token == ")" {
return "ERROR" // Need to roll out the whole failing mechanism
} else {
return atomizeToken(token: token)
}
}
private func atomizeToken(token token: String) -> Any {
if let intToken = Int(token) {
return intToken
} else if let floatToken = token.toFloat() {
return floatToken
}
return token
}
private func evaluateParsedTokens(parsedTokens parsedTokens: Any, environment: Environment) -> Any? {
if (parsedTokens is String == true) {
let variableReference = parsedTokens as! String
if let variable = environment.findEnvironmentWithVariable(variable: variableReference)?[variableReference] {
return variable as! String
}
return nil
} else if (parsedTokens is [Any] == false) { // Constant literal
return parsedTokens
}
let expressionArray = parsedTokens as! [Any]
let expressionName = expressionArray[0] as! String
if (expressionName == "quote") {
return expressionArray[1]
} else if (expressionName == "if") {
let test = expressionArray[1]
let consequence = expressionArray[2]
let alternative = expressionArray[3]
if self.evaluateParsedTokens(parsedTokens: test, environment: environment) as? Bool == true { // It is going to be a bool?
return consequence
} else {
return alternative
}
} else {
// TODO: More missing
}
var expressions = [Any]()
for expression in parsedTokens as! [Any] {
if let evaluatedExpression = evaluateParsedTokens(parsedTokens: expression, environment: environment) {
expressions.append(evaluatedExpression)
} else {
return nil
}
}
let procedureName = expressions.removeAtIndex(0) as! String
return executeProcedureForKey(key: procedureName, withExpressions: expressions)
}
private func executeProcedureForKey(key key: String, withExpressions expressions: [Any]) -> Any? {
// TODO: Implement the rest
switch key {
case "+":
return add(expressions)
case "-":
return substract(expressions)
case "*":
return multiply(expressions)
case "/":
return divide(expressions)
case "equal?":
return isEqual(expressions)
case "length":
return length(expressions)
default:
return nil
}
}
private func convertValueToString(value value: Any) -> String {
switch value {
case let i as Int:
return i.description
case let f as Float:
return f.description
case let b as Bool:
return b.description
default:
return value as! String
}
}
}
|
mit
|
1282d101634f52d5732f10e478fea6ae
| 33.490566 | 134 | 0.55671 | 4.67121 | false | false | false | false |
svenbacia/TraktKit
|
TraktKit/Sources/Resource/Trakt/ShowResource.swift
|
1
|
2419
|
//
// ShowResource.swift
// TraktKit
//
// Created by Sven Bacia on 06.09.16.
// Copyright © 2016 Sven Bacia. All rights reserved.
//
import Foundation
public struct ShowResource {
// MARK: - Properties
private let id: Int
private let configuration: Trakt.Configuration
// MARK: - Init
init(id: Int, configuration: Trakt.Configuration) {
self.id = id
self.configuration = configuration
}
// MARK: - Endpoints
public func summary(extended: Extended? = nil) -> Resource<Show> {
return buildResource(base: configuration.base, path: "/shows/\(id)", params: parameters(extended: extended))
}
public func comments(extended: Extended? = nil, page: Int? = nil, limit: Int? = nil) -> Resource<[Comment]> {
return buildResource(base: configuration.base, path: "/shows/\(id)/comments", params: parameters(page: page, limit: limit, extended: extended))
}
public func people(extended: Extended? = nil) -> Resource<Cast> {
return buildResource(base: configuration.base, path: "/shows/\(id)/people", params: parameters(extended: extended))
}
public func ratings() -> Resource<Ratings> {
return buildResource(base: configuration.base, path: "/shows/\(id)/ratings")
}
public func related(extended: Extended? = nil, page: Int? = nil, limit: Int? = nil) -> Resource<[Show]> {
return buildResource(base: configuration.base, path: "/shows/\(id)/related", params: parameters(page: page, limit: limit, extended: extended))
}
public func stats() -> Resource<Stats> {
return buildResource(base: configuration.base, path: "/shows/\(id)/stats")
}
public func watching(extended: Extended? = nil) -> Resource<[User]> {
return buildResource(base: configuration.base, path: "/shows/\(id)/watching", params: parameters(extended: extended))
}
// MARK: - Progress
public var progress: ProgressResource {
return ProgressResource(show: id, configuration: configuration)
}
// MARK: - Seasons
public func seasons(_ extended: Extended? = nil) -> Resource<[Season]> {
return buildResource(base: configuration.base, path: "/shows/\(id)/seasons", params: parameters(extended: extended))
}
public func season(_ season: Int) -> SeasonResource {
return SeasonResource(show: id, season: season, configuration: configuration)
}
}
|
mit
|
787d943471cd872abd63c7fa63e3de85
| 33.542857 | 151 | 0.658395 | 4.16179 | false | true | false | false |
brentsimmons/Evergreen
|
Mac/MainWindow/Sidebar/SidebarOutlineView.swift
|
1
|
1413
|
//
// SidebarOutlineView.swift
// NetNewsWire
//
// Created by Brent Simmons on 11/17/15.
// Copyright © 2015 Ranchero Software, LLC. All rights reserved.
//
import AppKit
import RSCore
import RSTree
class SidebarOutlineView : NSOutlineView {
@IBOutlet var keyboardDelegate: KeyboardDelegate!
// MARK: NSTableView
override func frameOfCell(atColumn column: Int, row: Int) -> NSRect {
// Don’t allow the pseudo-feeds at the top level to be indented.
var frame = super.frameOfCell(atColumn: column, row: row)
frame.origin.x += 4.0
frame.size.width -= 4.0
let node = item(atRow: row) as! Node
guard let parentNode = node.parent, parentNode.isRoot else {
return frame
}
guard node.representedObject is PseudoFeed else {
return frame
}
frame.origin.x -= indentationPerLevel
frame.size.width += indentationPerLevel
return frame
}
// MARK: NSView
override func viewWillStartLiveResize() {
if let scrollView = self.enclosingScrollView {
scrollView.hasVerticalScroller = false
}
super.viewWillStartLiveResize()
}
override func viewDidEndLiveResize() {
if let scrollView = self.enclosingScrollView {
scrollView.hasVerticalScroller = true
}
super.viewDidEndLiveResize()
}
// MARK: NSResponder
override func keyDown(with event: NSEvent) {
if keyboardDelegate.keydown(event, in: self) {
return
}
super.keyDown(with: event)
}
}
|
mit
|
59f12eaec80fa5d65fe042eb7c06ecfa
| 19.735294 | 70 | 0.719149 | 3.662338 | false | false | false | false |
overtake/TelegramSwift
|
Telegram-Mac/StickerPreviewHandler.swift
|
1
|
8745
|
//
// ModalPreviewHandler.swift
// Telegram
//
// Created by keepcoder on 02/02/2017.
// Copyright © 2017 Telegram. All rights reserved.
//
import Cocoa
import TelegramCore
import TGUIKit
import SwiftSignalKit
enum QuickPreviewMedia : Equatable {
case file(FileMediaReference, ModalPreviewControllerView.Type)
case image(ImageMediaReference, ModalPreviewControllerView.Type)
static func ==(lhs: QuickPreviewMedia, rhs: QuickPreviewMedia) -> Bool {
switch lhs {
case let .file(lhsReference, _):
if case let .file(rhsReference, _) = rhs {
return lhsReference.media.isEqual(to: rhsReference.media)
} else {
return false
}
case let .image(lhsReference, _):
if case let .image(rhsReference, _) = rhs {
return lhsReference.media.isEqual(to: rhsReference.media)
} else {
return false
}
}
}
var fileReference: FileMediaReference? {
switch self {
case let .file(reference, _):
return reference
default:
return nil
}
}
var imageReference: ImageMediaReference? {
switch self {
case let .image(reference, _):
return reference
default:
return nil
}
}
var viewType: ModalPreviewControllerView.Type {
switch self {
case let .file(_, type), let .image(_, type):
return type
}
}
}
extension GridNode : ModalPreviewProtocol {
func fileAtLocationInWindow(_ point: NSPoint) -> (QuickPreviewMedia, NSView?)? {
let point = self.documentView!.convert(point, from: nil)
var reference: (QuickPreviewMedia, NSView?)? = nil
self.forEachItemNode { node in
if NSPointInRect(point, node.frame) {
if let c = node as? ModalPreviewRowViewProtocol {
reference = c.fileAtPoint(node.convert(point, from: nil))
}
}
}
return reference
}
}
extension TableView : ModalPreviewProtocol {
func fileAtLocationInWindow(_ point: NSPoint) ->(QuickPreviewMedia, NSView?)? {
let index = self.row(at: documentView!.convert(point, from: nil))
if index != -1 {
let item = self.item(at: index)
if let view = self.viewNecessary(at: item.index), let c = view as? ModalPreviewRowViewProtocol {
return c.fileAtPoint(view.convert(point, from: nil))
}
}
return nil
}
}
protocol ModalPreviewRowViewProtocol {
func fileAtPoint(_ point:NSPoint) -> (QuickPreviewMedia, NSView?)?
}
protocol ModalPreviewProtocol {
func fileAtLocationInWindow(_ point:NSPoint) -> (QuickPreviewMedia, NSView?)?
}
protocol ModalPreviewControllerView : NSView {
func update(with reference: QuickPreviewMedia, context: AccountContext, animated: Bool)
func getContentView() -> NSView
}
fileprivate var handler:ModalPreviewHandler?
func startModalPreviewHandle(_ global:ModalPreviewProtocol, window:Window, context: AccountContext) {
handler = ModalPreviewHandler(global, window: window, context: context)
handler?.startHandler()
}
class ModalPreviewHandler : NSObject {
private let global:ModalPreviewProtocol
private let context:AccountContext
private let window:Window
private let modal:PreviewModalController
init(_ global:ModalPreviewProtocol, window:Window, context: AccountContext) {
self.global = global
self.window = window
self.context = context
self.modal = PreviewModalController(context)
}
func startHandler() {
let initial = global.fileAtLocationInWindow(window.mouseLocationOutsideOfEventStream)
if let initial = initial {
modal.update(with: initial.0)
let animation:ModalAnimationType
if let view = initial.1 {
var rect = view.convert(view.bounds, to: nil)
rect.origin.y = window.contentView!.frame.maxY - rect.maxY
animation = .scaleFrom(rect)
} else {
animation = .bottomToCenter
}
showModal(with: modal, for: window, animationType: animation)
window.set(mouseHandler: { [weak self] (_) -> KeyHandlerResult in
if let strongSelf = self, let reference = strongSelf.global.fileAtLocationInWindow(strongSelf.window.mouseLocationOutsideOfEventStream) {
strongSelf.modal.update(with: reference.0)
}
return .invoked
}, with: self, for: .leftMouseDragged, priority: .modal)
window.set(mouseHandler: { [weak self] (_) -> KeyHandlerResult in
self?.stopHandler()
return .invoked
}, with: self, for: .leftMouseUp, priority: .modal)
}
}
func stopHandler() {
window.removeAllHandlers(for: self)
if let view = self.global.fileAtLocationInWindow(self.window.mouseLocationOutsideOfEventStream)?.1 {
let content = modal.genericView.contentView?.getContentView() ?? modal.genericView
let rect = view.convert(view.bounds, to: modal.genericView.superview?.superview)
modal.close(animationType: .scaleToRect(rect, content))
} else {
modal.close()
}
handler = nil
}
deinit {
}
}
private final class PreviewModalView: View {
fileprivate var contentView: ModalPreviewControllerView?
required init(frame frameRect: NSRect) {
super.init(frame: frameRect)
}
deinit {
var bp:Int = 0
bp += 1
}
override func layout() {
super.layout()
}
func update(with preview: QuickPreviewMedia, context: AccountContext, animated: Bool) {
let viewType = preview.viewType
var changed = false
if contentView == nil || !contentView!.isKind(of: viewType) {
if animated {
let current = self.contentView
self.contentView = nil
current?.layer?.animateScaleSpring(from: 1, to: 0, duration: 0.2, removeOnCompletion: false, completion: { [weak current] completed in
if completed {
current?.removeFromSuperview()
}
})
} else {
self.contentView?.removeFromSuperview()
}
self.contentView = viewType.init(frame:NSZeroRect)
self.addSubview(self.contentView!)
changed = true
}
contentView?.frame = bounds
contentView?.update(with: preview, context: context, animated: animated && !changed)
if animated {
contentView?.layer?.animateScaleSpring(from: 0.5, to: 1.0, duration: 0.2)
}
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
class PreviewModalController: ModalViewController {
fileprivate let context:AccountContext
fileprivate var reference:QuickPreviewMedia?
init(_ context: AccountContext) {
self.context = context
super.init(frame: NSMakeRect(0, 0, min(context.window.frame.width - 50, 500), min(500, context.window.frame.height - 50)))
bar = .init(height: 0)
}
override var hasOwnTouchbar: Bool {
return false
}
override var containerBackground: NSColor {
return .clear
}
override func becomeFirstResponder() -> Bool? {
return nil
}
override var handleEvents:Bool {
return false
}
override func viewDidLoad() {
super.viewDidLoad()
if let reference = reference {
genericView.update(with: reference, context: context, animated: false)
}
readyOnce()
}
func update(with reference:QuickPreviewMedia?) {
if self.reference != reference {
self.reference = reference
if isLoaded(), let reference = reference {
genericView.update(with: reference, context: context, animated: true)
}
}
}
fileprivate var genericView:PreviewModalView {
return view as! PreviewModalView
}
override func viewClass() -> AnyClass {
return PreviewModalView.self
}
deinit {
var bp:Int = 0
bp += 1
}
// override var isFullScreen: Bool {
// return true
// }
}
|
gpl-2.0
|
bd734e42cfa82fad8315b87372cab9c4
| 29.788732 | 153 | 0.592749 | 4.945701 | false | false | false | false |
PiHanHsu/myscorebaord_lite
|
myscoreboard_lite/Resource/Reachability.swift
|
14
|
11028
|
/*
Copyright (c) 2014, Ashley Mills
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. 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.
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 SystemConfiguration
import Foundation
public enum ReachabilityError: Error {
case FailedToCreateWithAddress(sockaddr_in)
case FailedToCreateWithHostname(String)
case UnableToSetCallback
case UnableToSetDispatchQueue
}
@available(*, unavailable, renamed: "Notification.Name.reachabilityChanged")
public let ReachabilityChangedNotification = NSNotification.Name("ReachabilityChangedNotification")
extension Notification.Name {
public static let reachabilityChanged = Notification.Name("reachabilityChanged")
}
func callback(reachability:SCNetworkReachability, flags: SCNetworkReachabilityFlags, info: UnsafeMutableRawPointer?) {
guard let info = info else { return }
let reachability = Unmanaged<Reachability>.fromOpaque(info).takeUnretainedValue()
reachability.reachabilityChanged()
}
public class Reachability {
public typealias NetworkReachable = (Reachability) -> ()
public typealias NetworkUnreachable = (Reachability) -> ()
@available(*, unavailable, renamed: "Conection")
public enum NetworkStatus: CustomStringConvertible {
case notReachable, reachableViaWiFi, reachableViaWWAN
public var description: String {
switch self {
case .reachableViaWWAN: return "Cellular"
case .reachableViaWiFi: return "WiFi"
case .notReachable: return "No Connection"
}
}
}
public enum Connection: CustomStringConvertible {
case none, wifi, cellular
public var description: String {
switch self {
case .cellular: return "Cellular"
case .wifi: return "WiFi"
case .none: return "No Connection"
}
}
}
public var whenReachable: NetworkReachable?
public var whenUnreachable: NetworkUnreachable?
@available(*, deprecated: 4.0, renamed: "allowsCellularConnection")
public let reachableOnWWAN: Bool = true
/// Set to `false` to force Reachability.connection to .none when on cellular connection (default value `true`)
public var allowsCellularConnection: Bool
// The notification center on which "reachability changed" events are being posted
public var notificationCenter: NotificationCenter = NotificationCenter.default
@available(*, deprecated: 4.0, renamed: "connection.description")
public var currentReachabilityString: String {
return "\(connection)"
}
@available(*, unavailable, renamed: "connection")
public var currentReachabilityStatus: Connection {
return connection
}
public var connection: Connection {
guard isReachableFlagSet else { return .none }
// If we're reachable, but not on an iOS device (i.e. simulator), we must be on WiFi
guard isRunningOnDevice else { return .wifi }
var connection = Connection.none
if !isConnectionRequiredFlagSet {
connection = .wifi
}
if isConnectionOnTrafficOrDemandFlagSet {
if !isInterventionRequiredFlagSet {
connection = .wifi
}
}
if isOnWWANFlagSet {
if !allowsCellularConnection {
connection = .none
} else {
connection = .cellular
}
}
return connection
}
fileprivate var previousFlags: SCNetworkReachabilityFlags?
fileprivate var isRunningOnDevice: Bool = {
#if (arch(i386) || arch(x86_64)) && os(iOS)
return false
#else
return true
#endif
}()
fileprivate var notifierRunning = false
fileprivate let reachabilityRef: SCNetworkReachability
fileprivate let reachabilitySerialQueue = DispatchQueue(label: "uk.co.ashleymills.reachability")
required public init(reachabilityRef: SCNetworkReachability) {
allowsCellularConnection = true
self.reachabilityRef = reachabilityRef
}
public convenience init?(hostname: String) {
guard let ref = SCNetworkReachabilityCreateWithName(nil, hostname) else { return nil }
self.init(reachabilityRef: ref)
}
public convenience init?() {
var zeroAddress = sockaddr()
zeroAddress.sa_len = UInt8(MemoryLayout<sockaddr>.size)
zeroAddress.sa_family = sa_family_t(AF_INET)
guard let ref = SCNetworkReachabilityCreateWithAddress(nil, &zeroAddress) else { return nil }
self.init(reachabilityRef: ref)
}
deinit {
stopNotifier()
}
}
public extension Reachability {
// MARK: - *** Notifier methods ***
func startNotifier() throws {
guard !notifierRunning else { return }
var context = SCNetworkReachabilityContext(version: 0, info: nil, retain: nil, release: nil, copyDescription: nil)
context.info = UnsafeMutableRawPointer(Unmanaged<Reachability>.passUnretained(self).toOpaque())
if !SCNetworkReachabilitySetCallback(reachabilityRef, callback, &context) {
stopNotifier()
throw ReachabilityError.UnableToSetCallback
}
if !SCNetworkReachabilitySetDispatchQueue(reachabilityRef, reachabilitySerialQueue) {
stopNotifier()
throw ReachabilityError.UnableToSetDispatchQueue
}
// Perform an initial check
reachabilitySerialQueue.async {
self.reachabilityChanged()
}
notifierRunning = true
}
func stopNotifier() {
defer { notifierRunning = false }
SCNetworkReachabilitySetCallback(reachabilityRef, nil, nil)
SCNetworkReachabilitySetDispatchQueue(reachabilityRef, nil)
}
// MARK: - *** Connection test methods ***
@available(*, deprecated: 4.0, message: "Please use `connection != .none`")
var isReachable: Bool {
guard isReachableFlagSet else { return false }
if isConnectionRequiredAndTransientFlagSet {
return false
}
if isRunningOnDevice {
if isOnWWANFlagSet && !reachableOnWWAN {
// We don't want to connect when on cellular connection
return false
}
}
return true
}
@available(*, deprecated: 4.0, message: "Please use `connection == .cellular`")
var isReachableViaWWAN: Bool {
// Check we're not on the simulator, we're REACHABLE and check we're on WWAN
return isRunningOnDevice && isReachableFlagSet && isOnWWANFlagSet
}
@available(*, deprecated: 4.0, message: "Please use `connection == .wifi`")
var isReachableViaWiFi: Bool {
// Check we're reachable
guard isReachableFlagSet else { return false }
// If reachable we're reachable, but not on an iOS device (i.e. simulator), we must be on WiFi
guard isRunningOnDevice else { return true }
// Check we're NOT on WWAN
return !isOnWWANFlagSet
}
var description: String {
let W = isRunningOnDevice ? (isOnWWANFlagSet ? "W" : "-") : "X"
let R = isReachableFlagSet ? "R" : "-"
let c = isConnectionRequiredFlagSet ? "c" : "-"
let t = isTransientConnectionFlagSet ? "t" : "-"
let i = isInterventionRequiredFlagSet ? "i" : "-"
let C = isConnectionOnTrafficFlagSet ? "C" : "-"
let D = isConnectionOnDemandFlagSet ? "D" : "-"
let l = isLocalAddressFlagSet ? "l" : "-"
let d = isDirectFlagSet ? "d" : "-"
return "\(W)\(R) \(c)\(t)\(i)\(C)\(D)\(l)\(d)"
}
}
fileprivate extension Reachability {
func reachabilityChanged() {
guard previousFlags != flags else { return }
let block = connection != .none ? whenReachable : whenUnreachable
DispatchQueue.main.async {
block?(self)
self.notificationCenter.post(name: .reachabilityChanged, object:self)
}
previousFlags = flags
}
var isOnWWANFlagSet: Bool {
#if os(iOS)
return flags.contains(.isWWAN)
#else
return false
#endif
}
var isReachableFlagSet: Bool {
return flags.contains(.reachable)
}
var isConnectionRequiredFlagSet: Bool {
return flags.contains(.connectionRequired)
}
var isInterventionRequiredFlagSet: Bool {
return flags.contains(.interventionRequired)
}
var isConnectionOnTrafficFlagSet: Bool {
return flags.contains(.connectionOnTraffic)
}
var isConnectionOnDemandFlagSet: Bool {
return flags.contains(.connectionOnDemand)
}
var isConnectionOnTrafficOrDemandFlagSet: Bool {
return !flags.intersection([.connectionOnTraffic, .connectionOnDemand]).isEmpty
}
var isTransientConnectionFlagSet: Bool {
return flags.contains(.transientConnection)
}
var isLocalAddressFlagSet: Bool {
return flags.contains(.isLocalAddress)
}
var isDirectFlagSet: Bool {
return flags.contains(.isDirect)
}
var isConnectionRequiredAndTransientFlagSet: Bool {
return flags.intersection([.connectionRequired, .transientConnection]) == [.connectionRequired, .transientConnection]
}
var flags: SCNetworkReachabilityFlags {
var flags = SCNetworkReachabilityFlags()
if SCNetworkReachabilityGetFlags(reachabilityRef, &flags) {
return flags
} else {
return SCNetworkReachabilityFlags()
}
}
}
|
mit
|
1af16cbeb4a02bdb52956308f6cf214a
| 32.828221 | 125 | 0.653065 | 5.699225 | false | false | false | false |
illescasDaniel/Questions
|
Questions/Models/Question.swift
|
1
|
1112
|
//
// QuestionType.swift
// Questions
//
// Created by Daniel Illescas Romero on 24/05/2018.
// Copyright © 2018 Daniel Illescas Romero. All rights reserved.
//
import Foundation
class Question: Codable, CustomStringConvertible {
let question: String
let answers: [String]
var correctAnswers: Set<UInt8>! = []
let correct: UInt8?
let imageURL: String?
init(question: String, answers: [String], correct: Set<UInt8>, singleCorrect: UInt8? = nil, imageURL: String? = nil) {
self.question = question.trimmingCharacters(in: .whitespacesAndNewlines)
self.answers = answers.map({ $0.trimmingCharacters(in: .whitespacesAndNewlines) })
self.correctAnswers = correct
self.correct = singleCorrect
self.imageURL = imageURL?.trimmingCharacters(in: .whitespacesAndNewlines)
}
}
extension Question: Equatable {
static func ==(lhs: Question, rhs: Question) -> Bool {
return lhs.question == rhs.question && lhs.answers == rhs.answers && lhs.correctAnswers == rhs.correctAnswers
}
}
extension Question: Hashable {
func hash(into hasher: inout Hasher) {
hasher.combine(self.question.hash)
}
}
|
mit
|
344ed7553de3d84f9e9e86375077a2c5
| 28.236842 | 119 | 0.730873 | 3.728188 | false | false | false | false |
marcelganczak/swift-js-transpiler
|
test/weheartswift/loops-13.swift
|
1
|
106
|
var N = 10
var a = 1
var b = 0
for _ in 1...N {
print(a)
var tmp = a + b
b = a
a = tmp
}
|
mit
|
20db3c4045251342b240799092b82d1b
| 8.727273 | 19 | 0.40566 | 2.304348 | false | false | false | false |
phatblat/realm-cocoa
|
RealmSwift/RealmKeyedCollection.swift
|
2
|
24526
|
////////////////////////////////////////////////////////////////////////////
//
// Copyright 2021 Realm Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////
import Foundation
import Realm
/**
A homogenous key-value collection of `Object`s which can be retrieved, filtered, sorted, and operated upon.
*/
public protocol RealmKeyedCollection: Sequence, ThreadConfined, CustomStringConvertible {
/// The type of key associated with this collection
associatedtype Key: _MapKey
/// The type of value associated with this collection.
associatedtype Value: RealmCollectionValue
// MARK: Properties
/// The Realm which manages the map, or `nil` if the map is unmanaged.
var realm: Realm? { get }
/// Indicates if the map can no longer be accessed.
var isInvalidated: Bool { get }
/// Returns the number of key-value pairs in this map.
var count: Int { get }
/// A human-readable description of the objects contained in the Map.
var description: String { get }
// MARK: Mutation
/**
Updates the value stored in the dictionary for the given key, or adds a new key-value pair if the key does not exist.
- Note:If the value being added to the dictionary is an unmanaged object and the dictionary is managed
then that unmanaged object will be added to the Realm.
- warning: This method may only be called during a write transaction.
- parameter value: a value's key path predicate.
- parameter forKey: The direction to sort in.
*/
func updateValue(_ value: Value, forKey key: Key)
/**
Removes the given key and its associated object, only if the key exists in the dictionary. If the key does not
exist, the dictionary will not be modified.
- warning: This method may only be called during a write transaction.
*/
func removeObject(for key: Key)
/**
Removes all objects from the dictionary. The objects are not removed from the Realm that manages them.
- warning: This method may only be called during a write transaction.
*/
func removeAll()
/**
Returns the value for a given key, or sets a value for a key should the subscript be used for an assign.
- Note:If the value being added to the dictionary is an unmanaged object and the dictionary is managed
then that unmanaged object will be added to the Realm.
- Note:If the value being assigned for a key is `nil` then that key will be removed from the dictionary.
- warning: This method may only be called during a write transaction.
- parameter key: The key.
*/
subscript(key: Key) -> Value? { get set }
// MARK: KVC
/**
Returns a type of `Value` for a specified key if it exists in the map.
Note that when using key-value coding, the key must be a string.
- parameter key: The key to the property whose values are desired.
*/
func value(forKey key: String) -> AnyObject?
/**
Returns a type of `Value` for a specified key if it exists in the map.
- parameter keyPath: The key to the property whose values are desired.
*/
func value(forKeyPath keyPath: String) -> AnyObject?
/**
Adds a given key-value pair to the dictionary or updates a given key should it already exist.
- warning: This method can only be called during a write transaction.
- parameter value: The object value.
- parameter key: The name of the property whose value should be set on each object.
*/
func setValue(_ value: Any?, forKey key: String)
// MARK: Filtering
/**
Returns a `Results` containing all matching values in the dictionary with the given predicate.
- Note: This will return the values in the dictionary, and not the key-value pairs.
- parameter predicate: The predicate with which to filter the values.
*/
func filter(_ predicate: NSPredicate) -> Results<Value>
/**
Returns a Boolean value indicating whether the Map contains the key-value pair
satisfies the given predicate
- parameter where: a closure that test if any key-pair of the given map represents the match.
*/
func contains(where predicate: @escaping (_ key: Key, _ value: Value) -> Bool) -> Bool
// MARK: Sorting
/**
Returns a `Results` containing the objects in the dictionary, but sorted.
Objects are sorted based on their values. For example, to sort a dictionary of `Date`s from
neweset to oldest based, you might call `dates.sorted(ascending: true)`.
- parameter ascending: The direction to sort in.
*/
func sorted(ascending: Bool) -> Results<Value>
/**
Returns a `Results` containing the objects in the dictionary, but sorted.
Objects are sorted based on the values of the given key path. For example, to sort a dictionary of `Student`s from
youngest to oldest based on their `age` property, you might call
`students.sorted(byKeyPath: "age", ascending: true)`.
- warning: Dictionaries may only be sorted by properties of boolean, `Date`, `NSDate`, single and double-precision
floating point, integer, and string types.
- parameter keyPath: The key path to sort by.
- parameter ascending: The direction to sort in.
*/
func sorted(byKeyPath keyPath: String, ascending: Bool) -> Results<Value>
/**
Returns a `Results` containing the objects in the dictionary, but sorted.
- warning: Dictionaries may only be sorted by properties of boolean, `Date`, `NSDate`, single and double-precision
floating point, integer, and string types.
- see: `sorted(byKeyPath:ascending:)`
*/
func sorted<S: Sequence>(by sortDescriptors: S) -> Results<Value>
where S.Iterator.Element == SortDescriptor
/// Returns all of the keys in this dictionary.
var keys: [Key] { get }
/// Returns all of the values in the dictionary.
var values: [Value] { get }
// MARK: Aggregate Operations
/**
Returns the minimum (lowest) value of the given property among all the objects in the collection, or `nil` if the
dictionary is empty.
- warning: Only a property whose type conforms to the `MinMaxType` protocol can be specified.
- parameter property: The name of a property whose minimum value is desired.
*/
func min<T: MinMaxType>(ofProperty property: String) -> T?
/**
Returns the maximum (highest) value of the given property among all the objects in the dictionary, or `nil` if the
dictionary is empty.
- warning: Only a property whose type conforms to the `MinMaxType` protocol can be specified.
- parameter property: The name of a property whose minimum value is desired.
*/
func max<T: MinMaxType>(ofProperty property: String) -> T?
/**
Returns the sum of the given property for objects in the dictionary, or `nil` if the dictionary is empty.
- warning: Only names of properties of a type conforming to the `AddableType` protocol can be used.
- parameter property: The name of a property conforming to `AddableType` to calculate sum on.
*/
func sum<T: AddableType>(ofProperty property: String) -> T
/**
Returns the average value of a given property over all the objects in the dictionary, or `nil` if
the dictionary is empty.
- warning: Only a property whose type conforms to the `AddableType` protocol can be specified.
- parameter property: The name of a property whose values should be summed.
*/
func average<T: AddableType>(ofProperty property: String) -> T?
// MARK: Notifications
/**
Registers a block to be called each time the dictionary changes.
The block will be asynchronously called with the initial dictionary, and then called again after each write
transaction which changes either any of the keys or values in the dictionary.
The `change` parameter that is passed to the block reports, in the form of keys within the dictionary, which of
the key-value pairs were added, removed, or modified during each write transaction.
At the time when the block is called, the dictionary will be fully evaluated and up-to-date, and as long as you do
not perform a write transaction on the same thread or explicitly call `realm.refresh()`, accessing it will never
perform blocking work.
If no queue is given, notifications are delivered via the standard run loop, and so can't be delivered while the
run loop is blocked by other activity. If a queue is given, notifications are delivered to that queue instead. When
notifications can't be delivered instantly, multiple notifications may be coalesced into a single notification.
This can include the notification with the initial collection.
For example, the following code performs a write transaction immediately after adding the notification block, so
there is no opportunity for the initial notification to be delivered first. As a result, the initial notification
will reflect the state of the Realm after the write transaction.
```swift
let myStringMap = myObject.stringMap
print("myStringMap.count: \(myStringMap?.count)") // => 0
let token = myStringMap.observe { changes in
switch changes {
case .initial(let myStringMap):
// Will print "myStringMap.count: 1"
print("myStringMap.count: \(myStringMap.count)")
print("Dog Name: \(myStringMap["nameOfDog"])") // => "Rex"
break
case .update:
// Will not be hit in this example
break
case .error:
break
}
}
try! realm.write {
myStringMap["nameOfDog"] = "Rex"
}
// end of run loop execution context
```
You must retain the returned token for as long as you want updates to be sent to the block. To stop receiving
updates, call `invalidate()` on the token.
- warning: This method cannot be called during a write transaction, or when the containing Realm is read-only.
- parameter queue: The serial dispatch queue to receive notification on. If
`nil`, notifications are delivered to the current thread.
- parameter block: The block to be called whenever a change occurs.
- returns: A token which must be held for as long as you want updates to be delivered.
*/
func observe(on queue: DispatchQueue?,
_ block: @escaping (RealmMapChange<Self>) -> Void)
-> NotificationToken
/**
Registers a block to be called each time the dictionary changes.
The block will be asynchronously called with the initial dictionary, and then called again after each write
transaction which changes either any of the keys or values in the dictionary.
The `change` parameter that is passed to the block reports, in the form of keys within the dictionary, which of
the key-value pairs were added, removed, or modified during each write transaction.
At the time when the block is called, the dictionary will be fully evaluated and up-to-date, and as long as you do
not perform a write transaction on the same thread or explicitly call `realm.refresh()`, accessing it will never
perform blocking work.
If no queue is given, notifications are delivered via the standard run loop, and so can't be delivered while the
run loop is blocked by other activity. If a queue is given, notifications are delivered to that queue instead. When
notifications can't be delivered instantly, multiple notifications may be coalesced into a single notification.
This can include the notification with the initial collection.
For example, the following code performs a write transaction immediately after adding the notification block, so
there is no opportunity for the initial notification to be delivered first. As a result, the initial notification
will reflect the state of the Realm after the write transaction.
```swift
let myStringMap = myObject.stringMap
print("myStringMap.count: \(myStringMap?.count)") // => 0
let token = myStringMap.observe { changes in
switch changes {
case .initial(let myStringMap):
// Will print "myStringMap.count: 1"
print("myStringMap.count: \(myStringMap.count)")
print("Dog Name: \(myStringMap["nameOfDog"])") // => "Rex"
break
case .update:
// Will not be hit in this example
break
case .error:
break
}
}
try! realm.write {
myStringMap["nameOfDog"] = "Rex"
}
// end of run loop execution context
```
If no key paths are given, the block will be executed on any insertion,
modification, or deletion for all object properties and the properties of
any nested, linked objects. If a key path or key paths are provided,
then the block will be called for changes which occur only on the
provided key paths. For example, if:
```swift
class Dog: Object {
@Persisted var name: String
@Persisted var age: Int
@Persisted var toys: List<Toy>
}
// ...
let dogs = myObject.mapOfDogs
let token = dogs.observe(keyPaths: ["name"]) { changes in
switch changes {
case .initial(let dogs):
// ...
case .update:
// This case is hit:
// - after the token is intialized
// - when the name property of an object in the
// collection is modified
// - when an element is inserted or removed
// from the collection.
// This block is not triggered:
// - when a value other than name is modified on
// one of the elements.
case .error:
// ...
}
}
// end of run loop execution context
```
- If the observed key path were `["toys.brand"]`, then any insertion or
deletion to the `toys` list on any of the collection's elements would trigger the block.
Changes to the `brand` value on any `Toy` that is linked to a `Dog` in this
collection will trigger the block. Changes to a value other than `brand` on any `Toy` that
is linked to a `Dog` in this collection would not trigger the block.
Any insertion or removal to the `Dog` type collection being observed
would also trigger a notification.
- If the above example observed the `["toys"]` key path, then any insertion,
deletion, or modification to the `toys` list for any element in the collection
would trigger the block.
Changes to any value on any `Toy` that is linked to a `Dog` in this collection
would *not* trigger the block.
Any insertion or removal to the `Dog` type collection being observed
would still trigger a notification.
- note: Multiple notification tokens on the same object which filter for
separate key paths *do not* filter exclusively. If one key path
change is satisfied for one notification token, then all notification
token blocks for that object will execute.
You must retain the returned token for as long as you want updates to be sent to the block. To stop receiving
updates, call `invalidate()` on the token.
- warning: This method cannot be called during a write transaction, or when the containing Realm is read-only.
- parameter keyPaths: Only properties contained in the key paths array will trigger
the block when they are modified. If `nil`, notifications
will be delivered for any property change on the object.
String key paths which do not correspond to a valid a property
will throw an exception.
See description above for more detail on linked properties.
- note: The keyPaths parameter refers to object properties of the collection type and
*does not* refer to particular key/value pairs within the collection.
- parameter queue: The serial dispatch queue to receive notification on. If
`nil`, notifications are delivered to the current thread.
- parameter block: The block to be called whenever a change occurs.
- returns: A token which must be held for as long as you want updates to be delivered.
*/
func observe(keyPaths: [String]?,
on queue: DispatchQueue?,
_ block: @escaping (RealmMapChange<Self>) -> Void) -> NotificationToken
// MARK: Frozen Objects
/// Returns if this collection is frozen
var isFrozen: Bool { get }
/**
Returns a frozen (immutable) snapshot of this collection.
The frozen copy is an immutable collection which contains the same data as this collection
currently contains, but will not update when writes are made to the containing Realm. Unlike
live collections, frozen collections can be accessed from any thread.
- warning: This method cannot be called during a write transaction, or when the containing
Realm is read-only.
- warning: Holding onto a frozen collection for an extended period while performing write
transaction on the Realm may result in the Realm file growing to large sizes. See
`Realm.Configuration.maximumNumberOfActiveVersions` for more information.
*/
func freeze() -> Self
/**
Returns a live (mutable) version of this frozen collection.
This method resolves a reference to a live copy of the same frozen collection.
If called on a live collection, will return itself.
*/
func thaw() -> Self?
}
/**
Protocol for RealmKeyedCollections where the Value is of an Object type that
enables aggregatable operations.
*/
public extension RealmKeyedCollection where Value: OptionalProtocol, Value.Wrapped: ObjectBase, Value.Wrapped: RealmCollectionValue {
/**
Returns the minimum (lowest) value of the given property among all the objects in the collection, or `nil` if the
collection is empty.
- warning: Only a property whose type conforms to the `MinMaxType` protocol can be specified.
- parameter keyPath: The keyPath of a property whose minimum value is desired.
*/
func min<T: MinMaxType>(of keyPath: KeyPath<Value.Wrapped, T>) -> T? {
min(ofProperty: _name(for: keyPath))
}
/**
Returns the maximum (highest) value of the given property among all the objects in the collection, or `nil` if the
collection is empty.
- warning: Only a property whose type conforms to the `MinMaxType` protocol can be specified.
- parameter keyPath: The keyPath of a property whose minimum value is desired.
*/
func max<T: MinMaxType>(of keyPath: KeyPath<Value.Wrapped, T>) -> T? {
max(ofProperty: _name(for: keyPath))
}
/**
Returns the sum of the given property for objects in the collection, or `nil` if the collection is empty.
- warning: Only names of properties of a type conforming to the `AddableType` protocol can be used.
- parameter keyPath: The keyPath of a property conforming to `AddableType` to calculate sum on.
*/
func sum<T: AddableType>(of keyPath: KeyPath<Value.Wrapped, T>) -> T {
sum(ofProperty: _name(for: keyPath))
}
/**
Returns the average value of a given property over all the objects in the collection, or `nil` if
the collection is empty.
- warning: Only a property whose type conforms to the `AddableType` protocol can be specified.
- parameter keyPath: The keyPath of a property whose values should be summed.
*/
func average<T: AddableType>(of keyPath: KeyPath<Value.Wrapped, T>) -> T? {
average(ofProperty: _name(for: keyPath))
}
}
// MARK: Sortable
/**
Protocol for RealmKeyedCollections where the Value is of an Object type that
enables sortable operations.
*/
public extension RealmKeyedCollection where Value: OptionalProtocol, Value.Wrapped: ObjectBase, Value.Wrapped: RealmCollectionValue {
/**
Returns a `Results` containing the objects in the collection, but sorted.
Objects are sorted based on the values of the given key path. For example, to sort a collection of `Student`s from
youngest to oldest based on their `age` property, you might call
`students.sorted(byKeyPath: "age", ascending: true)`.
- warning: Collections may only be sorted by properties of boolean, `Date`, `NSDate`, single and double-precision
floating point, integer, and string types.
- parameter keyPath: The key path to sort by.
- parameter ascending: The direction to sort in.
*/
func sorted<T: Comparable>(by keyPath: KeyPath<Value.Wrapped, T>, ascending: Bool) -> Results<Value> {
sorted(byKeyPath: _name(for: keyPath), ascending: ascending)
}
}
public extension RealmKeyedCollection where Value: MinMaxType {
/**
Returns the minimum (lowest) value of the collection, or `nil` if the collection is empty.
*/
func min() -> Value? {
return min(ofProperty: "self")
}
/**
Returns the maximum (highest) value of the collection, or `nil` if the collection is empty.
*/
func max() -> Value? {
return max(ofProperty: "self")
}
}
public extension RealmKeyedCollection where Value: OptionalProtocol, Value.Wrapped: MinMaxType {
/**
Returns the minimum (lowest) value of the collection, or `nil` if the collection is empty.
*/
func min() -> Value.Wrapped? {
return min(ofProperty: "self")
}
/**
Returns the maximum (highest) value of the collection, or `nil` if the collection is empty.
*/
func max() -> Value.Wrapped? {
return max(ofProperty: "self")
}
}
public extension RealmKeyedCollection where Value: AddableType {
/**
Returns the sum of the values in the collection, or `nil` if the collection is empty.
*/
func sum() -> Value {
return sum(ofProperty: "self")
}
/**
Returns the average of all of the values in the collection.
*/
func average<T: AddableType>() -> T? {
return average(ofProperty: "self")
}
}
public extension RealmKeyedCollection where Value: OptionalProtocol, Value.Wrapped: AddableType {
/**
Returns the sum of the values in the collection, or `nil` if the collection is empty.
*/
func sum() -> Value.Wrapped {
return sum(ofProperty: "self")
}
/**
Returns the average of all of the values in the collection.
*/
func average<T: AddableType>() -> T? {
return average(ofProperty: "self")
}
}
public extension RealmKeyedCollection where Value: Comparable {
/**
Returns a `Results` containing the objects in the collection, but sorted.
Objects are sorted based on their values. For example, to sort a collection of `Date`s from
neweset to oldest based, you might call `dates.sorted(ascending: true)`.
- parameter ascending: The direction to sort in.
*/
func sorted(ascending: Bool = true) -> Results<Value> {
return sorted(byKeyPath: "self", ascending: ascending)
}
}
public extension RealmKeyedCollection where Value: OptionalProtocol, Value.Wrapped: Comparable {
/**
Returns a `Results` containing the objects in the collection, but sorted.
Objects are sorted based on their values. For example, to sort a collection of `Date`s from
neweset to oldest based, you might call `dates.sorted(ascending: true)`.
- parameter ascending: The direction to sort in.
*/
func sorted(ascending: Bool = true) -> Results<Value> {
return sorted(byKeyPath: "self", ascending: ascending)
}
}
|
apache-2.0
|
dbf4d2371353c1ed73a6449dd26be0e9
| 40.289562 | 133 | 0.674386 | 4.7485 | false | false | false | false |
i-schuetz/SwiftCharts
|
SwiftCharts/Views/StraightLinePathGenerator.swift
|
1
|
1450
|
//
// StraigthLinePathGenerator.swift
// SwiftCharts
//
// Created by ischuetz on 28/04/15.
// Copyright (c) 2015 ivanschuetz. All rights reserved.
//
import UIKit
open class StraightLinePathGenerator: ChartLinesViewPathGenerator {
public init() {}
open func generatePath(points: [CGPoint], lineWidth: CGFloat) -> UIBezierPath {
let progressline = UIBezierPath()
if points.count >= 2 {
progressline.lineWidth = lineWidth
progressline.lineCapStyle = .round
progressline.lineJoinStyle = .round
for i in 0..<(points.count - 1) {
let p1 = points[i]
let p2 = points[i + 1]
progressline.move(to: p1)
progressline.addLine(to: p2)
}
}
return progressline
}
open func generateAreaPath(points: [CGPoint], lineWidth: CGFloat) -> UIBezierPath {
let progressline = UIBezierPath()
progressline.lineWidth = 1.0
progressline.lineCapStyle = .round
progressline.lineJoinStyle = .round
if let p = points.first {
progressline.move(to: p)
}
if points.count >= 2 {
for i in 1..<points.count {
let p = points[i]
progressline.addLine(to: p)
}
}
return progressline
}
}
|
apache-2.0
|
d1417a49df70b97a65b967c22ea4b90c
| 24.438596 | 87 | 0.537241 | 4.865772 | false | false | false | false |
esttorhe/SlackTeamExplorer
|
SlackTeamExplorer/Pods/Nimble/Nimble/Matchers/RaisesException.swift
|
28
|
6068
|
import Foundation
/// A Nimble matcher that succeeds when the actual expression raises an
/// exception with the specified name, reason, and/or userInfo.
///
/// Alternatively, you can pass a closure to do any arbitrary custom matching
/// to the raised exception. The closure only gets called when an exception
/// is raised.
///
/// nil arguments indicates that the matcher should not attempt to match against
/// that parameter.
public func raiseException(
named: String? = nil,
reason: String? = nil,
userInfo: NSDictionary? = nil,
closure: ((NSException) -> Void)? = nil) -> MatcherFunc<Any> {
return MatcherFunc { actualExpression, failureMessage in
var exception: NSException?
var capture = NMBExceptionCapture(handler: ({ e in
exception = e
}), finally: nil)
capture.tryBlock {
actualExpression.evaluate()
return
}
setFailureMessageForException(failureMessage, exception, named, reason, userInfo, closure)
return exceptionMatchesNonNilFieldsOrClosure(exception, named, reason, userInfo, closure)
}
}
internal func setFailureMessageForException(
failureMessage: FailureMessage,
exception: NSException?,
named: String?,
reason: String?,
userInfo: NSDictionary?,
closure: ((NSException) -> Void)?) {
failureMessage.postfixMessage = "raise exception"
if let named = named {
failureMessage.postfixMessage += " with name <\(named)>"
}
if let reason = reason {
failureMessage.postfixMessage += " with reason <\(reason)>"
}
if let userInfo = userInfo {
failureMessage.postfixMessage += " with userInfo <\(userInfo)>"
}
if let closure = closure {
failureMessage.postfixMessage += " that satisfies block"
}
if named == nil && reason == nil && userInfo == nil && closure == nil {
failureMessage.postfixMessage = "raise any exception"
}
if let exception = exception {
failureMessage.actualValue = "\(NSStringFromClass(exception.dynamicType)) { name=\(exception.name), reason='\(stringify(exception.reason))', userInfo=\(stringify(exception.userInfo)) }"
} else {
failureMessage.actualValue = "no exception"
}
}
internal func exceptionMatchesNonNilFieldsOrClosure(
exception: NSException?,
named: String?,
reason: String?,
userInfo: NSDictionary?,
closure: ((NSException) -> Void)?) -> Bool {
var matches = false
if let exception = exception {
matches = true
if named != nil && exception.name != named {
matches = false
}
if reason != nil && exception.reason != reason {
matches = false
}
if userInfo != nil && exception.userInfo != userInfo {
matches = false
}
if let closure = closure {
let assertions = gatherFailingExpectations {
closure(exception)
}
let messages = map(assertions) { $0.message }
if messages.count > 0 {
matches = false
}
}
}
return matches
}
@objc public class NMBObjCRaiseExceptionMatcher : NMBMatcher {
internal var _name: String?
internal var _reason: String?
internal var _userInfo: NSDictionary?
internal var _block: ((NSException) -> Void)?
internal init(name: String?, reason: String?, userInfo: NSDictionary?, block: ((NSException) -> Void)?) {
_name = name
_reason = reason
_userInfo = userInfo
_block = block
}
public func matches(actualBlock: () -> NSObject!, failureMessage: FailureMessage, location: SourceLocation) -> Bool {
let block: () -> Any? = ({ actualBlock(); return nil })
let expr = Expression(expression: block, location: location)
return raiseException(
named: _name,
reason: _reason,
userInfo: _userInfo,
closure: _block
).matches(expr, failureMessage: failureMessage)
}
public func doesNotMatch(actualBlock: () -> NSObject!, failureMessage: FailureMessage, location: SourceLocation) -> Bool {
return !matches(actualBlock, failureMessage: failureMessage, location: location)
}
public var named: (name: String) -> NMBObjCRaiseExceptionMatcher {
return ({ name in
return NMBObjCRaiseExceptionMatcher(
name: name,
reason: self._reason,
userInfo: self._userInfo,
block: self._block
)
})
}
public var reason: (reason: String?) -> NMBObjCRaiseExceptionMatcher {
return ({ reason in
return NMBObjCRaiseExceptionMatcher(
name: self._name,
reason: reason,
userInfo: self._userInfo,
block: self._block
)
})
}
public var userInfo: (userInfo: NSDictionary?) -> NMBObjCRaiseExceptionMatcher {
return ({ userInfo in
return NMBObjCRaiseExceptionMatcher(
name: self._name,
reason: self._reason,
userInfo: userInfo,
block: self._block
)
})
}
public var satisfyingBlock: (block: ((NSException) -> Void)?) -> NMBObjCRaiseExceptionMatcher {
return ({ block in
return NMBObjCRaiseExceptionMatcher(
name: self._name,
reason: self._reason,
userInfo: self._userInfo,
block: block
)
})
}
}
extension NMBObjCMatcher {
public class func raiseExceptionMatcher() -> NMBObjCRaiseExceptionMatcher {
return NMBObjCRaiseExceptionMatcher(name: nil, reason: nil, userInfo: nil, block: nil)
}
}
|
mit
|
dc4d566f19e01fa6ab02842679d9c031
| 33.089888 | 197 | 0.580257 | 5.481481 | false | false | false | false |
Wolox/wolmo-core-ios
|
WolmoCoreTests/Extensions/UIKit/UICollectionViewSpec.swift
|
1
|
5029
|
//
// UICollectionViewSpec.swift
// WolmoCore
//
// Created by Daniela Riesgo on 4/19/17.
// Copyright © 2017 Wolox. All rights reserved.
//
import Foundation
import Quick
import Nimble
import WolmoCore
public class UICollectionViewSpec: QuickSpec, UICollectionViewDataSource, UICollectionViewDelegate {
public func numberOfSections(in collectionView: UICollectionView) -> Int {
return 5
}
public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 2
}
public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
return UICollectionViewCell()
}
public func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
return UICollectionReusableView()
}
override public func spec() {
var collectionView: UICollectionView!
beforeEach {
collectionView = NibLoadableUICollectionView.loadFromNib()!
collectionView.dataSource = self
collectionView.delegate = self
collectionView.reloadData()
}
describe("#register(cell:) and #dequeue(cell:for:)") {
context("when dequeing an already registered cell") {
it("should return the loaded cell") {
collectionView.register(cell: NibLoadableCollectionCell.self)
let cell = collectionView.dequeue(cell: NibLoadableCollectionCell.self, for: IndexPath(row: 0, section: 0))
expect(cell).toNot(beNil())
}
}
context("when dequeing a not before registered cell") {
it("should return .none") {
expect(collectionView.dequeue(cell: NibLoadableCollectionCell.self, for: IndexPath(row: 0, section: 0)))
.to(raiseException(named: "NSInternalInconsistencyException"))
}
}
}
//Test failing because of error: "NSInternalInconsistencyException",
//"request for layout attributes for supplementary view UICollectionElementKindSectionHeader in section 0 when there are only 0 sections in the collection view"
//But don't know why.
/*
describe("#register(header:) and #dequeue(header:for:)") {
context("when dequeing an already registered header") {
it("should return the loaded view") {
collectionView.register(header: NibLoadableCollectionView.self)
let view = collectionView.dequeue(header: NibLoadableCollectionView.self, for: IndexPath(row: 0, section: 0))
expect(view).toNot(beNil())
}
}
context("when dequeing a view registered for footer") {
it("should return .none") {
collectionView.register(footer: NibLoadableCollectionView.self)
expect(collectionView.dequeue(header: NibLoadableCollectionView.self, for: IndexPath(row: 0, section: 0)))
.to(raiseException(named: "NSInternalInconsistencyException"))
}
}
context("when dequeing a not before registered view") {
it("should return .none") {
expect(collectionView.dequeue(header: NibLoadableCollectionView.self, for: IndexPath(row: 0, section: 0)))
.to(raiseException(named: "NSInternalInconsistencyException"))
}
}
}
describe("#register(footer:) and #dequeue(footer:for:)") {
context("when dequeing an already registered footer") {
it("should return the loaded view") {
collectionView.register(footer: NibLoadableCollectionView.self)
let view = collectionView.dequeue(footer: NibLoadableCollectionView.self, for: IndexPath(row: 0, section: 0))
expect(view).toNot(beNil())
}
}
context("when dequeing a view registered for header") {
it("should return .none") {
collectionView.register(header: NibLoadableCollectionView.self)
expect(collectionView.dequeue(footer: NibLoadableCollectionView.self, for: IndexPath(row: 0, section: 0)))
.to(raiseException(named: "NSInternalInconsistencyException"))
}
}
context("when dequeing a not before registered view") {
it("should return .none") {
expect(collectionView.dequeue(footer: NibLoadableCollectionView.self, for: IndexPath(row: 0, section: 0)))
.to(raiseException(named: "NSInternalInconsistencyException"))
}
}
}
*/
}
}
|
mit
|
2d0ad52eeafa13dbad0149b9e1568775
| 45.990654 | 169 | 0.604614 | 5.766055 | false | false | false | false |
airspeedswift/swift-compiler-crashes
|
crashes-fuzzing/00901-ab.swift
|
1
|
2213
|
// Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
g..startIndex, AnyObject)
import Foundation
import Foundation
enum b {
}
func i: (x) -> String {
convenience init(c
}
public var b)
protocol A {
protocol B = g: NSObject {
}
func b: $0
self.startIndex)
}
case C: l) -> {
}
typealias B = a<c({
}
}
class func c<b[T]({
typealias E
for b = f<d()):
var a: d) {
for ([0x31] = ""ab"
var a<Int], AnyObject> (x) -> {
}
class b
class A {
class a(T) -> String {
func c<B : A: A, T> String {
}
}
class A {
protocol A {
return ""foo"
}
}
func g
}
class b: end)
protocol b = {
}
i<d {
class a<T>([B
}
case c, 3] = []
typealias e : Any, b = nil
}
struct e {
class A.b where I.c: a {
func c() -> Any in
}
class C(T>("
struct c(_ c<h == d
return !.Type) -> Any in
}
struct S : d where H) -> T>
}
}
func c
enum A {
for b {
i> {
convenience init(c, range.e : a {
typealias b {
enum A where d
class func b, let i<T.e> ("".h>Bool)
}
}
}
self.Type
class B == D> S(bytes: T
func g<e, b {
}
class A {
}
case A<T>()(x: A.c where T> (A> {
}
}
return "ab")
typealias e = {
typealias C {
func f(start: ([c) in return b, U>() ->(b.f == a(start, object2: T) -> String {
func g.count]]("")?
}
protocol A : T> Any) -> V, let end = .E == ""A.<T : d where A.c {
}
func a"
}
protocol A {
func e: ()
protocol a {
}
class A<I : Int -> A {
}
let foo as [[])()
}
}
protocol b {
b() -> U) -> Bool {
}
}
func b: c, c: NSManagedObject {
}
}
struct Q<Y> Bool {
get
struct c, U) -> Any, e == {
func i() -> U {
typealias d: P {
}
}
self.endIndex - range.f == { }
let i: c<T: start, i> T {
func a(""
return [Int
struct e = e!)
return { _, g : C {
map()
protocol a = {
extension NSData {
class C("[1].f = nil
convenience init(x) {
if true }
let v: b
}
}
enum A {
map(x: A : d where B = e: b {
}
}
import Foundation
d: A<T> Any, Any) {
self.E
}
class func c, x }
}
}
var a: S(bytes: A>(c<b
extension String {
class b()
struct c {
typealias B<T>(b> A {
for ()
}
extension Array {
func a<T> Any] in
func f() -> : T : d = { }
}
}
}
}
self.e = {
typealias e = T) {
func a<T>] = b.a("
let i: B<T.B : B? = b: c: A, AnyObject, y)
}
struct B<T>()
fu
|
mit
|
293ea65fdaf2e8b50b688f97812fe807
| 12.493902 | 87 | 0.564844 | 2.366845 | false | false | false | false |
therealbnut/swift
|
test/ClangImporter/objc_ir.swift
|
2
|
15951
|
// RUN: rm -rf %t && mkdir -p %t
// RUN: %build-clang-importer-objc-overlays
// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk-nosource -I %t) -I %S/Inputs/custom-modules -emit-ir -o - -primary-file %s | %FileCheck %s
// REQUIRES: objc_interop
// REQUIRES: OS=macosx
// CHECK: [[B:%CSo1B]] = type
import ObjectiveC
import Foundation
import objc_ext
import TestProtocols
import ObjCIRExtras
// CHECK: @"\01L_selector_data(method:withFloat:)" = private global [18 x i8] c"method:withFloat:\00"
// CHECK: @"\01L_selector_data(method:withDouble:)" = private global [19 x i8] c"method:withDouble:\00"
// CHECK: @"\01L_selector_data(method:separateExtMethod:)" = private global [26 x i8] c"method:separateExtMethod:\00", section "__TEXT,__objc_methname,cstring_literals"
// Instance method invocation
// CHECK: define hidden void @_TF7objc_ir15instanceMethodsFCSo1BT_([[B]]*
func instanceMethods(_ b: B) {
// CHECK: load i8*, i8** @"\01L_selector(method:withFloat:)"
// CHECK: call i32 bitcast (void ()* @objc_msgSend to i32
var i = b.method(1, with: 2.5 as Float)
// CHECK: load i8*, i8** @"\01L_selector(method:withDouble:)"
// CHECK: call i32 bitcast (void ()* @objc_msgSend to i32
i = i + b.method(1, with: 2.5 as Double)
}
// CHECK: define hidden void @_TF7objc_ir16extensionMethodsFT1bCSo1B_T_
func extensionMethods(b b: B) {
// CHECK: load i8*, i8** @"\01L_selector(method:separateExtMethod:)", align 8
// CHECK: [[T0:%.*]] = call i8* bitcast (void ()* @objc_msgSend to i8*
// CHECK-NEXT: [[T1:%.*]] = call i8* @objc_retainAutoreleasedReturnValue(i8* [[T0]])
// CHECK-NOT: [[T0]]
// CHECK: [[T1]]
b.method(1, separateExtMethod:1.5)
}
// CHECK: define hidden void @_TF7objc_ir19initCallToAllocInitFT1iVs5Int32_T_
func initCallToAllocInit(i i: CInt) {
// CHECK: call {{.*}} @_TFCSo1BCfT3intVs5Int32_GSQS__
B(int: i)
}
// CHECK: linkonce_odr hidden {{.*}} @_TFCSo1BCfT3intVs5Int32_GSQS__
// CHECK: call [[OPAQUE:%.*]]* @objc_allocWithZone
// Indexed subscripting
// CHECK: define hidden void @_TF7objc_ir19indexedSubscriptingFT1bCSo1B3idxSi1aCSo1A_T_
func indexedSubscripting(b b: B, idx: Int, a: A) {
// CHECK: load i8*, i8** @"\01L_selector(setObject:atIndexedSubscript:)", align 8
b[idx] = a
// CHECK: load i8*, i8** @"\01L_selector(objectAtIndexedSubscript:)"
var a2 = b[idx] as! A
}
// CHECK: define hidden void @_TF7objc_ir17keyedSubscriptingFT1bCSo1B3idxCSo1A1aS1__T_
func keyedSubscripting(b b: B, idx: A, a: A) {
// CHECK: load i8*, i8** @"\01L_selector(setObject:forKeyedSubscript:)"
b[a] = a
// CHECK: load i8*, i8** @"\01L_selector(objectForKeyedSubscript:)"
var a2 = b[a] as! A
}
// CHECK: define hidden void @_TF7objc_ir14propertyAccessFT1bCSo1B_T_
func propertyAccess(b b: B) {
// CHECK: load i8*, i8** @"\01L_selector(counter)"
// CHECK: load i8*, i8** @"\01L_selector(setCounter:)"
b.counter = b.counter + 1
// CHECK: call %swift.type* @_TMaCSo1B()
// CHECK: bitcast %swift.type* {{%.+}} to %objc_class*
// CHECK: load i8*, i8** @"\01L_selector(sharedCounter)"
// CHECK: load i8*, i8** @"\01L_selector(setSharedCounter:)"
B.sharedCounter = B.sharedCounter + 1
}
// CHECK: define hidden [[B]]* @_TF7objc_ir8downcastFT1aCSo1A_CSo1B(
func downcast(a a: A) -> B {
// CHECK: [[CLASS:%.*]] = load %objc_class*, %objc_class** @"OBJC_CLASS_REF_$_B"
// CHECK: [[T0:%.*]] = call %objc_class* @swift_rt_swift_getInitializedObjCClass(%objc_class* [[CLASS]])
// CHECK: [[T1:%.*]] = bitcast %objc_class* [[T0]] to i8*
// CHECK: call i8* @swift_dynamicCastObjCClassUnconditional(i8* [[A:%.*]], i8* [[T1]]) [[NOUNWIND:#[0-9]+]]
return a as! B
}
// CHECK: define hidden void @_TF7objc_ir19almostSubscriptableFT3as1CSo19AlmostSubscriptable1aCSo1A_T_
func almostSubscriptable(as1 as1: AlmostSubscriptable, a: A) {
as1.objectForKeyedSubscript(a)
}
// CHECK: define hidden void @_TF7objc_ir13protocolTypesFT1aCSo7NSMince1bPSo9NSRuncing__T_(%CSo7NSMince*, %objc_object*) {{.*}} {
func protocolTypes(a a: NSMince, b: NSRuncing) {
// - (void)eatWith:(id <NSRuncing>)runcer;
a.eat(with: b)
// CHECK: [[SEL:%.*]] = load i8*, i8** @"\01L_selector(eatWith:)", align 8
// CHECK: call void bitcast (void ()* @objc_msgSend to void ([[OPAQUE:%.*]]*, i8*, i8*)*)([[OPAQUE:%.*]]* {{%.*}}, i8* [[SEL]], i8* {{%.*}})
}
// CHECK-LABEL: define hidden void @_TF7objc_ir6getsetFT1pPSo8FooProto__T_(%objc_object*) {{.*}} {
func getset(p p: FooProto) {
// CHECK: load i8*, i8** @"\01L_selector(bar)"
// CHECK: load i8*, i8** @"\01L_selector(setBar:)"
let prop = p.bar
p.bar = prop
}
// CHECK-LABEL: define hidden %swift.type* @_TF7objc_ir16protocolMetatypeFT1pPSo8FooProto__PMPS0__(%objc_object*) {{.*}} {
func protocolMetatype(p: FooProto) -> FooProto.Type {
// CHECK: = call %swift.type* @swift_getObjectType(%objc_object* %0)
// CHECK-NOT: {{retain|release}}
// CHECK: [[RAW_RESULT:%.+]] = call i8* @processFooType(i8* {{%.+}})
// CHECK: [[CASTED_RESULT:%.+]] = bitcast i8* [[RAW_RESULT]] to %objc_class*
// CHECK: [[SWIFT_RESULT:%.+]] = call %swift.type* @swift_getObjCClassMetadata(%objc_class* [[CASTED_RESULT]])
// CHECK: call void @swift_unknownRelease(%objc_object* %0)
// CHECK: ret %swift.type* [[SWIFT_RESULT]]
let type = processFooType(type(of: p))
return type
} // CHECK: }
class Impl: FooProto, AnotherProto {
@objc var bar: Int32 = 0
}
// CHECK-LABEL: define hidden %swift.type* @_TF7objc_ir27protocolCompositionMetatypeFT1pCS_4Impl_PMPSo12AnotherProtoSo8FooProto_(%C7objc_ir4Impl*) {{.*}} {
func protocolCompositionMetatype(p: Impl) -> (FooProto & AnotherProto).Type {
// CHECK: = getelementptr inbounds %C7objc_ir4Impl, %C7objc_ir4Impl* %0, i32 0, i32 0, i32 0
// CHECK-NOT: {{retain|release}}
// CHECK: [[RAW_RESULT:%.+]] = call i8* @processComboType(i8* {{%.+}})
// CHECK: [[CASTED_RESULT:%.+]] = bitcast i8* [[RAW_RESULT]] to %objc_class*
// CHECK: [[SWIFT_RESULT:%.+]] = call %swift.type* @swift_getObjCClassMetadata(%objc_class* [[CASTED_RESULT]])
// CHECK: call void bitcast (void (%swift.refcounted*)* @swift_rt_swift_release to void (%C7objc_ir4Impl*)*)(%C7objc_ir4Impl* %0)
// CHECK: ret %swift.type* [[SWIFT_RESULT]]
let type = processComboType(type(of: p))
return type
} // CHECK: }
// CHECK-LABEL: define hidden %swift.type* @_TF7objc_ir28protocolCompositionMetatype2FT1pCS_4Impl_PMPSo12AnotherProtoSo8FooProto_(%C7objc_ir4Impl*) {{.*}} {
func protocolCompositionMetatype2(p: Impl) -> (FooProto & AnotherProto).Type {
// CHECK: = getelementptr inbounds %C7objc_ir4Impl, %C7objc_ir4Impl* %0, i32 0, i32 0, i32 0
// CHECK-NOT: {{retain|release}}
// CHECK: [[RAW_RESULT:%.+]] = call i8* @processComboType2(i8* {{%.+}})
// CHECK: [[CASTED_RESULT:%.+]] = bitcast i8* [[RAW_RESULT]] to %objc_class*
// CHECK: [[SWIFT_RESULT:%.+]] = call %swift.type* @swift_getObjCClassMetadata(%objc_class* [[CASTED_RESULT]])
// CHECK: call void bitcast (void (%swift.refcounted*)* @swift_rt_swift_release to void (%C7objc_ir4Impl*)*)(%C7objc_ir4Impl* %0)
// CHECK: ret %swift.type* [[SWIFT_RESULT]]
let type = processComboType2(type(of: p))
return type
} // CHECK: }
// CHECK-LABEL: define hidden void @_TF7objc_ir17pointerPropertiesFCSo14PointerWrapperT_(%CSo14PointerWrapper*) {{.*}} {
func pointerProperties(_ obj: PointerWrapper) {
// CHECK: load i8*, i8** @"\01L_selector(setVoidPtr:)"
// CHECK: load i8*, i8** @"\01L_selector(setIntPtr:)"
// CHECK: load i8*, i8** @"\01L_selector(setIdPtr:)"
obj.voidPtr = nil as UnsafeMutableRawPointer?
obj.intPtr = nil as UnsafeMutablePointer?
obj.idPtr = nil as AutoreleasingUnsafeMutablePointer?
}
// CHECK-LABEL: define hidden void @_TF7objc_ir16strangeSelectorsFCSo13SwiftNameTestT_(%CSo13SwiftNameTest*) {{.*}} {
func strangeSelectors(_ obj: SwiftNameTest) {
// CHECK: load i8*, i8** @"\01L_selector(:b:)"
obj.empty(a: 0, b: 0)
}
// CHECK-LABEL: define hidden void @_TF7objc_ir20customFactoryMethodsFT_T_() {{.*}} {
func customFactoryMethods() {
// CHECK: call %CSo13SwiftNameTest* @_TTOFCSo13SwiftNameTestCfT10dummyParamT__S_
// CHECK: call %CSo13SwiftNameTest* @_TTOFCSo13SwiftNameTestCfT2ccGSqP___S_
// CHECK: call %CSo13SwiftNameTest* @_TTOFCSo13SwiftNameTestCfT5emptyVs5Int32_S_
_ = SwiftNameTest(dummyParam: ())
_ = SwiftNameTest(cc: nil)
_ = SwiftNameTest(empty: 0)
// CHECK: load i8*, i8** @"\01L_selector(testZ)"
// CHECK: load i8*, i8** @"\01L_selector(testY:)"
// CHECK: load i8*, i8** @"\01L_selector(testX:xx:)"
// CHECK: load i8*, i8** @"\01L_selector(::)"
_ = SwiftNameTest.zz()
_ = SwiftNameTest.yy(aa: nil)
_ = SwiftNameTest.xx(nil, bb: nil)
_ = SwiftNameTest.empty(1, 2)
do {
// CHECK: call %CSo18SwiftNameTestError* @_TTOFCSo18SwiftNameTestErrorCfzT5errorT__S_
// CHECK: call %CSo18SwiftNameTestError* @_TTOFCSo18SwiftNameTestErrorCfzT2aaGSqP__5errorT__S_
// CHECK: call %CSo18SwiftNameTestError* @_TTOFCSo18SwiftNameTestErrorCfzT2aaGSqP__5errorT_5blockFT_T__S_
// CHECK: call %CSo18SwiftNameTestError* @_TTOFCSo18SwiftNameTestErrorCfzT5errorT_5blockFT_T__S_
// CHECK: call %CSo18SwiftNameTestError* @_TTOFCSo18SwiftNameTestErrorCfzT2aaGSqP___S_
// CHECK: call %CSo18SwiftNameTestError* @_TTOFCSo18SwiftNameTestErrorCfzT2aaGSqP__5blockFT_T__S_
// CHECK: call %CSo18SwiftNameTestError* @_TTOFCSo18SwiftNameTestErrorCfzT5blockFT_T__S_
_ = try SwiftNameTestError(error: ())
_ = try SwiftNameTestError(aa: nil, error: ())
_ = try SwiftNameTestError(aa: nil, error: (), block: {})
_ = try SwiftNameTestError(error: (), block: {})
_ = try SwiftNameTestError(aa: nil)
_ = try SwiftNameTestError(aa: nil, block: {})
_ = try SwiftNameTestError(block: {})
// CHECK: load i8*, i8** @"\01L_selector(testW:error:)"
// CHECK: load i8*, i8** @"\01L_selector(testW2:error:)"
// CHECK: load i8*, i8** @"\01L_selector(testV:)"
// CHECK: load i8*, i8** @"\01L_selector(testV2:)"
_ = try SwiftNameTestError.ww(nil)
_ = try SwiftNameTestError.w2(nil, error: ())
_ = try SwiftNameTestError.vv()
_ = try SwiftNameTestError.v2(error: ())
} catch _ {
}
}
// CHECK-LABEL: define linkonce_odr hidden %CSo13SwiftNameTest* @_TTOFCSo13SwiftNameTestCfT10dummyParamT__S_
// CHECK: load i8*, i8** @"\01L_selector(b)"
// CHECK: }
// CHECK-LABEL: define linkonce_odr hidden %CSo13SwiftNameTest* @_TTOFCSo13SwiftNameTestCfT2ccGSqP___S_
// CHECK: load i8*, i8** @"\01L_selector(c:)"
// CHECK: }
// CHECK-LABEL: define linkonce_odr hidden %CSo18SwiftNameTestError* @_TTOFCSo18SwiftNameTestErrorCfzT5errorT__S_
// CHECK: load i8*, i8** @"\01L_selector(err1:)"
// CHECK: }
// CHECK-LABEL: define linkonce_odr hidden %CSo18SwiftNameTestError* @_TTOFCSo18SwiftNameTestErrorCfzT2aaGSqP__5errorT__S_
// CHECK: load i8*, i8** @"\01L_selector(err2:error:)"
// CHECK: }
// CHECK-LABEL: define linkonce_odr hidden %CSo18SwiftNameTestError* @_TTOFCSo18SwiftNameTestErrorCfzT2aaGSqP__5errorT_5blockFT_T__S_
// CHECK: load i8*, i8** @"\01L_selector(err3:error:callback:)"
// CHECK: }
// CHECK-LABEL: define linkonce_odr hidden %CSo18SwiftNameTestError* @_TTOFCSo18SwiftNameTestErrorCfzT5errorT_5blockFT_T__S_
// CHECK: load i8*, i8** @"\01L_selector(err4:callback:)"
// CHECK: }
// CHECK-LABEL: define linkonce_odr hidden %CSo18SwiftNameTestError* @_TTOFCSo18SwiftNameTestErrorCfzT2aaGSqP___S_
// CHECK: load i8*, i8** @"\01L_selector(err5:error:)"
// CHECK: }
// CHECK-LABEL: define linkonce_odr hidden %CSo18SwiftNameTestError* @_TTOFCSo18SwiftNameTestErrorCfzT2aaGSqP__5blockFT_T__S_
// CHECK: load i8*, i8** @"\01L_selector(err6:error:callback:)"
// CHECK: }
// CHECK-LABEL: define linkonce_odr hidden %CSo18SwiftNameTestError* @_TTOFCSo18SwiftNameTestErrorCfzT5blockFT_T__S_
// CHECK: load i8*, i8** @"\01L_selector(err7:callback:)"
// CHECK: }
// CHECK-LABEL: define hidden void @_TF7objc_ir29customFactoryMethodsInheritedFT_T_() {{.*}} {
func customFactoryMethodsInherited() {
// CHECK: call %CSo16SwiftNameTestSub* @_TTOFCSo16SwiftNameTestSubCfT10dummyParamT__S_
// CHECK: call %CSo16SwiftNameTestSub* @_TTOFCSo16SwiftNameTestSubCfT2ccGSqP___S_
_ = SwiftNameTestSub(dummyParam: ())
_ = SwiftNameTestSub(cc: nil)
// CHECK: load i8*, i8** @"\01L_selector(testZ)"
// CHECK: load i8*, i8** @"\01L_selector(testY:)"
// CHECK: load i8*, i8** @"\01L_selector(testX:xx:)"
_ = SwiftNameTestSub.zz()
_ = SwiftNameTestSub.yy(aa: nil)
_ = SwiftNameTestSub.xx(nil, bb: nil)
do {
// CHECK: call %CSo21SwiftNameTestErrorSub* @_TTOFCSo21SwiftNameTestErrorSubCfzT5errorT__S_
// CHECK: call %CSo21SwiftNameTestErrorSub* @_TTOFCSo21SwiftNameTestErrorSubCfzT2aaGSqP__5errorT__S_
// CHECK: call %CSo21SwiftNameTestErrorSub* @_TTOFCSo21SwiftNameTestErrorSubCfzT2aaGSqP__5errorT_5blockFT_T__S_
// CHECK: call %CSo21SwiftNameTestErrorSub* @_TTOFCSo21SwiftNameTestErrorSubCfzT5errorT_5blockFT_T__S_
// CHECK: call %CSo21SwiftNameTestErrorSub* @_TTOFCSo21SwiftNameTestErrorSubCfzT2aaGSqP___S_
// CHECK: call %CSo21SwiftNameTestErrorSub* @_TTOFCSo21SwiftNameTestErrorSubCfzT2aaGSqP__5blockFT_T__S_
// CHECK: call %CSo21SwiftNameTestErrorSub* @_TTOFCSo21SwiftNameTestErrorSubCfzT5blockFT_T__S_
_ = try SwiftNameTestErrorSub(error: ())
_ = try SwiftNameTestErrorSub(aa: nil, error: ())
_ = try SwiftNameTestErrorSub(aa: nil, error: (), block: {})
_ = try SwiftNameTestErrorSub(error: (), block: {})
_ = try SwiftNameTestErrorSub(aa: nil)
_ = try SwiftNameTestErrorSub(aa: nil, block: {})
_ = try SwiftNameTestErrorSub(block: {})
// CHECK: load i8*, i8** @"\01L_selector(testW:error:)"
// CHECK: load i8*, i8** @"\01L_selector(testW2:error:)"
// CHECK: load i8*, i8** @"\01L_selector(testV:)"
// CHECK: load i8*, i8** @"\01L_selector(testV2:)"
_ = try SwiftNameTestErrorSub.ww(nil)
_ = try SwiftNameTestErrorSub.w2(nil, error: ())
_ = try SwiftNameTestErrorSub.vv()
_ = try SwiftNameTestErrorSub.v2(error: ())
} catch _ {
}
}
// CHECK-LABEL: define linkonce_odr hidden %CSo16SwiftNameTestSub* @_TTOFCSo16SwiftNameTestSubCfT10dummyParamT__S_
// CHECK: load i8*, i8** @"\01L_selector(b)"
// CHECK: }
// CHECK-LABEL: define linkonce_odr hidden %CSo16SwiftNameTestSub* @_TTOFCSo16SwiftNameTestSubCfT2ccGSqP___S_
// CHECK: load i8*, i8** @"\01L_selector(c:)"
// CHECK: }
// CHECK-LABEL: define linkonce_odr hidden %CSo21SwiftNameTestErrorSub* @_TTOFCSo21SwiftNameTestErrorSubCfzT5errorT__S_
// CHECK: load i8*, i8** @"\01L_selector(err1:)"
// CHECK: }
// CHECK-LABEL: define linkonce_odr hidden %CSo21SwiftNameTestErrorSub* @_TTOFCSo21SwiftNameTestErrorSubCfzT2aaGSqP__5errorT__S_
// CHECK: load i8*, i8** @"\01L_selector(err2:error:)"
// CHECK: }
// CHECK-LABEL: define linkonce_odr hidden %CSo21SwiftNameTestErrorSub* @_TTOFCSo21SwiftNameTestErrorSubCfzT2aaGSqP__5errorT_5blockFT_T__S_
// CHECK: load i8*, i8** @"\01L_selector(err3:error:callback:)"
// CHECK: }
// CHECK-LABEL: define linkonce_odr hidden %CSo21SwiftNameTestErrorSub* @_TTOFCSo21SwiftNameTestErrorSubCfzT5errorT_5blockFT_T__S_
// CHECK: load i8*, i8** @"\01L_selector(err4:callback:)"
// CHECK: }
// CHECK-LABEL: define linkonce_odr hidden %CSo21SwiftNameTestErrorSub* @_TTOFCSo21SwiftNameTestErrorSubCfzT2aaGSqP___S_
// CHECK: load i8*, i8** @"\01L_selector(err5:error:)"
// CHECK: }
// CHECK-LABEL: define linkonce_odr hidden %CSo21SwiftNameTestErrorSub* @_TTOFCSo21SwiftNameTestErrorSubCfzT2aaGSqP__5blockFT_T__S_
// CHECK: load i8*, i8** @"\01L_selector(err6:error:callback:)"
// CHECK: }
// CHECK-LABEL: define linkonce_odr hidden %CSo21SwiftNameTestErrorSub* @_TTOFCSo21SwiftNameTestErrorSubCfzT5blockFT_T__S_
// CHECK: load i8*, i8** @"\01L_selector(err7:callback:)"
// CHECK: }
// CHECK: linkonce_odr hidden {{.*}} @_TTOFCSo1BcfT3intVs5Int32_GSQS__
// CHECK: load i8*, i8** @"\01L_selector(initWithInt:)"
// CHECK: call [[OPAQUE:%.*]]* bitcast (void ()* @objc_msgSend
// CHECK: attributes [[NOUNWIND]] = { nounwind }
|
apache-2.0
|
b3f6f5f94111693af5371a23c43f7214
| 46.053097 | 168 | 0.684346 | 3.286156 | false | true | false | false |
Fenrikur/ef-app_ios
|
Domain Model/EurofurenceModelTests/Events/Tag Adaption/InOrderToSupportKageTag_ApplicationShould.swift
|
1
|
1448
|
import EurofurenceModel
import XCTest
class InOrderToSupportKageTag_ApplicationShould: XCTestCase {
func testIndicateItIsKageEventWhenTagPresent() {
var syncResponse = ModelCharacteristics.randomWithoutDeletions
let randomEvent = syncResponse.events.changed.randomElement()
var event = randomEvent.element
event.tags = ["kage"]
syncResponse.events.changed = [event]
let context = EurofurenceSessionTestBuilder().build()
context.performSuccessfulSync(response: syncResponse)
let eventsObserver = CapturingEventsServiceObserver()
context.eventsService.add(eventsObserver)
let observedEvent = eventsObserver.allEvents.first
XCTAssertEqual(true, observedEvent?.isKageEvent)
}
func testNotIndicateItIsArtShowEventWhenTagNotPresent() {
var syncResponse = ModelCharacteristics.randomWithoutDeletions
let randomEvent = syncResponse.events.changed.randomElement()
var event = randomEvent.element
event.tags = []
syncResponse.events.changed = [event]
let context = EurofurenceSessionTestBuilder().build()
context.performSuccessfulSync(response: syncResponse)
let eventsObserver = CapturingEventsServiceObserver()
context.eventsService.add(eventsObserver)
let observedEvent = eventsObserver.allEvents.first
XCTAssertEqual(false, observedEvent?.isKageEvent)
}
}
|
mit
|
52713351475a3172ee44c90b56fbce3e
| 39.222222 | 70 | 0.732735 | 5.983471 | false | true | false | false |
OneupNetwork/SQRichTextEditor
|
Example/SQRichTextEditor/ToolItemCell.swift
|
1
|
2190
|
//
// ToolBarItemCell.swift
// SQRichTextEditor_Example
//
// Created by Jesse on 2019/12/13.
// Copyright © 2019 CocoaPods. All rights reserved.
//
import UIKit
import SQRichTextEditor
class ToolItemCell: UICollectionViewCell {
lazy var textLabel: UILabel = {
let _textLabel = UILabel()
_textLabel.translatesAutoresizingMaskIntoConstraints = false
return _textLabel
}()
override init(frame: CGRect) {
super.init(frame: frame)
contentView.addSubview(textLabel)
textLabel.centerXAnchor.constraint(equalTo: contentView.centerXAnchor).isActive = true
textLabel.centerYAnchor.constraint(equalTo: contentView.centerYAnchor).isActive = true
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func configCell(option: ToolOptionType, attribute: SQTextAttribute) {
//Format
var isActive = false
switch option {
case .bold:
isActive = attribute.format.hasBold
case .italic:
isActive = attribute.format.hasItalic
case .strikethrough:
isActive = attribute.format.hasStrikethrough
case .underline:
isActive = attribute.format.hasUnderline
default:
break
}
textLabel.text = option.description
textLabel.font = isActive ? ToolItemCellSettings.activeFont : ToolItemCellSettings.normalfont
textLabel.textColor = isActive ? ToolItemCellSettings.activeColor : ToolItemCellSettings.normalColor
//TextInfo
switch option {
case .setTextSize:
if let size = attribute.textInfo.size {
textLabel.text = "Font Size(\(size)px)"
}
case .setTextColor:
if let color = attribute.textInfo.color {
textLabel.textColor = color
}
case .setTextBackgroundColor:
if let color = attribute.textInfo.backgroundColor {
textLabel.textColor = color
}
default:
break
}
}
}
|
mit
|
97965b9a6bf3c27aa8b616a036138b90
| 29.402778 | 108 | 0.606213 | 5.211905 | false | false | false | false |
fancymax/12306ForMac
|
12306ForMac/Utilities/ReminderManager.swift
|
1
|
2054
|
//
// ReminderManager.swift
// 12306ForMac
//
// Created by fancymax on 2/24/2017.
// Copyright © 2017年 fancy. All rights reserved.
//
import Foundation
import EventKit
class ReminderManager: NSObject {
private let eventStore:EKEventStore
private var isAccessToEventStoreGranted:Bool
fileprivate static let sharedManager = ReminderManager()
class var sharedInstance: ReminderManager {
return sharedManager
}
private override init () {
isAccessToEventStoreGranted = false
eventStore = EKEventStore()
}
@discardableResult
func updateAuthorizationStatus()->Bool {
switch EKEventStore.authorizationStatus(for: .reminder) {
case .authorized:
self.isAccessToEventStoreGranted = true
return true
case .notDetermined:
self.eventStore.requestAccess(to: .reminder, completion: {[unowned self] granted,error in
DispatchQueue.main.async {
self.isAccessToEventStoreGranted = granted
}
})
return false
case .restricted, .denied:
isAccessToEventStoreGranted = false
return false
}
}
func createReminder(_ title:String, startDate:Date) {
if !isAccessToEventStoreGranted {
return
}
let reminder = EKReminder(eventStore: self.eventStore)
reminder.calendar = eventStore.defaultCalendarForNewReminders()
reminder.title = title
var date = Date(timeInterval: 5, since: Date())
var alarm = EKAlarm(absoluteDate: date)
reminder.addAlarm(alarm)
date = Date(timeInterval: 10, since: Date())
alarm = EKAlarm(absoluteDate: date)
reminder.addAlarm(alarm)
date = Date(timeInterval: 15, since: Date())
alarm = EKAlarm(absoluteDate: date)
reminder.addAlarm(alarm)
try! eventStore.save(reminder, commit: true)
}
}
|
mit
|
c99369c5042822a8ea3b326276cc364b
| 28.3 | 101 | 0.612872 | 5.140351 | false | false | false | false |
mchakravarty/goalsapp
|
Goals/Goals/Goals.swift
|
1
|
6372
|
//
// Goals.swift
// Goals
//
// Created by Manuel M T Chakravarty on 22/06/2016.
// Copyright © [2016..2017] Chakravarty & Keller. All rights reserved.
//
// Model representation
import Foundation
import UIKit
// MARK: Model data structures
/// The set of colours that might be used to render goals.
///
let goalColours: [UIColor] = [.blue, .cyan, .green, .yellow, .orange, .red, .purple]
enum GoalInterval: CustomStringConvertible {
case daily, weekly, monthly
var description: String {
switch self {
case .daily: return "Daily"
case .weekly: return "Weekly"
case .monthly: return "Monthly"
}
}
/// Printed frequency for the current time interval, assumming the argument is greater than zero.
///
func frequency(number: Int) -> String {
var result: String
switch number {
case 1: result = "once"
case 2: result = "twice"
default: result = "\(number) times"
}
switch self {
case .daily: result += " per day"
case .weekly: result += " per week"
case .monthly: result += " per month"
}
return result
}
}
/// Specification of a single goal
///
struct Goal {
let uuid: UUID // Unique identifier for a specific goal
var colour: UIColor
var title: String
var interval: GoalInterval
var frequency: Int // how often the goal ought to be achieved during the interval
init(colour: UIColor, title: String, interval: GoalInterval, frequency: Int) {
self.uuid = UUID()
self.colour = colour
self.title = title
self.interval = interval
self.frequency = frequency
}
init() { self = Goal(colour: .green, title: "New Goal", interval: .daily, frequency: 1) }
var frequencyPerInterval: String {
// FIXME: use NumberFormatter to print frequency in words
return "\(interval.frequency(number: frequency))"
}
/// Percentage towards achieving the goal in the current interval given a specific count of how often the task/activity
/// has been done in the current interval.
///
func percentage(count: Int) -> Float { return Float(count) / Float(frequency) }
}
extension Goal {
static func ===(lhs: Goal, rhs: Goal) -> Bool { return lhs.uuid == rhs.uuid }
}
/// A goal and the progress towards that goal in an interval. Only active goals make progress.
///
typealias GoalProgress = (goal: Goal, progress: Int?)
/// Specification of a collection of goals with progress — complete, immutable model state.
///
/// * The order of the goals in the array determines their order on the overview screen.
///
/// NB: If the number of entries in this array was bigger, it would be more efficient to use a dictionary indexed by
/// goals (or rather their UUID), but as it is, an array suffices and also matches the ordering of the goals in UI.
///
typealias Goals = [GoalProgress]
/// Adjust the progress component of goals with progress according to the activity array.
///
/// Precondition: the activities array has at least as many entries as the goals array
///
func mergeActivity(goals: Goals, activity: [Bool]) -> Goals {
return zip(goals, activity).map{ goal, isActive in
switch (goal.progress, isActive) {
case (nil, false),
(.some, true): return goal
case (nil, true): return (goal: goal.goal, progress: 0)
case (.some, false): return (goal: goal.goal, progress: nil)
}
}
}
// MARK: -
// MARK: Goals edits
/// This type encompases all transformations that may be applied to goals except advancing the progress counts in values
/// of type `Goals`.
///
enum GoalEdit {
case add(goal: Goal)
case delete(goal: Goal)
case update(goal: Goal)
case setActivity(activity: [Bool])
}
extension GoalEdit {
func transform(_ goals: Goals) -> Goals {
switch self {
case .add(let newGoal):
guard !goals.contains(where: { $0.goal === newGoal} ) else { return goals }
var newGoals = goals
newGoals.insert((goal: newGoal, progress: nil), at: 0)
return newGoals
case .delete(let goal):
return goals.filter{ !($0.goal === goal) }
case .update(let newGoal):
return goals.map{ (goal: Goal, count: Int?) in
return (goal === newGoal) ? (goal: newGoal, progress: count) : (goal: goal, progress: count) }
case .setActivity(let goalsActivity):
return mergeActivity(goals: goals, activity: goalsActivity)
}
}
}
/// Type of a stream of goal edits.
///
typealias GoalEdits = Changes<GoalEdit>
// MARK: -
// MARK: Progress edits
/// This type captures the transformations that advance goal progress.
///
enum ProgressEdit {
case bump(goal: Goal)
}
extension ProgressEdit {
func transform(_ goals: Goals) -> Goals {
switch self {
case .bump(let bumpedGoal):
return goals.map{ (goal: Goal, count: Int?) in
return (goal === bumpedGoal) ? (goal: goal, progress: count.flatMap{ $0 + 1 }) : (goal: goal, progress: count) }
}
}
}
/// Type of a stream of progress edits.
///
typealias ProgressEdits = Changes<ProgressEdit>
// MARK: -
// MARK: All model edits
/// Merged edits
///
enum Edit {
case goalEdit(edit: GoalEdit)
case progressEdit(edit: ProgressEdit)
}
extension Edit {
init(goalOrProgressEdit: Either<GoalEdit, ProgressEdit>) {
switch goalOrProgressEdit {
case .left(let goalEdit): self = .goalEdit(edit: goalEdit)
case .right(let progressEdit): self = .progressEdit(edit: progressEdit)
}
}
func transform(_ goals: Goals) -> Goals {
switch self {
case .goalEdit(let goalEdit): return goalEdit.transform(goals)
case .progressEdit(let progressEdit): return progressEdit.transform(goals)
}
}
}
typealias Edits = Changes<Edit>
// MARK: -
// MARK: Complete app model
struct GoalsModel {
// The two types of edit streams
//
let goalEdits = GoalEdits(),
progressEdits = ProgressEdits()
/// Combined edits
///
let edits: Edits
/// The current model value is determined by accumulating all edits.
///
let model: Changing<Goals>
init(initial: Goals) {
// Create the change propagation network
edits = goalEdits.merge(right: progressEdits).map{ Edit(goalOrProgressEdit: $0) }
model = edits.accumulate(startingFrom: initial){ edit, currentGoals in
return edit.transform(currentGoals)
}
}
}
|
bsd-2-clause
|
4f36b13d9a3a81b50355e5f2e1757142
| 25.427386 | 121 | 0.661014 | 3.83906 | false | false | false | false |
SwiftOnEdge/Edge
|
Sources/HTTP/Routing/ResponseMiddleware.swift
|
1
|
1531
|
//
// ResponseMiddleware.swift
// Edge
//
// Created by Tyler Fleming Cloutier on 11/22/17.
//
import Foundation
import StreamKit
import Regex
import PathToRegex
struct ResponseMiddleware: HandlerNode {
weak var parent: Router?
let transform: ResponseMapper
func map(responses: Signal<Response>) -> Signal<Response>{
let results: Signal<Response>
switch transform {
case .sync(let syncTransform):
results = responses.map { response -> Response in
syncTransform(response)
}
case .async(let asyncTransform):
results = responses.flatMap { response -> Signal<Response> in
return asyncTransform(response).asSignal()
}
}
return results
}
func handle(
requests: Signal<Request>,
errors: Signal<(Request, Error)>,
responses: Signal<Response>
) -> (
handled: Signal<Response>,
errored: Signal<(Request, Error)>,
unhandled: Signal<Request>
) {
let (handled, handledInput) = Signal<Response>.pipe()
map(responses: responses).add(observer: handledInput)
return (handled, errors, requests)
}
init(parent: Router, _ transform: ResponseMapper) {
self.transform = transform
self.parent = parent
}
}
extension ResponseMiddleware: CustomStringConvertible {
var description: String {
return "RESPONSE MIDDLEWARE '\(routePath)'"
}
}
|
mit
|
454336a7d0fcb3f1e87b520435411468
| 24.098361 | 77 | 0.605487 | 4.681957 | false | false | false | false |
hongxinhope/TBRepeatPicker
|
Example/SwitchLanguageViewController.swift
|
1
|
2199
|
//
// SwitchLanguageViewController.swift
// TBRepeatPicker
//
// Created by 洪鑫 on 15/10/9.
// Copyright © 2015年 Teambition. All rights reserved.
//
import UIKit
private let SwitchLanguageViewControllerCellID = "SwitchLanguageViewControllerCell"
protocol SwitchLanguageViewControllerDelegate {
func donePickingLanguage(language: TBRPLanguage)
}
class SwitchLanguageViewController: UITableViewController {
var language: TBRPLanguage = .English
var delegate: SwitchLanguageViewControllerDelegate?
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.leftBarButtonItem = UIBarButtonItem(title: "Cancel", style: .Plain, target: self, action: "cancelPressed")
}
func cancelPressed() {
dismissViewControllerAnimated(true, completion: nil)
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 5
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCellWithIdentifier(SwitchLanguageViewControllerCellID)
if cell == nil {
cell = UITableViewCell.init(style: .Default, reuseIdentifier: SwitchLanguageViewControllerCellID)
}
cell?.textLabel?.text = languageStrings[indexPath.row]
if language == languages[indexPath.row] {
cell?.accessoryType = .Checkmark
} else {
cell?.accessoryType = .None
}
return cell!
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: true)
language = languages[indexPath.row]
tableView.reloadData()
if let _ = delegate {
dismissViewControllerAnimated(true, completion: { () -> Void in
self.delegate?.donePickingLanguage(self.language)
})
}
}
}
|
mit
|
0c5554fb89fa6ff3d5bfc76d46c3e451
| 30.314286 | 129 | 0.675639 | 5.333333 | false | false | false | false |
RocketChat/Rocket.Chat.iOS
|
Rocket.Chat/API/Requests/Message/UploadMessageRequest.swift
|
1
|
2760
|
//
// UploadRequest.swift
// Rocket.Chat
//
// Created by Matheus Cardoso on 12/7/17.
// Copyright © 2017 Rocket.Chat. All rights reserved.
//
import SwiftyJSON
final class UploadMessageRequest: APIRequest {
typealias APIResourceType = UploadMessageResource
let requiredVersion = Version(0, 60, 0)
let method: HTTPMethod = .post
var path: String {
return "/api/v1/rooms.upload/\(roomId)"
}
let contentType: String
let roomId: String
let data: Data
let filename: String
let mimetype: String
let msg: String
let description: String
let boundary = "Boundary-\(String.random())"
init(roomId: String, data: Data, filename: String, mimetype: String, msg: String = "", description: String = "") {
self.roomId = roomId
self.data = data
self.filename = filename
self.mimetype = mimetype
self.msg = msg
self.description = description
self.contentType = "multipart/form-data; boundary=\(boundary)"
}
func body() -> Data? {
let tempFileUrl = URL(fileURLWithPath: "\(NSTemporaryDirectory())upload_\(String.random(10)).temp")
FileManager.default.createFile(atPath: tempFileUrl.path, contents: nil)
guard let fileHandle = FileHandle(forWritingAtPath: tempFileUrl.path) else {
return nil
}
// write prefix
var prefixData = Data()
let boundaryPrefix = "--\(boundary)\r\n"
prefixData.appendString(boundaryPrefix)
prefixData.appendString("Content-Disposition: form-data; name=\"msg\"\r\n\r\n")
prefixData.appendString(msg)
prefixData.appendString("\r\n".appending(boundaryPrefix))
prefixData.appendString("Content-Disposition: form-data; name=\"description\"\r\n\r\n")
prefixData.appendString(description)
prefixData.appendString("\r\n".appending(boundaryPrefix))
prefixData.appendString("Content-Disposition: form-data; name=\"file\"; filename=\"\(filename)\"\r\n")
prefixData.appendString("Content-Type: \(mimetype)\r\n\r\n")
//try? prefixData.append(fileURL: tempFileUrl)
fileHandle.write(prefixData)
// write file
fileHandle.seekToEndOfFile()
fileHandle.write(data)
// write suffix
var suffixData = Data()
suffixData.appendString("\r\n--".appending(boundary.appending("--")))
fileHandle.seekToEndOfFile()
fileHandle.write(suffixData)
fileHandle.closeFile()
// return mapped data
return try? Data(contentsOf: tempFileUrl, options: .mappedIfSafe)
}
}
final class UploadMessageResource: APIResource {
var error: String? {
return raw?["error"].string
}
}
|
mit
|
32e6a5d7c52f36d0c3babbe5931a5524
| 27.443299 | 118 | 0.645161 | 4.50817 | false | false | false | false |
yanagiba/swift-ast
|
Sources/AST/Declaration/TypealiasDeclaration.swift
|
2
|
1674
|
/*
Copyright 2017 Ryuichi Intellectual Property and the Yanagiba project contributors
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.
*/
public class TypealiasDeclaration : ASTNode, Declaration {
public let attributes: Attributes
public let accessLevelModifier: AccessLevelModifier?
public let name: Identifier
public let generic: GenericParameterClause?
public let assignment: Type
public init(
attributes: Attributes = [],
accessLevelModifier: AccessLevelModifier? = nil,
name: Identifier,
generic: GenericParameterClause? = nil,
assignment: Type
) {
self.attributes = attributes
self.accessLevelModifier = accessLevelModifier
self.name = name
self.generic = generic
self.assignment = assignment
}
// MARK: - ASTTextRepresentable
override public var textDescription: String {
let attrsText = attributes.isEmpty ? "" : "\(attributes.textDescription) "
let modifierText = accessLevelModifier.map({ "\($0.textDescription) " }) ?? ""
let genericText = generic?.textDescription ?? ""
return "\(attrsText)\(modifierText)typealias \(name)\(genericText) = \(assignment.textDescription)"
}
}
|
apache-2.0
|
69b4a80f3ffac6c34fc168da2763528a
| 35.391304 | 103 | 0.734767 | 5.103659 | false | false | false | false |
mjgaylord/SwiftDDP
|
SwiftDDP/DDPClient.swift
|
1
|
22162
|
//
//
// A DDP Client written in Swift
//
// Copyright (c) 2016 Peter Siegesmund <[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.
//
// This software uses CryptoSwift: https://github.com/krzyzanowskim/CryptoSwift/
//
import Foundation
import SwiftWebSocket
import XCGLogger
let log = XCGLogger(identifier: "DDP")
public typealias DDPMethodCallback = (_ result:Any?, _ error:DDPError?) -> ()
public typealias DDPConnectedCallback = (_ session:String) -> ()
public typealias DDPCallback = () -> ()
/**
DDPDelegate provides an interface to react to user events
*/
public protocol SwiftDDPDelegate {
func ddpUserDidLogin(_ user:String)
func ddpUserDidLogout(_ user:String)
}
/**
DDPClient is the base class for communicating with a server using the DDP protocol
*/
open class DDPClient: NSObject {
// included for storing login id and token
internal let userData = UserDefaults.standard
let background: OperationQueue = {
let queue = OperationQueue()
queue.name = "DDP Background Data Queue"
queue.qualityOfService = .background
return queue
}()
// Callbacks execute in the order they're received
internal let callbackQueue: OperationQueue = {
let queue = OperationQueue()
queue.name = "DDP Callback Queue"
queue.maxConcurrentOperationCount = 1
queue.qualityOfService = .userInitiated
return queue
}()
// Document messages are processed in the order that they are received,
// separately from callbacks
internal let documentQueue: OperationQueue = {
let queue = OperationQueue()
queue.name = "DDP Background Queue"
queue.maxConcurrentOperationCount = 1
queue.qualityOfService = .background
return queue
}()
// Hearbeats get a special queue so that they're not blocked by
// other operations, causing the connection to close
internal let heartbeat: OperationQueue = {
let queue = OperationQueue()
queue.name = "DDP Heartbeat Queue"
queue.qualityOfService = .utility
return queue
}()
let userBackground: OperationQueue = {
let queue = OperationQueue()
queue.name = "DDP High Priority Background Queue"
queue.qualityOfService = .userInitiated
return queue
}()
let userMainQueue: OperationQueue = {
let queue = OperationQueue.main
queue.name = "DDP High Priorty Main Queue"
queue.qualityOfService = .userInitiated
return queue
}()
fileprivate var socket:WebSocket!{
didSet{ socket.allowSelfSignedSSL = self.allowSelfSignedSSL }
}
fileprivate var server:(ping:Date?, pong:Date?) = (nil, nil)
internal var resultCallbacks:[String:Completion] = [:]
internal var subCallbacks:[String:Completion] = [:]
internal var unsubCallbacks:[String:Completion] = [:]
open var url:String!
fileprivate var subscriptions = [String:(id:String, name:String, ready:Bool)]()
internal var events = DDPEvents()
internal var connection:(ddp:Bool, session:String?) = (false, nil)
open var delegate:SwiftDDPDelegate?
// MARK: Settings
/**
Boolean value that determines whether the
*/
open var allowSelfSignedSSL:Bool = false {
didSet{
guard let currentSocket = socket else { return }
currentSocket.allowSelfSignedSSL = allowSelfSignedSSL
}
}
/**
Sets the log level. The default value is .None.
Possible values: .Verbose, .Debug, .Info, .Warning, .Error, .Severe, .None
*/
open var logLevel = XCGLogger.Level.none {
didSet {
log.setup(level: logLevel, showLogIdentifier: true, showFunctionName: true, showThreadName: true, showLevel: true, showFileNames: false, showLineNumbers: true, showDate: false, writeToFile: nil, fileLevel: .none)
}
}
internal override init() {
super.init()
}
/**
Creates a random String id
*/
open func getId() -> String {
let numbers = Set<Character>(["0","1","2","3","4","5","6","7","8","9"])
let uuid = UUID().uuidString.replacingOccurrences(of: "-", with: "")
var id = ""
for character in uuid.characters {
if (!numbers.contains(character) && (round(Float(arc4random()) / Float(UINT32_MAX)) == 1)) {
id += String(character).lowercased()
} else {
id += String(character)
}
}
return id
}
/**
Makes a DDP connection to the server
- parameter url: The String url to connect to, ex. "wss://todos.meteor.com/websocket"
- parameter callback: A closure that takes a String argument with the value of the websocket session token
*/
open func connect(_ url:String, callback:DDPConnectedCallback?) {
self.url = url
// capture the thread context in which the function is called
let executionQueue = OperationQueue.current
socket = WebSocket(url)
//Create backoff
let backOff:DDPExponentialBackoff = DDPExponentialBackoff()
socket.event.close = {code, reason, clean in
//Use backoff to slow reconnection retries
backOff.createBackoff({
log.info("Web socket connection closed with code \(code). Clean: \(clean). \(reason)")
let event = self.socket.event
self.socket = WebSocket(url)
self.socket.event = event
self.ping()
})
}
socket.event.error = events.onWebsocketError
socket.event.open = {
self.heartbeat.addOperation() {
// Add a subscription to loginServices to each connection event
let callbackWithServiceConfiguration = { (session:String) in
// let loginServicesSubscriptionCollection = "meteor_accounts_loginServiceConfiguration"
let loginServiceConfiguration = "meteor.loginServiceConfiguration"
self.sub(loginServiceConfiguration, params: nil) // /tools/meteor-services/auth.js line 922
// Resubscribe to existing subs on connection to ensure continuity
self.subscriptions.forEach({ (subscription: (String, (id: String, name: String, ready: Bool))) -> () in
if subscription.1.name != loginServiceConfiguration {
self.sub(subscription.1.id, name: subscription.1.name, params: nil, callback: nil)
}
})
callback?(session)
}
var completion = Completion(callback: callbackWithServiceConfiguration)
//Reset the backoff to original values
backOff.reset()
completion.executionQueue = executionQueue
self.events.onConnected = completion
self.sendMessage(["msg":"connect", "version":"1", "support":["1"]])
}
}
socket.event.message = { message in
self.background.addOperation() {
if let text = message as? String {
do { try self.ddpMessageHandler(DDPMessage(message: text)) }
catch { log.debug("Message handling error. Raw message: \(text)")}
}
}
}
}
fileprivate func ping() {
heartbeat.addOperation() {
self.sendMessage(["msg":"ping", "id":self.getId()])
}
}
// Respond to a server ping
fileprivate func pong(_ ping: DDPMessage) {
heartbeat.addOperation() {
self.server.ping = Date()
var response = ["msg":"pong"]
if let id = ping.id { response["id"] = id }
self.sendMessage(response as NSDictionary)
}
}
// Parse DDP messages and dispatch to the appropriate function
internal func ddpMessageHandler(_ message: DDPMessage) throws {
log.debug("Received message: \(message.json)")
switch message.type {
case .Connected:
self.connection = (true, message.session!)
self.events.onConnected.execute(message.session!)
case .Result: callbackQueue.addOperation() {
if let id = message.id, // Message has id
let completion = self.resultCallbacks[id], // There is a callback registered for the message
let result = message.result {
completion.execute(result, error: message.error)
self.resultCallbacks[id] = nil
} else if let id = message.id,
let completion = self.resultCallbacks[id] {
completion.execute(nil, error:message.error)
self.resultCallbacks[id] = nil
}
}
// Principal callbacks for managing data
// Document was added
case .Added: documentQueue.addOperation() {
if let collection = message.collection,
let id = message.id {
self.documentWasAdded(collection, id: id, fields: message.fields)
}
}
// Document was changed
case .Changed: documentQueue.addOperation() {
if let collection = message.collection,
let id = message.id {
self.documentWasChanged(collection, id: id, fields: message.fields, cleared: message.cleared)
}
}
// Document was removed
case .Removed: documentQueue.addOperation() {
if let collection = message.collection,
let id = message.id {
self.documentWasRemoved(collection, id: id)
}
}
// Notifies you when the result of a method changes
case .Updated: documentQueue.addOperation() {
if let methods = message.methods {
self.methodWasUpdated(methods)
}
}
// Callbacks for managing subscriptions
case .Ready: documentQueue.addOperation() {
if let subs = message.subs {
self.ready(subs)
}
}
// Callback that fires when subscription has been completely removed
//
case .Nosub: documentQueue.addOperation() {
if let id = message.id {
self.nosub(id, error: message.error)
}
}
case .Ping: heartbeat.addOperation() { self.pong(message) }
case .Pong: heartbeat.addOperation() { self.server.pong = Date() }
case .Error: background.addOperation() {
self.didReceiveErrorMessage(DDPError(json: message.json))
}
default: log.error("Unhandled message: \(message.json)")
}
}
fileprivate func sendMessage(_ message:NSDictionary) {
if let m = message.stringValue() {
self.socket.send(m)
}
}
/**
Executes a method on the server. If a callback is passed, the callback is asynchronously
executed when the method has completed. The callback takes two arguments: result and error. It
the method call is successful, result contains the return value of the method, if any. If the method fails,
error contains information about the error.
- parameter name: The name of the method
- parameter params: An object containing method arguments, if any
- parameter callback: The closure to be executed when the method has been executed
*/
@discardableResult open func method(_ name: String, params: Any?, callback: DDPMethodCallback?) -> String {
let id = getId()
let message = ["msg":"method", "method":name, "id":id] as NSMutableDictionary
if let p = params { message["params"] = p }
if let completionCallback = callback {
let completion = Completion(callback: completionCallback)
self.resultCallbacks[id] = completion
}
userBackground.addOperation() {
self.sendMessage(message)
}
return id
}
//
// Subscribe
//
@discardableResult internal func sub(_ id: String, name: String, params: [Any]?, callback: DDPCallback?) -> String {
if let completionCallback = callback {
let completion = Completion(callback: completionCallback)
self.subCallbacks[id] = completion
}
self.subscriptions[id] = (id, name, false)
let message = ["msg":"sub", "name":name, "id":id] as NSMutableDictionary
if let p = params { message["params"] = p }
userBackground.addOperation() {
self.sendMessage(message)
}
return id
}
/**
Sends a subscription request to the server.
- parameter name: The name of the subscription
- parameter params: An object containing method arguments, if any
*/
@discardableResult open func sub(_ name: String, params: [Any]?) -> String {
let id = getId()
return sub(id, name: name, params: params, callback:nil)
}
/**
Sends a subscription request to the server. If a callback is passed, the callback asynchronously
runs when the client receives a 'ready' message indicating that the initial subset of documents contained
in the subscription has been sent by the server.
- parameter name: The name of the subscription
- parameter params: An object containing method arguments, if any
- parameter callback: The closure to be executed when the server sends a 'ready' message
*/
open func sub(_ name:String, params: [Any]?, callback: DDPCallback?) -> String {
let id = getId()
print("Subscribing to ID \(id)")
return sub(id, name: name, params: params, callback: callback)
}
// Iterates over the Dictionary of subscriptions to find a subscription by name
internal func findSubscription(_ name:String) -> [String] {
var subs:[String] = []
for sub in subscriptions.values {
if sub.name == name {
subs.append(sub.id)
}
}
return subs
}
// Iterates over the Dictionary of subscriptions to find a subscription by name
internal func subscriptionReady(_ name:String) -> Bool {
for sub in subscriptions.values {
if sub.name == name {
return sub.ready
}
}
return false
}
//
// Unsubscribe
//
/**
Sends an unsubscribe request to the server.
- parameter name: The name of the subscription
- parameter callback: The closure to be executed when the server sends a 'ready' message
*/
open func unsub(withName name: String) -> [String] {
return findSubscription(name).map({id in
background.addOperation() { self.sendMessage(["msg":"unsub", "id": id]) }
unsub(withId: id, callback: nil)
return id
})
}
/**
Sends an unsubscribe request to the server. If a callback is passed, the callback asynchronously
runs when the client receives a 'ready' message indicating that the subset of documents contained
in the subscription have been removed.
- parameter name: The name of the subscription
- parameter callback: The closure to be executed when the server sends a 'ready' message
*/
open func unsub(withId id: String, callback: DDPCallback?) {
if let completionCallback = callback {
let completion = Completion(callback: completionCallback)
unsubCallbacks[id] = completion
}
background.addOperation() { self.sendMessage(["msg":"unsub", "id":id]) }
}
//
// Responding to server subscription messages
//
fileprivate func ready(_ subs: [String]) {
for id in subs {
if let completion = subCallbacks[id] {
completion.execute() // Run the callback
subCallbacks[id] = nil // Delete the callback after running
} else { // If there is no callback, execute the method
if var sub = subscriptions[id] {
sub.ready = true
subscriptions[id] = sub
subscriptionIsReady(sub.id, subscriptionName: sub.name)
}
}
}
}
fileprivate func nosub(_ id: String, error: DDPError?) {
if let e = error, (e.isValid == true) {
log.error("\(e)")
} else {
if let completion = unsubCallbacks[id],
let _ = subscriptions[id] {
completion.execute()
unsubCallbacks[id] = nil
subscriptions[id] = nil
} else {
if let subscription = subscriptions[id] {
subscriptions[id] = nil
subscriptionWasRemoved(subscription.id, subscriptionName: subscription.name)
}
}
}
}
//
// public callbacks: should be overridden
//
/**
Executes when a subscription is ready.
- parameter subscriptionId: A String representation of the hash of the subscription name
- parameter subscriptionName: The name of the subscription
*/
open func subscriptionIsReady(_ subscriptionId: String, subscriptionName:String) {}
/**
Executes when a subscription is removed.
- parameter subscriptionId: A String representation of the hash of the subscription name
- parameter subscriptionName: The name of the subscription
*/
open func subscriptionWasRemoved(_ subscriptionId:String, subscriptionName:String) {}
/**
Executes when the server has sent a new document.
- parameter collection: The name of the collection that the document belongs to
- parameter id: The document's unique id
- parameter fields: The documents properties
*/
open func documentWasAdded(_ collection:String, id:String, fields:NSDictionary?) {
if let added = events.onAdded { added(collection, id, fields) }
}
/**
Executes when the server sends a message to remove a document.
- parameter collection: The name of the collection that the document belongs to
- parameter id: The document's unique id
*/
open func documentWasRemoved(_ collection:String, id:String) {
if let removed = events.onRemoved { removed(collection, id) }
}
/**
Executes when the server sends a message to update a document.
- parameter collection: The name of the collection that the document belongs to
- parameter id: The document's unique id
- parameter fields: Optional object with EJSON values containing the fields to update
- parameter cleared: Optional array of strings (field names to delete)
*/
open func documentWasChanged(_ collection:String, id:String, fields:NSDictionary?, cleared:[String]?) {
if let changed = events.onChanged { changed(collection, id, fields, cleared as NSArray?) }
}
/**
Executes when the server sends a message indicating that the result of a method has changed.
- parameter methods: An array of strings (ids passed to 'method', all of whose writes have been reflected in data messages)
*/
open func methodWasUpdated(_ methods:[String]) {
if let updated = events.onUpdated { updated(methods) }
}
/**
Executes when the client receives an error message from the server. Such a message is used to represent errors raised by the method or subscription, as well as an attempt to subscribe to an unknown subscription or call an unknown method.
- parameter message: A DDPError object with information about the error
*/
open func didReceiveErrorMessage(_ message: DDPError) {
if let error = events.onError { error(message) }
}
}
|
mit
|
ba171da95f42289386092c2aa220a96b
| 36.372681 | 242 | 0.587808 | 5.111162 | false | false | false | false |
RaviDesai/CodeMashSample
|
iTunesRest/iTunesRestTests/StringExtensionsTests.swift
|
1
|
1048
|
//
// StringExtensionsTests.swift
// iTunesRest
//
// Created by Ravi Desai on 10/29/14.
// Copyright (c) 2014 RSD. All rights reserved.
//
import Foundation
import Quick
import Nimble
import iTunesRest
class StringExtensionsSpec : QuickSpec {
override func spec() {
describe("String extension specs") {
it("regular substring with String.Index still works") {
var mystr = "I love swift string extensions"
var start = advance(mystr.startIndex, 2)
var end = advance(start, 4)
expect(mystr[start..<end]).to(equal("love"))
}
it("substring range with integer") {
var mystr = "I love swift string extensions"
expect(mystr[2...5]).to(equal("love"))
}
it("set with Integer") {
var mystr = "I love swift string extensions"
mystr[2...5] = "like"
expect(mystr).to(equal("I like swift string extensions"))
}
}
}
}
|
apache-2.0
|
bf16e8a66716e9c18d443433e9816b87
| 29.823529 | 73 | 0.549618 | 4.192 | false | false | false | false |
AndreyBaranchikov/Keinex-iOS
|
Keinex/Defaults.swift
|
1
|
555
|
//
// Defaults.swift
// Keinex
//
// Created by Андрей on 07.08.16.
// Copyright © 2016 Keinex. All rights reserved.
//
import Foundation
import UIKit
let userDefaults = UserDefaults.standard
let isiPad = UIDevice.current.userInterfaceIdiom == UIUserInterfaceIdiom.pad
let latestPostValue = "postValue"
//Sources
let sourceUrl:NSString = "SourceUrlDefault"
let sourceUrlKeinexRu:NSString = "https://keinex.ru/wp-json/wp/v2/posts/"
let sourceUrlKeinexCom:NSString = "http://keinex.com/wp-json/wp/v2/posts/"
let autoDelCache:NSString = "none"
|
mit
|
3b599d5866541f4326ab1ce3863bf6db
| 26.4 | 76 | 0.757299 | 3.113636 | false | false | false | false |
zhuhaow/soca
|
soca/Util/Yaml/Regex.swift
|
1
|
3113
|
import Foundation
func matchRange (string: String, regex: NSRegularExpression) -> NSRange {
let sr = NSMakeRange(0, string.utf16Count)
return regex.rangeOfFirstMatchInString(string, options: nil, range: sr)
}
func matches (string: String, regex: NSRegularExpression) -> Bool {
return matchRange(string, regex).location != NSNotFound
}
func regex (pattern: String, options: String = "") -> NSRegularExpression! {
if matches(options, invalidOptionsPattern) {
return nil
}
let opts = reduce(options, NSRegularExpressionOptions()) {
acc, opt in
acc | (regexOptions[opt] ?? NSRegularExpressionOptions())
}
return NSRegularExpression(pattern: pattern, options: opts, error: nil)
}
let invalidOptionsPattern =
NSRegularExpression(pattern: "[^ixsm]", options: nil, error: nil)!
let regexOptions: [Character: NSRegularExpressionOptions] = [
"i": .CaseInsensitive,
"x": .AllowCommentsAndWhitespace,
"s": .DotMatchesLineSeparators,
"m": .AnchorsMatchLines
]
func replace (regex: NSRegularExpression, template: String) (string: String)
-> String {
var s = NSMutableString(string: string)
let range = NSMakeRange(0, string.utf16Count)
regex.replaceMatchesInString(s, options: nil, range: range,
withTemplate: template)
return s
}
func replace (regex: NSRegularExpression, block: [String] -> String)
(string: String) -> String {
var s = NSMutableString(string: string)
let range = NSMakeRange(0, string.utf16Count)
var offset = 0
regex.enumerateMatchesInString(string, options: nil, range: range) {
result, _, _ in
var captures = [String](count: result.numberOfRanges, repeatedValue: "")
for i in 0..<result.numberOfRanges {
if let r = result.rangeAtIndex(i).toRange() {
captures[i] = (string as NSString).substringWithRange(NSRange(r))
}
}
let replacement = block(captures)
let offR = NSMakeRange(result.range.location + offset, result.range.length)
offset += countElements(replacement) - result.range.length
s.replaceCharactersInRange(offR, withString: replacement)
}
return s
}
func splitLead (regex: NSRegularExpression) (string: String)
-> (String, String) {
let r = matchRange(string, regex)
if r.location == NSNotFound {
return ("", string)
} else {
let s = string as NSString
let i = r.location + r.length
return (s.substringToIndex(i), s.substringFromIndex(i))
}
}
func splitTrail (regex: NSRegularExpression) (string: String)
-> (String, String) {
let r = matchRange(string, regex)
if r.location == NSNotFound {
return (string, "")
} else {
let s = string as NSString
let i = r.location
return (s.substringToIndex(i), s.substringFromIndex(i))
}
}
func substringWithRange (range: NSRange) (string: String) -> String {
return (string as NSString).substringWithRange(range)
}
func substringFromIndex (index: Int) (string: String) -> String {
return (string as NSString).substringFromIndex(index)
}
func substringToIndex (index: Int) (string: String) -> String {
return (string as NSString).substringToIndex(index)
}
|
mit
|
f2edcb103edbd7df524607b9f16fd2b4
| 31.092784 | 79 | 0.702538 | 4.05867 | false | false | false | false |
radazzouz/firefox-ios
|
Client/Frontend/Home/ActivityStreamPanel.swift
|
1
|
26492
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Shared
import UIKit
import Deferred
import Storage
import WebImage
import XCGLogger
private let log = Logger.browserLogger
private let DefaultSuggestedSitesKey = "topSites.deletedSuggestedSites"
// MARK: - Lifecycle
struct ASPanelUX {
static let backgroundColor = UIColor(white: 1.0, alpha: 0.5)
static let topSitesCacheSize = 12
static let historySize = 10
static let rowHeight: CGFloat = 65
static let sectionHeight: CGFloat = 15
static let footerHeight: CGFloat = 0
// These ratios repersent how much space the topsites require.
// They are calculated from the iphone 5 which requires 220px of vertical height on a 320px width screen.
// 320/220 = 1.4545.
static let TopSiteDoubleRowRatio: CGFloat = 1.4545
static let TopSiteSingleRowRatio: CGFloat = 4.7333
static let PageControlOffsetSize: CGFloat = 20
}
class ActivityStreamPanel: UITableViewController, HomePanel {
weak var homePanelDelegate: HomePanelDelegate?
fileprivate let profile: Profile
fileprivate let telemetry: ActivityStreamTracker
fileprivate let topSitesManager = ASHorizontalScrollCellManager()
fileprivate var isInitialLoad = true //Prevents intro views from flickering while content is loading
fileprivate let events = [NotificationFirefoxAccountChanged, NotificationProfileDidFinishSyncing, NotificationPrivateDataClearedHistory, NotificationDynamicFontChanged]
fileprivate var sessionStart: Timestamp?
lazy var longPressRecognizer: UILongPressGestureRecognizer = {
return UILongPressGestureRecognizer(target: self, action: #selector(ActivityStreamPanel.longPress(_:)))
}()
var highlights: [Site] = []
init(profile: Profile, telemetry: ActivityStreamTracker? = nil) {
self.profile = profile
self.telemetry = telemetry ?? ActivityStreamTracker(eventsTracker: PingCentre.clientForTopic(.ActivityStreamEvents, clientID: profile.clientID),
sessionsTracker: PingCentre.clientForTopic(.ActivityStreamSessions, clientID: profile.clientID))
super.init(style: .grouped)
view.addGestureRecognizer(longPressRecognizer)
self.profile.history.setTopSitesCacheSize(Int32(ASPanelUX.topSitesCacheSize))
events.forEach { NotificationCenter.default.addObserver(self, selector: #selector(self.notificationReceived(_:)), name: $0, object: nil) }
}
deinit {
events.forEach { NotificationCenter.default.removeObserver(self, name: $0, object: nil) }
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
Section.allValues.forEach { tableView.register(Section($0.rawValue).cellType, forCellReuseIdentifier: Section($0.rawValue).cellIdentifier) }
tableView.backgroundColor = ASPanelUX.backgroundColor
tableView.keyboardDismissMode = .onDrag
tableView.separatorStyle = .none
tableView.delegate = self
tableView.dataSource = self
tableView.rowHeight = UITableViewAutomaticDimension
tableView.separatorInset = UIEdgeInsets.zero
tableView.estimatedRowHeight = ASPanelUX.rowHeight
tableView.estimatedSectionHeaderHeight = ASPanelUX.sectionHeight
tableView.sectionFooterHeight = ASPanelUX.footerHeight
tableView.sectionHeaderHeight = UITableViewAutomaticDimension
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
sessionStart = Date.now()
all([invalidateTopSites(), invalidateHighlights()]).uponQueue(DispatchQueue.main) { _ in
self.isInitialLoad = false
self.reloadAll()
}
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
telemetry.reportSessionStop(Date.now() - (sessionStart ?? 0))
sessionStart = nil
}
override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
super.traitCollectionDidChange(previousTraitCollection)
self.topSitesManager.currentTraits = self.traitCollection
DispatchQueue.main.async {
self.tableView.reloadData()
}
}
}
// MARK: - Section management
extension ActivityStreamPanel {
enum Section: Int {
case topSites
case highlights
case highlightIntro
static let count = 3
static let allValues = [topSites, highlights, highlightIntro]
var title: String? {
switch self {
case .highlights: return Strings.ASHighlightsTitle
case .topSites: return nil
case .highlightIntro: return nil
}
}
var headerHeight: CGFloat {
switch self {
case .highlights: return 40
case .topSites: return 0
case .highlightIntro: return 2
}
}
func cellHeight(_ traits: UITraitCollection, width: CGFloat) -> CGFloat {
switch self {
case .highlights: return UITableViewAutomaticDimension
case .topSites:
if traits.horizontalSizeClass == .compact && traits.verticalSizeClass == .regular {
return CGFloat(Int(width / ASPanelUX.TopSiteDoubleRowRatio)) + ASPanelUX.PageControlOffsetSize
} else {
return CGFloat(Int(width / ASPanelUX.TopSiteSingleRowRatio)) + ASPanelUX.PageControlOffsetSize
}
case .highlightIntro: return UITableViewAutomaticDimension
}
}
var headerView: UIView? {
switch self {
case .highlights:
let view = ASHeaderView()
view.title = title
return view
case .topSites:
return nil
case .highlightIntro:
let view = ASHeaderView()
view.title = title
return view
}
}
var cellIdentifier: String {
switch self {
case .topSites: return "TopSiteCell"
case .highlights: return "HistoryCell"
case .highlightIntro: return "HighlightIntroCell"
}
}
var cellType: UITableViewCell.Type {
switch self {
case .topSites: return ASHorizontalScrollCell.self
case .highlights: return AlternateSimpleHighlightCell.self
case .highlightIntro: return HighlightIntroCell.self
}
}
init(at indexPath: IndexPath) {
self.init(rawValue: indexPath.section)!
}
init(_ section: Int) {
self.init(rawValue: section)!
}
}
}
// MARK: - Tableview Delegate
extension ActivityStreamPanel {
override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
// Depending on if highlights are present. Hide certain section headers.
switch Section(section) {
case .highlights:
return highlights.isEmpty ? 0 : Section(section).headerHeight
case .highlightIntro:
return !highlights.isEmpty ? 0 : Section(section).headerHeight
case .topSites:
return Section(section).headerHeight
}
}
override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
return Section(section).headerView
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return Section(indexPath.section).cellHeight(self.traitCollection, width: self.view.frame.width)
}
fileprivate func showSiteWithURLHandler(_ url: URL) {
let visitType = VisitType.bookmark
homePanelDelegate?.homePanel(self, didSelectURL: url, visitType: visitType)
}
override func tableView(_ tableView: UITableView, willSelectRowAt indexPath: IndexPath) -> IndexPath? {
self.longPressRecognizer.isEnabled = false
return indexPath
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
selectItemAtIndex(indexPath.item, inSection: Section(indexPath.section))
}
}
// MARK: - Tableview Data Source
extension ActivityStreamPanel {
override func numberOfSections(in tableView: UITableView) -> Int {
return Section.count
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
switch Section(section) {
case .topSites:
return topSitesManager.content.isEmpty ? 0 : 1
case .highlights:
return self.highlights.count
case .highlightIntro:
return self.highlights.isEmpty && !self.isInitialLoad ? 1 : 0
}
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let identifier = Section(indexPath.section).cellIdentifier
let cell = tableView.dequeueReusableCell(withIdentifier: identifier, for: indexPath)
switch Section(indexPath.section) {
case .topSites:
return configureTopSitesCell(cell, forIndexPath: indexPath)
case .highlights:
return configureHistoryItemCell(cell, forIndexPath: indexPath)
case .highlightIntro:
return configureHighlightIntroCell(cell, forIndexPath: indexPath)
}
}
func configureTopSitesCell(_ cell: UITableViewCell, forIndexPath indexPath: IndexPath) -> UITableViewCell {
let topSiteCell = cell as! ASHorizontalScrollCell
topSiteCell.delegate = self.topSitesManager
return cell
}
func configureHistoryItemCell(_ cell: UITableViewCell, forIndexPath indexPath: IndexPath) -> UITableViewCell {
let site = highlights[indexPath.row]
let simpleHighlightCell = cell as! AlternateSimpleHighlightCell
simpleHighlightCell.configureWithSite(site)
return simpleHighlightCell
}
func configureHighlightIntroCell(_ cell: UITableViewCell, forIndexPath indexPath: IndexPath) -> UITableViewCell {
let introCell = cell as! HighlightIntroCell
//The cell is configured on creation. No need to configure
return introCell
}
}
// MARK: - Data Management
extension ActivityStreamPanel {
func notificationReceived(_ notification: Notification) {
switch notification.name {
case NotificationProfileDidFinishSyncing, NotificationFirefoxAccountChanged, NotificationPrivateDataClearedHistory, NotificationDynamicFontChanged:
self.invalidateTopSites().uponQueue(DispatchQueue.main) { _ in
self.reloadAll()
}
default:
log.warning("Received unexpected notification \(notification.name)")
}
}
fileprivate func reloadAll() {
self.tableView.reloadData()
}
fileprivate func invalidateHighlights() -> Success {
return self.profile.recommendations.getHighlights().bindQueue(DispatchQueue.main) { result in
self.highlights = result.successValue?.asArray() ?? self.highlights
return succeed()
}
}
fileprivate func invalidateTopSites() -> Success {
let frecencyLimit = ASPanelUX.topSitesCacheSize
// Update our top sites cache if it's been invalidated
return self.profile.history.updateTopSitesCacheIfInvalidated() >>== { _ in
return self.profile.history.getTopSitesWithLimit(frecencyLimit) >>== { topSites in
let mySites = topSites.asArray()
let defaultSites = self.defaultTopSites()
// Merge default topsites with a user's topsites.
let mergedSites = mySites.union(defaultSites, f: { (site) -> String in
return URL(string: site.url)?.hostSLD ?? ""
})
// Favour topsites from defaultSites as they have better favicons.
let newSites = mergedSites.map { site -> Site in
let domain = URL(string: site.url)?.hostSLD
return defaultSites.find { $0.title.lowercased() == domain } ?? site
}
self.topSitesManager.currentTraits = self.view.traitCollection
self.topSitesManager.content = newSites.count > ASPanelUX.topSitesCacheSize ? Array(newSites[0..<ASPanelUX.topSitesCacheSize]) : newSites
self.topSitesManager.urlPressedHandler = { [unowned self] url, indexPath in
self.longPressRecognizer.isEnabled = false
self.telemetry.reportEvent(.Click, source: .TopSites, position: indexPath.item)
self.showSiteWithURLHandler(url as URL)
}
return succeed()
}
}
}
func hideURLFromTopSites(_ siteURL: URL) {
guard let host = siteURL.normalizedHost else {
return
}
let url = siteURL.absoluteString
// if the default top sites contains the siteurl. also wipe it from default suggested sites.
if defaultTopSites().filter({$0.url == url}).isEmpty == false {
deleteTileForSuggestedSite(url)
}
profile.history.removeHostFromTopSites(host).uponQueue(DispatchQueue.main) { result in
guard result.isSuccess else { return }
self.invalidateTopSites().uponQueue(DispatchQueue.main) { _ in
self.reloadAll()
}
}
}
func hideFromHighlights(_ site: Site) {
profile.recommendations.removeHighlightForURL(site.url).uponQueue(DispatchQueue.main) { result in
guard result.isSuccess else { return }
self.invalidateHighlights().uponQueue(DispatchQueue.main) { _ in
self.reloadAll()
}
}
}
fileprivate func deleteTileForSuggestedSite(_ siteURL: String) {
var deletedSuggestedSites = profile.prefs.arrayForKey(DefaultSuggestedSitesKey) as? [String] ?? []
deletedSuggestedSites.append(siteURL)
profile.prefs.setObject(deletedSuggestedSites, forKey: DefaultSuggestedSitesKey)
}
func defaultTopSites() -> [Site] {
let suggested = SuggestedSites.asArray()
let deleted = profile.prefs.arrayForKey(DefaultSuggestedSitesKey) as? [String] ?? []
return suggested.filter({deleted.index(of: $0.url) == .none})
}
@objc fileprivate func longPress(_ longPressGestureRecognizer: UILongPressGestureRecognizer) {
guard longPressGestureRecognizer.state == UIGestureRecognizerState.began else { return }
let touchPoint = longPressGestureRecognizer.location(in: self.view)
guard let indexPath = tableView.indexPathForRow(at: touchPoint) else { return }
switch Section(indexPath.section) {
case .highlights:
presentContextMenuForHighlightCellWithIndexPath(indexPath)
case .topSites:
let topSiteCell = self.tableView.cellForRow(at: indexPath) as! ASHorizontalScrollCell
let pointInTopSite = longPressGestureRecognizer.location(in: topSiteCell.collectionView)
guard let topSiteIndexPath = topSiteCell.collectionView.indexPathForItem(at: pointInTopSite) else { return }
presentContextMenuForTopSiteCellWithIndexPath(topSiteIndexPath)
case .highlightIntro:
break
}
}
func presentContextMenu(_ contextMenu: ActionOverlayTableViewController) {
contextMenu.modalPresentationStyle = .overFullScreen
contextMenu.modalTransitionStyle = .crossDissolve
self.present(contextMenu, animated: true, completion: nil)
}
func presentContextMenuForTopSiteCellWithIndexPath(_ indexPath: IndexPath) {
let topsiteIndex = IndexPath(row: 0, section: Section.topSites.rawValue)
guard let topSiteCell = self.tableView.cellForRow(at: topsiteIndex) as? ASHorizontalScrollCell else { return }
guard let topSiteItemCell = topSiteCell.collectionView.cellForItem(at: indexPath) as? TopSiteItemCell else { return }
let siteImage = topSiteItemCell.imageView.image
let siteBGColor = topSiteItemCell.contentView.backgroundColor
let site = self.topSitesManager.content[indexPath.item]
presentContextMenuForSite(site, atIndex: indexPath.item, forSection: .topSites, siteImage: siteImage, siteBGColor: siteBGColor)
}
func presentContextMenuForHighlightCellWithIndexPath(_ indexPath: IndexPath) {
guard let highlightCell = tableView.cellForRow(at: indexPath) as? AlternateSimpleHighlightCell else { return }
let siteImage = highlightCell.siteImageView.image
let siteBGColor = highlightCell.siteImageView.backgroundColor
let site = highlights[indexPath.row]
presentContextMenuForSite(site, atIndex: indexPath.row, forSection: .highlights, siteImage: siteImage, siteBGColor: siteBGColor)
}
fileprivate func fetchBookmarkStatusThenPresentContextMenu(_ site: Site, atIndex index: Int, forSection section: Section, siteImage: UIImage?, siteBGColor: UIColor?) {
profile.bookmarks.modelFactory >>== {
$0.isBookmarked(site.url).uponQueue(DispatchQueue.main) { result in
guard let isBookmarked = result.successValue else {
log.error("Error getting bookmark status: \(result.failureValue).")
return
}
site.setBookmarked(isBookmarked)
self.presentContextMenuForSite(site, atIndex: index, forSection: section, siteImage: siteImage, siteBGColor: siteBGColor)
}
}
}
func presentContextMenuForSite(_ site: Site, atIndex index: Int, forSection section: Section, siteImage: UIImage?, siteBGColor: UIColor?) {
guard let _ = site.bookmarked else {
fetchBookmarkStatusThenPresentContextMenu(site, atIndex: index, forSection: section, siteImage: siteImage, siteBGColor: siteBGColor)
return
}
guard let contextMenu = contextMenuForSite(site, atIndex: index, forSection: section, siteImage: siteImage, siteBGColor: siteBGColor) else {
return
}
self.presentContextMenu(contextMenu)
}
func contextMenuForSite(_ site: Site, atIndex index: Int, forSection section: Section, siteImage: UIImage?, siteBGColor: UIColor?) -> ActionOverlayTableViewController? {
guard let siteURL = URL(string: site.url) else {
return nil
}
let pingSource: ASPingSource
switch section {
case .topSites:
pingSource = .TopSites
case .highlights:
pingSource = .Highlights
case .highlightIntro:
pingSource = .HighlightsIntro
}
let openInNewTabAction = ActionOverlayTableViewAction(title: Strings.OpenInNewTabContextMenuTitle, iconString: "action_new_tab") { action in
self.homePanelDelegate?.homePanelDidRequestToOpenInNewTab(siteURL, isPrivate: false)
}
let openInNewPrivateTabAction = ActionOverlayTableViewAction(title: Strings.OpenInNewPrivateTabContextMenuTitle, iconString: "action_new_private_tab") { action in
self.homePanelDelegate?.homePanelDidRequestToOpenInNewTab(siteURL, isPrivate: true)
}
let bookmarkAction: ActionOverlayTableViewAction
if site.bookmarked ?? false {
bookmarkAction = ActionOverlayTableViewAction(title: Strings.RemoveBookmarkContextMenuTitle, iconString: "action_bookmark_remove", handler: { action in
self.profile.bookmarks.modelFactory >>== {
$0.removeByURL(siteURL.absoluteString)
site.setBookmarked(false)
}
})
} else {
bookmarkAction = ActionOverlayTableViewAction(title: Strings.BookmarkContextMenuTitle, iconString: "action_bookmark", handler: { action in
let shareItem = ShareItem(url: site.url, title: site.title, favicon: site.icon)
self.profile.bookmarks.shareItem(shareItem)
var userData = [QuickActions.TabURLKey: shareItem.url]
if let title = shareItem.title {
userData[QuickActions.TabTitleKey] = title
}
QuickActions.sharedInstance.addDynamicApplicationShortcutItemOfType(.openLastBookmark,
withUserData: userData,
toApplication: UIApplication.shared)
site.setBookmarked(true)
})
}
let deleteFromHistoryAction = ActionOverlayTableViewAction(title: Strings.DeleteFromHistoryContextMenuTitle, iconString: "action_delete", handler: { action in
self.telemetry.reportEvent(.Delete, source: pingSource, position: index)
self.profile.history.removeHistoryForURL(site.url)
})
let shareAction = ActionOverlayTableViewAction(title: Strings.ShareContextMenuTitle, iconString: "action_share", handler: { action in
let helper = ShareExtensionHelper(url: siteURL, tab: nil, activities: [])
let controller = helper.createActivityViewController { completed, activityType in
self.telemetry.reportEvent(.Share, source: pingSource, position: index, shareProvider: activityType)
}
self.present(controller, animated: true, completion: nil)
})
let removeTopSiteAction = ActionOverlayTableViewAction(title: Strings.RemoveFromASContextMenuTitle, iconString: "action_close", handler: { action in
self.telemetry.reportEvent(.Dismiss, source: pingSource, position: index)
self.hideURLFromTopSites(site.tileURL)
})
let dismissHighlightAction = ActionOverlayTableViewAction(title: Strings.RemoveFromASContextMenuTitle, iconString: "action_close", handler: { action in
self.telemetry.reportEvent(.Dismiss, source: pingSource, position: index)
self.hideFromHighlights(site)
})
var actions = [openInNewTabAction, openInNewPrivateTabAction, bookmarkAction, shareAction]
switch section {
case .highlights: actions.append(contentsOf: [dismissHighlightAction, deleteFromHistoryAction])
case .topSites: actions.append(removeTopSiteAction)
case .highlightIntro: break
}
return ActionOverlayTableViewController(site: site, actions: actions, siteImage: siteImage, siteBGColor: siteBGColor)
}
func selectItemAtIndex(_ index: Int, inSection section: Section) {
switch section {
case .highlights:
telemetry.reportEvent(.Click, source: .Highlights, position: index)
let site = self.highlights[index]
showSiteWithURLHandler(URL(string:site.url)!)
case .topSites, .highlightIntro:
return
}
}
}
// MARK: Telemetry
enum ASPingEvent: String {
case Click = "CLICK"
case Delete = "DELETE"
case Dismiss = "DISMISS"
case Share = "SHARE"
}
enum ASPingSource: String {
case Highlights = "HIGHLIGHTS"
case TopSites = "TOP_SITES"
case HighlightsIntro = "HIGHLIGHTS_INTRO"
}
struct ActivityStreamTracker {
let eventsTracker: PingCentreClient
let sessionsTracker: PingCentreClient
func reportEvent(_ event: ASPingEvent, source: ASPingSource, position: Int, shareProvider: String? = nil) {
var eventPing: [String: Any] = [
"event": event.rawValue,
"page": "NEW_TAB",
"source": source.rawValue,
"action_position": position,
"app_version": AppInfo.appVersion,
"build": AppInfo.buildNumber,
"locale": Locale.current.identifier,
"release_channel": AppConstants.BuildChannel.rawValue
]
if let provider = shareProvider {
eventPing["share_provider"] = provider
}
eventsTracker.sendPing(eventPing as [String : AnyObject], validate: true)
}
func reportSessionStop(_ duration: UInt64) {
sessionsTracker.sendPing([
"session_duration": NSNumber(value: duration),
"app_version": AppInfo.appVersion,
"build": AppInfo.buildNumber,
"locale": Locale.current.identifier,
"release_channel": AppConstants.BuildChannel.rawValue
], validate: true)
}
}
// MARK: - Section Header View
struct ASHeaderViewUX {
static let SeperatorColor = UIColor(rgb: 0xedecea)
static let TextFont = DynamicFontHelper.defaultHelper.DefaultSmallFontBold
static let SeperatorHeight = 1
static let Insets: CGFloat = 20
static let TitleTopInset: CGFloat = 5
}
class ASHeaderView: UIView {
lazy fileprivate var titleLabel: UILabel = {
let titleLabel = UILabel()
titleLabel.text = self.title
titleLabel.textColor = UIColor.gray
titleLabel.font = ASHeaderViewUX.TextFont
return titleLabel
}()
var title: String? {
willSet(newTitle) {
titleLabel.text = newTitle
}
}
override init(frame: CGRect) {
super.init(frame: frame)
addSubview(titleLabel)
titleLabel.snp.makeConstraints { make in
make.leading.equalTo(self).inset(ASHeaderViewUX.Insets)
make.trailing.equalTo(self).inset(-ASHeaderViewUX.Insets)
make.top.equalTo(self).inset(ASHeaderViewUX.TitleTopInset)
make.bottom.equalTo(self)
}
let seperatorLine = UIView()
seperatorLine.backgroundColor = ASHeaderViewUX.SeperatorColor
addSubview(seperatorLine)
seperatorLine.snp.makeConstraints { make in
make.height.equalTo(ASHeaderViewUX.SeperatorHeight)
make.leading.equalTo(self.snp.leading)
make.trailing.equalTo(self.snp.trailing)
make.top.equalTo(self.snp.top)
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
|
mpl-2.0
|
23ad9c2b1decf43732bebcac3c0b2194
| 40.264798 | 173 | 0.663219 | 5.256349 | false | false | false | false |
ioriwellings/BluetoothKit
|
Source/BKSendDataTask.swift
|
13
|
2658
|
//
// BluetoothKit
//
// Copyright (c) 2015 Rasmus Taulborg Hummelmose - https://github.com/rasmusth
//
// 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
internal func ==(lhs: BKSendDataTask, rhs: BKSendDataTask) -> Bool {
return lhs.destination == rhs.destination && lhs.data.isEqualToData(rhs.data)
}
internal class BKSendDataTask: Equatable {
// MARK: Properties
internal let data: NSData
internal let destination: BKRemoteCentral
internal let completionHandler: ((data: NSData, remoteCentral: BKRemoteCentral, error: BKPeripheral.Error?) -> Void)?
internal var offset = 0
internal var maximumPayloadLength: Int {
return destination.central.maximumUpdateValueLength
}
internal var lengthOfRemainingData: Int {
return data.length - offset
}
internal var sentAllData: Bool {
return lengthOfRemainingData == 0
}
internal var rangeForNextPayload: NSRange {
let lenghtOfNextPayload = maximumPayloadLength <= lengthOfRemainingData ? maximumPayloadLength : lengthOfRemainingData
return NSMakeRange(offset, lenghtOfNextPayload)
}
internal var nextPayload: NSData {
return data.subdataWithRange(rangeForNextPayload)
}
// MARK: Initialization
internal init(data: NSData, destination: BKRemoteCentral, completionHandler: ((data: NSData, remoteCentral: BKRemoteCentral, error: BKPeripheral.Error?) -> Void)?) {
self.data = data
self.destination = destination
self.completionHandler = completionHandler
}
}
|
mit
|
731bf82c6ab43b62347efb2d9291e952
| 37.521739 | 169 | 0.720467 | 4.868132 | false | false | false | false |
InversePandas/Fire
|
Fire/ViewController.swift
|
1
|
13476
|
//
// ViewController.swift
// Fire
//
// Created by Karen Kennedy on 12/5/14.
// Copyright (c) 2014 Karen Kennedy. All rights reserved.
//
import UIKit
import MessageUI
import CoreLocation
import CoreData
import Foundation
// URL for FireServer
let FireURL: NSString = "http://actonadream.org/fireServer.php"
// How often do we update location when contacting server
let UpdateInterval: NSTimeInterval = 10*60 // every 10 minutes
class ViewController: UIViewController, MFMessageComposeViewControllerDelegate, CLLocationManagerDelegate {
// (Lat,Long) of user is stored here as soon as it is received
var locationManager: CLLocationManager!
var firstLocation: Bool = false // set to false when running in simulator, true otherwise
var locData: CLLocationCoordinate2D!
var locCount: integer_t = 0
var notificationSet: Bool = true
// used to store results from databse
var contact_entries = [NSManagedObject]()
// used to update server with new user position
var timer: NSTimer? = nil
/*********************** UIViewController Functions **********************/
// Runs once the view has appeared
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
}
// Runs once the view has loaded
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
// load the location manager to start querying for location data
self.launchLocationManager()
// setting a fire date for our notification
let date_current = NSDate()
let calendar = NSCalendar.currentCalendar()
let components = calendar.components( .CalendarUnitYear | .CalendarUnitMonth | .CalendarUnitDay | .CalendarUnitHour | .CalendarUnitMinute, fromDate: date_current)
let year = components.year
let month = components.month
let day = components.day
let hour = components.hour
let minutes = components.minute
if notificationSet {
var dateComp:NSDateComponents = NSDateComponents()
dateComp.year = year;
dateComp.month = month;
dateComp.day = day;
dateComp.hour = hour;
dateComp.minute = (minutes + 1) % 60;
dateComp.timeZone = NSTimeZone.systemTimeZone()
var calender:NSCalendar! = NSCalendar(calendarIdentifier: NSGregorianCalendar)
// defining our variable date made of our datecomponents shown above
var date:NSDate! = calender.dateFromComponents(dateComp)
var notification:UILocalNotification = UILocalNotification()
notification.category = "FIRST_CATEGORY"
notification.alertBody = "Are you doing ok? Swipe left to respond."
notification.fireDate = date
notification.repeatInterval = .CalendarUnitDay
UIApplication.sharedApplication().scheduleLocalNotification(notification)
notificationSet = false;
}
}
// Runs once a memory warning is received
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/* Fire Button calls this function which attempt to send a request to the server (if online) or a
* text message to the list of contacts (if not online) for our single fire approach
* This function is also called the first time we acquire a valid location for the user (as soon as the
* app is launched.
*/
@IBAction func sendMessage(sender: AnyObject) {
// attempt contact with server to check internet connectivity
self.post(["type": "connection"], url: FireURL) { (succeeded: Bool, reply: NSDictionary) -> ()
in
// we have internet access, so send the request to the server
if (succeeded) {
self.sendMsgToServer(self.constructTxtMsg(), phoneList: self.getContactNumbers())
// sendMessage again every UpdateInterval
self.timer = NSTimer.scheduledTimerWithTimeInterval(UpdateInterval, target: self, selector: Selector("sendMessage"), userInfo: nil, repeats: false)
// TODO - alert the user that this is happening
}
// ask the user to send the message because we have no internet access
else {
self.presentViewController(self.constructMessageView(), animated: true, completion: nil)
// turn off the NSTimer if existent
if (self.timer != nil) {
self.timer!.invalidate()
self.timer = nil
}
// TODO - should alert user that location will NOT be updated automatically
}
}
}
/*********************** MFMessageComposeViewController functions **********************/
func messageComposeViewController(controller: MFMessageComposeViewController!, didFinishWithResult result: MessageComposeResult) {
switch (result.value) {
case MessageComposeResultCancelled.value:
println("Message was cancelled")
self.dismissViewControllerAnimated(true, completion: nil)
case MessageComposeResultFailed.value:
println("Message failed")
self.dismissViewControllerAnimated(true, completion: nil)
case MessageComposeResultSent.value:
println("Message was sent")
self.dismissViewControllerAnimated(true, completion: nil)
default:
break;
}
}
/*********************** CLLocationManagerDelegate Functions **********************/
/*
* This function is called as soon as the Location has been updated
*/
func locationManager(manager:CLLocationManager, didUpdateLocations locations:[AnyObject]) {
// store the updated location in the class
self.locData = manager.location.coordinate
self.locCount++
println("Location was updated successfully to coordinates \(self.locData.latitude), \(self.locData.longitude). Total updates: \(self.locCount).")
// first time we see the location
if (self.firstLocation) {
// don't present the view again unless it is the first location
self.firstLocation = false
self.sendMessage([])
}
}
/*********************** Useful Helper Functions **********************/
/*
* Connects to remote server and sends the messageText to the phone numbers in the phoneList
* (or attempts to, the server currently does nothing)
*/
func sendMsgToServer(messageText: String, phoneList: NSMutableArray) -> Bool {
// sending
self.post(["type": "message", "text": messageText, "phones": phoneList.componentsJoinedByString(",")], url: FireURL) { (succeeded: Bool, response: NSDictionary) -> () in
var alert = UIAlertController(title: "Success!", message: "Empty!", preferredStyle: UIAlertControllerStyle.Alert)
if(succeeded) {
alert.title = "Success!"
alert.message = response["msg"] as? String
// we can also parse the server response here using response["json"] information
}
else {
alert.title = "Failed : ("
alert.message = response["msg"] as? String
}
// Move to the UI thread
dispatch_async(dispatch_get_main_queue(), { () -> Void in
// Show the alert
self.presentViewController(alert, animated: true, completion: nil)
})
}
return true
}
/*
* Connects to the contact database and returns an array of phone
* numbers to whom the text message should be sent!
*/
func getContactNumbers() -> NSMutableArray{
//1
let appDelegate =
UIApplication.sharedApplication().delegate as AppDelegate
let managedContext = appDelegate.managedObjectContext!
// 2
let fetchRequest = NSFetchRequest(entityName:"Contacts")
//3
var error: NSError?
let fetchedResults =
managedContext.executeFetchRequest(fetchRequest,
error: &error) as [NSManagedObject]?
if let results = fetchedResults {
contact_entries = results
} else {
println("Could not fetch \(error), \(error!.userInfo)")
}
var phoneNumbers: NSMutableArray = NSMutableArray()
for entry in contact_entries {
var phone: String = entry.valueForKey("contactPhoneNumber") as String
phoneNumbers.addObject(phone)
}
return phoneNumbers
}
/*
* Constructs a message to place into the message sent from this phone
*/
func constructTxtMsg() -> String {
var mapURL = ""
if (self.locData != nil) {
mapURL += "You can find me here: https://maps.google.com/maps?saddr=Current+Location&daddr=\(self.locData.latitude),\(self.locData.longitude)"
}
var msg = "Please help! I'm currently in a life threatening situation and you're my number one emergency contact.";
return msg + mapURL
}
/*
* Constructs a new message view with the contact numbers
* required for this button - currently, this means the default
* button.
*/
func constructMessageView() -> MFMessageComposeViewController {
var messageVC = MFMessageComposeViewController()
messageVC.body = self.constructTxtMsg()
messageVC.recipients = self.getContactNumbers()
messageVC.messageComposeDelegate = self;
return messageVC
}
/*
* Starts the location manager aspect of the class so GPS
* coordinates can be stored in self.locationManager
*/
func launchLocationManager () -> Void {
locationManager = CLLocationManager()
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
// request authorization from the user
locationManager.requestAlwaysAuthorization()
locationManager.startUpdatingLocation()
}
/*
* Source: http://jamesonquave.com/blog/making-a-post-request-in-swift/
* Sends a post request with params to the specified url
*/
func post(params : Dictionary<String, String>, url : String, postCompleted : (succeeded: Bool, response: NSDictionary) -> ()) {
var request = NSMutableURLRequest(URL: NSURL(string: url)!)
var session = NSURLSession.sharedSession()
request.HTTPMethod = "POST"
var err: NSError?
request.HTTPBody = NSJSONSerialization.dataWithJSONObject(params, options: nil, error: &err)
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
var task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in
println("Response: \(response)")
var strData = NSString(data: data, encoding: NSUTF8StringEncoding)
println("Body: \(strData)")
var err: NSError?
var json = NSJSONSerialization.JSONObjectWithData(data, options: .MutableLeaves, error: &err) as? NSDictionary
var msg = "No message"
// Did the JSONObjectWithData constructor return an error? If so, log the error to the console
if(err != nil) {
println(err!.localizedDescription)
let jsonStr = NSString(data: data, encoding: NSUTF8StringEncoding)
println("Error could not parse JSON: '\(jsonStr)'")
postCompleted(succeeded: false, response: ["msg": "Error in response."])
}
else {
// The JSONObjectWithData constructor didn't return an error. But, we should still
// check and make sure that json has a value using optional binding.
if let parseJSON = json {
// Okay, the parsedJSON is here, let's get the value for 'success' out of it
if let success = parseJSON["success"] as? Bool {
println("Success: \(success)")
postCompleted(succeeded: success, response: ["json" : parseJSON,
"msg": "Connection Successful"])
}
return
}
else {
// Woa, okay the json object was nil, something went wrong. Maybe the server isn't running?
let jsonStr = NSString(data: data, encoding: NSUTF8StringEncoding)
println("Error could not parse JSON: \(jsonStr)")
postCompleted(succeeded: false, response: ["msg": "Error in connection"])
}
}
})
task.resume()
}
}
|
gpl-3.0
|
0fa4c3d7939e46640df29e535eee1224
| 40.340491 | 177 | 0.601365 | 5.534292 | false | false | false | false |
Bouke/HAP
|
Sources/HAP/Base/Predefined/Characteristics/Characteristic.SetDuration.swift
|
1
|
2053
|
import Foundation
public extension AnyCharacteristic {
static func setDuration(
_ value: UInt32 = 0,
permissions: [CharacteristicPermission] = [.read, .write, .events],
description: String? = "Set Duration",
format: CharacteristicFormat? = .uint32,
unit: CharacteristicUnit? = .seconds,
maxLength: Int? = nil,
maxValue: Double? = 3600,
minValue: Double? = 0,
minStep: Double? = 1,
validValues: [Double] = [],
validValuesRange: Range<Double>? = nil
) -> AnyCharacteristic {
AnyCharacteristic(
PredefinedCharacteristic.setDuration(
value,
permissions: permissions,
description: description,
format: format,
unit: unit,
maxLength: maxLength,
maxValue: maxValue,
minValue: minValue,
minStep: minStep,
validValues: validValues,
validValuesRange: validValuesRange) as Characteristic)
}
}
public extension PredefinedCharacteristic {
static func setDuration(
_ value: UInt32 = 0,
permissions: [CharacteristicPermission] = [.read, .write, .events],
description: String? = "Set Duration",
format: CharacteristicFormat? = .uint32,
unit: CharacteristicUnit? = .seconds,
maxLength: Int? = nil,
maxValue: Double? = 3600,
minValue: Double? = 0,
minStep: Double? = 1,
validValues: [Double] = [],
validValuesRange: Range<Double>? = nil
) -> GenericCharacteristic<UInt32> {
GenericCharacteristic<UInt32>(
type: .setDuration,
value: value,
permissions: permissions,
description: description,
format: format,
unit: unit,
maxLength: maxLength,
maxValue: maxValue,
minValue: minValue,
minStep: minStep,
validValues: validValues,
validValuesRange: validValuesRange)
}
}
|
mit
|
256b03192afc79eb6cc154e94bea9305
| 32.655738 | 75 | 0.575743 | 5.291237 | false | false | false | false |
mgingras/garagr
|
garagrIOS/ViewController.swift
|
1
|
5587
|
//
// ViewController.swift
// garagrIOS
//
// Created by Martin Gingras on 2014-12-01.
// Copyright (c) 2014 mgingras. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var formUsername: UITextField!
@IBOutlet weak var formPassword: UITextField!
@IBOutlet weak var feedback: UILabel!
var userId: NSNumber?
var username: NSString?
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func validateUsernameAndPassword(){
if formUsername.hasText() && formPassword.hasText() {
getUserInfo(formUsername.text, formPassword: formPassword.text, handleFormInput)
}
}
func handleFormInput(isValid: Bool){
if(isValid){
self.performSegueWithIdentifier("moveToUserViewSegue", sender: self)
}
}
func getUserInfo(formUsername: String, formPassword: String, callback: (Bool)-> Void){
let url = NSURL(string: "http://localhost:3000/login?username=" + formUsername + "&password=" + formPassword)
var request = NSMutableURLRequest(URL: url!)
request.HTTPMethod = "POST"
let task = NSURLSession.sharedSession().dataTaskWithRequest(request){(data, response, error) in
println(NSString(data: data, encoding: NSUTF8StringEncoding))
var err: NSError?
var jsonResult = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &err) as NSDictionary
if (err != nil) {
println("JSON Error \(err!.localizedDescription)")
}
let status: String! = jsonResult["status"] as NSString
if status != "ok" {
let message: String! = jsonResult["message"] as NSString
NSOperationQueue.mainQueue().addOperationWithBlock(){
self.feedback.text = message
callback(false)
}
} else{
NSOperationQueue.mainQueue().addOperationWithBlock(){
self.userId = jsonResult["userId"] as? NSNumber
self.username = formUsername
callback(true)
}
}
}
task.resume()
}
@IBAction func showSignUpAlert(){
showAlert("Enter details below")
}
func showAlert(message :NSString){
var alert = UIAlertController(title: "Create new account", message: message, preferredStyle: .Alert)
alert.addTextFieldWithConfigurationHandler({ (textField) -> Void in
textField.placeholder = "Username"
})
alert.addTextFieldWithConfigurationHandler({ (textField) -> Void in
textField.placeholder = "Password"
textField.secureTextEntry = true
})
alert.addAction(UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel){
UIAlertAction in
})
alert.addAction(UIAlertAction(title: "OK", style: .Default, handler: { (action) -> Void in
let desiredUsername = alert.textFields![0] as UITextField
let desiredPassword = alert.textFields![1] as UITextField
if !desiredPassword.hasText() || !desiredUsername.hasText() {
self.showAlert("Please enter your desired Username and Password")
}else{
var url = NSURL(string: "http://localhost:3000/users?username=" + desiredUsername.text + "&password=" + desiredPassword.text)
var request = NSMutableURLRequest(URL: url!)
request.HTTPMethod = "POST"
let task = NSURLSession.sharedSession().dataTaskWithRequest(request){(data, response, error) in
println(NSString(data: data, encoding: NSUTF8StringEncoding))
var err: NSError?
var jsonResult = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &err) as NSDictionary
if (err != nil) {
println("JSON Error \(err!.localizedDescription)")
}
let status: String! = jsonResult["status"] as NSString
if status != "ok" {
let message: String! = jsonResult["message"] as NSString
self.showAlert(message)
}else{
self.userId = jsonResult["userId"] as? NSNumber
NSOperationQueue.mainQueue().addOperationWithBlock(){
self.formUsername.text = desiredUsername.text
}
}
}
task.resume()
}
}))
self.presentViewController(alert, animated: true, completion: nil)
}
override func prepareForSegue(segue: (UIStoryboardSegue!), sender: AnyObject!) {
if segue.identifier == "moveToUserViewSegue" {
let appDelegate = UIApplication.sharedApplication().delegate as AppDelegate
appDelegate.userId = self.userId
appDelegate.username = self.username
}
}
}
|
mit
|
5294819f54bfe1b8c2ec676b30d686e4
| 38.624113 | 159 | 0.578844 | 5.570289 | false | false | false | false |
kyouko-taiga/anzen
|
Sources/AnzenIR/AIRBuilder.swift
|
1
|
5838
|
import AST
public class AIRBuilder {
public init(unit: AIRUnit, context: ASTContext) {
self.unit = unit
self.context = context
}
/// The AIR unit being edited.
public let unit: AIRUnit
/// The AST context of the unit.
public let context: ASTContext
/// The current instruction block.
public var currentBlock: InstructionBlock?
/// Creates a new reference in the current instruction block.
public func buildMakeRef(
type: AIRType,
withID id: Int? = nil,
debugInfo: DebugInfo? = nil) -> MakeRefInst
{
let registerID = id ?? currentBlock!.nextRegisterID()
let inst = MakeRefInst(type: type, id: registerID, debugInfo: debugInfo)
currentBlock!.instructions.append(inst)
return inst
}
public func buildAlloc(
type: AIRType,
withID id: Int? = nil,
debugInfo: DebugInfo? = nil) -> AllocInst
{
let registerID = id ?? currentBlock!.nextRegisterID()
let inst = AllocInst(type: type, id: registerID, debugInfo: debugInfo)
currentBlock!.instructions.append(inst)
return inst
}
public func buildUnsafeCast(
source: AIRValue,
as castType: AIRType,
withID id: Int? = nil,
debugInfo: DebugInfo? = nil) -> UnsafeCastInst
{
let registerID = id ?? currentBlock!.nextRegisterID()
let inst = UnsafeCastInst(
operand: source,
type: castType,
id: registerID,
debugInfo: debugInfo)
currentBlock!.instructions.append(inst)
return inst
}
public func buildExtract(
from source: AIRRegister,
index: Int,
type: AIRType,
withID id: Int? = nil,
debugInfo: DebugInfo? = nil) -> ExtractInst
{
let registerID = id ?? currentBlock!.nextRegisterID()
let inst = ExtractInst(
source: source,
index: index,
type: type,
id: registerID,
debugInfo: debugInfo)
currentBlock!.instructions.append(inst)
return inst
}
public func buildRefEq(
lhs: AIRValue,
rhs: AIRValue,
withID id: Int? = nil,
debugInfo: DebugInfo? = nil) -> RefEqInst
{
let registerID = id ?? currentBlock!.nextRegisterID()
let inst = RefEqInst(lhs: lhs, rhs: rhs, id: registerID, debugInfo: debugInfo)
currentBlock!.instructions.append(inst)
return inst
}
public func buildRefNe(
lhs: AIRValue,
rhs: AIRValue,
withID id: Int? = nil,
debugInfo: DebugInfo? = nil) -> RefNeInst
{
let registerID = id ?? currentBlock!.nextRegisterID()
let inst = RefNeInst(lhs: lhs, rhs: rhs, id: registerID, debugInfo: debugInfo)
currentBlock!.instructions.append(inst)
return inst
}
public func buildApply(
callee: AIRValue,
arguments: [AIRValue],
type: AIRType,
withID id: Int? = nil,
debugInfo: DebugInfo? = nil) -> ApplyInst
{
let registerID = id ?? currentBlock!.nextRegisterID()
let inst = ApplyInst(
callee: callee,
arguments: arguments,
type: type,
id: registerID,
debugInfo: debugInfo)
currentBlock!.instructions.append(inst)
return inst
}
public func buildPartialApply(
function: AIRFunction,
arguments: [AIRValue],
type: AIRType,
withID id: Int? = nil,
debugInfo: DebugInfo? = nil) -> PartialApplyInst
{
let registerID = id ?? currentBlock!.nextRegisterID()
let inst = PartialApplyInst(
function: function,
arguments: arguments,
type: type,
id: registerID,
debugInfo: debugInfo)
currentBlock!.instructions.append(inst)
return inst
}
@discardableResult
public func buildReturn(value: AIRValue? = nil) -> ReturnInst {
let inst = ReturnInst(value: value)
currentBlock!.instructions.append(inst)
return inst
}
@discardableResult
public func buildCopy(source: AIRValue, target: AIRRegister, debugInfo: DebugInfo? = nil)
-> CopyInst
{
let inst = CopyInst(source: source, target: target, debugInfo: debugInfo)
currentBlock!.instructions.append(inst)
return inst
}
@discardableResult
public func buildMove(source: AIRValue, target: AIRRegister, debugInfo: DebugInfo? = nil)
-> MoveInst
{
let inst = MoveInst(source: source, target: target, debugInfo: debugInfo)
currentBlock!.instructions.append(inst)
return inst
}
@discardableResult
public func buildBind(source: AIRValue, target: AIRRegister, debugInfo: DebugInfo? = nil)
-> BindInst
{
let inst = BindInst(source: source, target: target, debugInfo: debugInfo)
currentBlock!.instructions.append(inst)
return inst
}
@discardableResult
public func build(
assignment: BindingOperator,
source: AIRValue,
target: AIRRegister,
debugInfo: DebugInfo? = nil) -> AIRInstruction
{
switch assignment {
case .copy: return buildCopy(source: source, target: target, debugInfo: debugInfo)
case .move: return buildMove(source: source, target: target, debugInfo: debugInfo)
case .ref : return buildBind(source: source, target: target, debugInfo: debugInfo)
}
}
@discardableResult
public func buildDrop(value: MakeRefInst, debugInfo: DebugInfo? = nil) -> DropInst {
let inst = DropInst(value: value, debugInfo: debugInfo)
currentBlock!.instructions.append(inst)
return inst
}
@discardableResult
public func buildBranch(
condition: AIRValue,
thenLabel: String,
elseLabel: String,
debugInfo: DebugInfo? = nil) -> BranchInst
{
let inst = BranchInst(
condition: condition,
thenLabel: thenLabel,
elseLabel: elseLabel,
debugInfo: debugInfo)
currentBlock!.instructions.append(inst)
return inst
}
@discardableResult
public func buildJump(label: String, debugInfo: DebugInfo? = nil) -> JumpInst {
let inst = JumpInst(label: label, debugInfo: debugInfo)
currentBlock!.instructions.append(inst)
return inst
}
}
|
apache-2.0
|
65fcdc510f463c57f193f4c15b6ceae6
| 26.537736 | 91 | 0.675916 | 4.009615 | false | false | false | false |
Boilertalk/VaporFacebookBot
|
Sources/VaporFacebookBot/Webhooks/FacebookCallback.swift
|
1
|
890
|
//
// FacebookCallback.swift
// VaporFacebookBot
//
// Created by Koray Koska on 24/05/2017.
//
//
import Foundation
import Vapor
public final class FacebookCallback: JSONConvertible {
public var object: String
public var entry: [FacebookCallbackEntry]
public init(json: JSON) throws {
object = try json.get("object")
if let a = json["entry"]?.array {
var arr = [FacebookCallbackEntry]()
for e in a {
arr.append(try FacebookCallbackEntry(json: e))
}
entry = arr
} else {
throw Abort(.badRequest, metadata: "entry is not set or is not an array in FacebookCallback")
}
}
public func makeJSON() throws -> JSON {
var json = JSON()
try json.set("object", object)
try json.set("entry", entry.jsonArray())
return json
}
}
|
mit
|
446f9dcc0cfdd75f6bf5de59949cb502
| 21.820513 | 105 | 0.583146 | 4.238095 | false | false | false | false |
Amosel/CollectionView
|
CollectionView/Node.swift
|
1
|
2656
|
import Foundation
class Node : Hashable, Equatable {
init(name:String, type:NodeType, createChildren: () -> Set<Node>) {
self.nodeType = type
self.name = name
self.children = createChildren()
onChildrenChanged(self.children, old: Set<Node>())
}
init(name:String, type:NodeType) {
self.nodeType = type
self.name = name
self.children = Set<Node>()
}
let name:String
enum NodeType : Int {
case normal = 1
case important = 2
case critical = 3
}
let nodeType:NodeType
// setting the parent should be possible only internally.
// do not set the parent extenally.
weak var parent: Node? {
didSet {
parentHash = self.parent?.hashValue ?? 0
}
}
func onChildrenChanged(_ new:Set<Node>,old:Set<Node>) {
for child in old.filter( {!new.contains($0)} ) {
child.parent = nil
}
for child in new {
child.parent = self
}
}
var children : Set<Node> {
didSet {
onChildrenChanged(children, old: oldValue)
}
}
var parentHash:Int = 0
var hashValue: Int {
get {
return parentHash ^ self.children.hashValue ^ nodeType.hashValue ^ (name.hashValue << 8)
}
}
func walk(_ level:Int, visit: (_ node:Node,_ level:Int) -> ()) {
visit(self,level)
let nextLevel = level+1
for each in self.children {
each.walk(nextLevel, visit: visit)
}
}
func walk(_ visit: (_ node:Node, _ level:Int) -> ()) {
walk(0, visit: visit)
}
var groupByLevel : [Int:[Node]] {
var mutable = [Int:[Node]]()
walk { node, level in
if var nodes:[Node] = mutable[level] {
nodes.append(node)
} else {
mutable[level] = [node]
}
}
return mutable
}
static func ==(lhs:Node, rhs:Node) -> Bool {
return lhs.hashValue == rhs.hashValue
}
}
extension Node {
var byIndexPaths : [IndexPath : Node] {
var mutable : [IndexPath : Node] = [:]
self.walk({ (node, level) -> () in
let indexPath = mutable.keys.nextIndexPathInSection(level)
mutable[indexPath] = node
})
return mutable
}
var array : [[Node]] {
var mutable = [[Node]]()
self.walk({ (node, level) -> () in
if mutable.count > level {
mutable[level] = mutable[level]+[node]
} else {
mutable.append([node])
}
})
return mutable
}
}
|
mit
|
e2a37b208ffd15f7aff0882a1d7e2e01
| 25.29703 | 101 | 0.519955 | 4.054962 | false | false | false | false |
roshanman/FriendCircle
|
FriendCircle/Classes/Tools/Date+Extension.swift
|
1
|
1030
|
//
// Date+Extension.swift
// FriendCircle
//
// Created by zhangxiuming on 2017/09/23.
//
import Foundation
extension Date {
var formatedPublish: String {
let now = Date()
let interval = now.timeIntervalSince(self)
let hour = Int(interval / 3600)
switch hour {
case 0:
return "刚刚"
case 1...23:
return "\(hour)小时前"
default:
if year != now.year {
return "\(now.year - year)年前"
}
if month != now.month {
return "\(now.month - month)月前"
}
return "\(now.day - day)天前"
}
}
}
extension Date {
var year: Int {
return Calendar.current.component(.year, from: self)
}
var month: Int {
return Calendar.current.component(.month, from: self)
}
var day: Int {
return Calendar.current.component(.day, from: self)
}
}
|
mit
|
1f19f2da49226153e4fbe4153df457bb
| 19.16 | 61 | 0.481151 | 4.182573 | false | false | false | false |
AlexeyTyurenkov/NBUStats
|
NBUStatProject/NBUStat/Modules/UXCurrentIndex/UXCurrentIndexPresenter.swift
|
1
|
1510
|
//
// UXCurrentIndexPresenter.swift
// FinStat Ukraine
//
// Created by Aleksey Tyurenkov on 3/6/18.
// Copyright © 2018 Oleksii Tiurenkov. All rights reserved.
//
import Foundation
import FinstatLib
enum IndexError:Error
{
case general
}
protocol UXCurrentIndexPresenterProtocol: PresenterProtocol {
func showDataProviderInfo()
}
class UXCurrentIndexPresenter: UXCurrentIndexPresenterProtocol
{
weak var delegate: PresenterViewDelegate?
var router: UXCurrentIndexRouter?
var interactor = UXCurrentIndexInteractor()
var currentModel: UXCurrencyIndexModel?
func updateView() {
}
func viewLoaded() {
interactor.load { (models, error) in
guard error == nil else { self.delegate?.presenter(self, getError: error!); return }
if let model = models.first
{
self.currentModel = model
self.delegate?.presenter(self, updateAsProfessional: false)
}
else
{
self.delegate?.presenter(self, getError: IndexError.general)
}
}
}
var cellTypes: [BaseTableCellProtocol.Type] = []
var dataProviderInfo: DataProviderInfoProtocol {
return self
}
func showDataProviderInfo() {
if let controller = delegate as? UXCurrentIndexViewController
{
router?.presentDataProviderInfo(from: controller, dataProviderInfo: dataProviderInfo)
}
}
}
|
mit
|
e31b19605f6ad9657a9dbf2742fc4b9c
| 24.15 | 97 | 0.636846 | 4.715625 | false | false | false | false |
planvine/Line-Up-iOS-SDK
|
Pod/Classes/Network/Reachability.swift
|
1
|
1100
|
//
// Reachability.swift
// Pods
//
// Created by Andrea Ferrando on 31/03/2016.
//
//
import SystemConfiguration
/**
* Reachability is a public class regardings the network reachability
* - Note: Reachability.isConnectedToNetwork() returns true if the device is connected to a network
*/
@objc public class Reachability : LineUp {
class func isConnectedToNetwork() -> Bool {
var zeroAddress = sockaddr_in()
zeroAddress.sin_len = UInt8(sizeofValue(zeroAddress))
zeroAddress.sin_family = sa_family_t(AF_INET)
let defaultRouteReachability = withUnsafePointer(&zeroAddress) {
SCNetworkReachabilityCreateWithAddress(nil, UnsafePointer($0))
}
var flags = SCNetworkReachabilityFlags()
if !SCNetworkReachabilityGetFlags(defaultRouteReachability!, &flags) {
return false
}
let isReachable = (flags.rawValue & UInt32(kSCNetworkFlagsReachable)) != 0
let needsConnection = (flags.rawValue & UInt32(kSCNetworkFlagsConnectionRequired)) != 0
return (isReachable && !needsConnection)
}
}
|
mit
|
19deecff184684fe86c3db3ed28f4078
| 34.516129 | 99 | 0.691818 | 4.932735 | false | false | false | false |
matthijs2704/vapor-apns
|
Sources/VaporAPNS/Payload.swift
|
1
|
8092
|
//
// Payload.swift
// VaporAPNS
//
// Created by Matthijs Logemann on 01/10/2016.
//
//
import Foundation
import JSON
import Core
open class Payload: JSONRepresentable {
/// The number to display as the badge of the app icon.
public var badge: Int?
/// A short string describing the purpose of the notification. Apple Watch displays this string as part of the notification interface. This string is displayed only briefly and should be crafted so that it can be understood quickly. This key was added in iOS 8.2.
public var title: String?
// A secondary description of the reason for the alert.
public var subtitle: String?
/// The text of the alert message. Can be nil if using titleLocKey
public var body: String?
/// The key to a title string in the Localizable.strings file for the current localization. The key string can be formatted with %@ and %n$@ specifiers to take the variables specified in the titleLocArgs array.
public var titleLocKey: String?
/// Variable string values to appear in place of the format specifiers in titleLocKey.
public var titleLocArgs: [String]?
/// If a string is specified, the system displays an alert that includes the Close and View buttons. The string is used as a key to get a localized string in the current localization to use for the right button’s title instead of “View”.
public var actionLocKey: String?
/// A key to an alert-message string in a Localizable.strings file for the current localization (which is set by the user’s language preference). The key string can be formatted with %@ and %n$@ specifiers to take the variables specified in the bodyLocArgs array.
public var bodyLocKey: String?
/// Variable string values to appear in place of the format specifiers in bodyLocKey.
public var bodyLocArgs: [String]?
/// The filename of an image file in the app bundle, with or without the filename extension. The image is used as the launch image when users tap the action button or move the action slider. If this property is not specified, the system either uses the previous snapshot, uses the image identified by the UILaunchImageFile key in the app’s Info.plist file, or falls back to Default.png.
public var launchImage: String?
/// The name of a sound file in the app bundle or in the Library/Sounds folder of the app’s data container. The sound in this file is played as an alert. If the sound file doesn’t exist or default is specified as the value, the default alert sound is played.
public var sound: String?
/// a category that is used by iOS 10+ notifications
public var category: String?
/// Silent push notification. This automatically ignores any other push message keys (title, body, ect.) and only the extra key-value pairs are added to the final payload
public var contentAvailable: Bool = false
/// A Boolean indicating whether the payload contains content that can be modified by an iOS 10+ Notification Service Extension (media, encrypted content, ...)
public var hasMutableContent: Bool = false
/// When displaying notifications, the system visually groups notifications with the same thread identifier together.
public var threadId: String?
// Any extra key-value pairs to add to the JSON
public var extra: [String: NodeRepresentable] = [:]
// Simple, empty initializer
public init() {}
open func makeJSON() throws -> JSON {
var payloadData: [String: NodeRepresentable] = [:]
var apsPayloadData: [String: NodeRepresentable] = [:]
if contentAvailable {
apsPayloadData["content-available"] = true
} else {
// Create alert dictionary
var alert: [String: NodeRepresentable] = [:]
if let title = title {
alert["title"] = title
}
if let titleLocKey = titleLocKey {
alert["title-loc-key"] = titleLocKey
if let titleLocArgs = titleLocArgs {
alert["title-loc-args"] = try titleLocArgs.makeNode(in: nil)
}
}
if let subtitle = subtitle {
alert["subtitle"] = subtitle
}
if let body = body {
alert["body"] = body
} else {
if let bodyLocKey = bodyLocKey {
alert["loc-key"] = bodyLocKey
if let bodyLocArgs = bodyLocArgs {
alert["loc-args"] = try bodyLocArgs.makeNode(in: nil)
}
}
}
if let actionLocKey = actionLocKey {
alert["action-loc-key"] = actionLocKey
}
if let launchImage = launchImage {
alert["launch-image"] = launchImage
}
// Alert dictionary created
apsPayloadData["alert"] = try alert.makeNode(in: nil)
if let badge = badge {
apsPayloadData["badge"] = badge
}
if let sound = sound {
apsPayloadData["sound"] = sound
}
if let category = category {
apsPayloadData["category"] = category
}
if hasMutableContent {
apsPayloadData["mutable-content"] = 1
}
if let threadId = threadId {
apsPayloadData["thread-id"] = threadId
}
}
payloadData["aps"] = try apsPayloadData.makeNode(in: nil)
for (key, value) in extra {
payloadData[key] = value
}
let json = JSON(node: try payloadData.makeNode(in: nil))
return json
}
}
public extension Payload {
public convenience init(message: String) {
self.init()
self.body = message
}
public convenience init(title: String, body: String) {
self.init()
self.title = title
self.body = body
}
public convenience init(title: String, body: String, badge: Int) {
self.init()
self.title = title
self.body = body
self.badge = badge
}
/// A simple, already made, Content-Available payload
public static var contentAvailable: Payload {
let payload = Payload()
payload.contentAvailable = true
return payload
}
}
extension Payload: Equatable {
public static func ==(lhs: Payload, rhs: Payload) -> Bool {
guard lhs.badge == rhs.badge else {
return false
}
guard lhs.title == rhs.title else {
return false
}
guard lhs.body == rhs.body else {
return false
}
guard lhs.titleLocKey == rhs.titleLocKey else {
return false
}
guard lhs.titleLocArgs != nil && rhs.titleLocArgs != nil && lhs.titleLocArgs! == rhs.titleLocArgs! else {
return false
}
guard lhs.actionLocKey == rhs.actionLocKey else {
return false
}
guard lhs.bodyLocKey == rhs.bodyLocKey else {
return false
}
guard lhs.bodyLocArgs != nil && rhs.bodyLocArgs != nil && lhs.bodyLocArgs! == rhs.bodyLocArgs! else {
return false
}
guard lhs.launchImage == rhs.launchImage else {
return false
}
guard lhs.sound == rhs.sound else {
return false
}
guard lhs.contentAvailable == rhs.contentAvailable else {
return false
}
guard lhs.threadId == rhs.threadId else {
return false
}
// guard lhs.extra == rhs.extra else {
// return false
// }
return true
}
}
|
mit
|
011a250b4551785db4a0052f28b1de8b
| 33.669528 | 390 | 0.585417 | 4.922608 | false | false | false | false |
stephentyrone/swift
|
test/Driver/Dependencies/fail-added-fine.swift
|
5
|
2248
|
/// bad ==> main | bad --> other
// RUN: %empty-directory(%t)
// RUN: cp -r %S/Inputs/fail-simple-fine/* %t
// RUN: touch -t 201401240005 %t/*
// RUN: cd %t && %swiftc_driver -c -driver-use-frontend-path "%{python.unquoted};%S/Inputs/update-dependencies.py;%swift-dependency-tool" -output-file-map %t/output.json -incremental -disable-direct-intramodule-dependencies -driver-always-rebuild-dependents ./main.swift ./other.swift -module-name main -j1 -v 2>&1 | %FileCheck -check-prefix=CHECK-INITIAL %s
// CHECK-INITIAL-NOT: warning
// CHECK-INITIAL: Handled main.swift
// CHECK-INITIAL: Handled other.swift
// RUN: cd %t && not %swiftc_driver -c -driver-use-frontend-path "%{python.unquoted};%S/Inputs/update-dependencies-bad.py;%swift-dependency-tool" -output-file-map %t/output.json -incremental -disable-direct-intramodule-dependencies -driver-always-rebuild-dependents ./main.swift ./other.swift ./bad.swift -module-name main -j1 -v 2>&1 | %FileCheck -check-prefix=CHECK-ADDED %s
// RUN: %FileCheck -check-prefix=CHECK-RECORD-ADDED %s < %t/main~buildrecord.swiftdeps
// CHECK-ADDED-NOT: Handled
// CHECK-ADDED: Handled bad.swift
// CHECK-ADDED-NOT: Handled
// CHECK-RECORD-ADDED-DAG: "./bad.swift": !private [
// CHECK-RECORD-ADDED-DAG: "./main.swift": [
// CHECK-RECORD-ADDED-DAG: "./other.swift": [
// RUN: %empty-directory(%t)
// RUN: cp -r %S/Inputs/fail-simple-fine/* %t
// RUN: touch -t 201401240005 %t/*
// RUN: cd %t && %swiftc_driver -c -driver-use-frontend-path "%{python.unquoted};%S/Inputs/update-dependencies.py;%swift-dependency-tool" -output-file-map %t/output.json -incremental -disable-direct-intramodule-dependencies -driver-always-rebuild-dependents ./main.swift ./other.swift -module-name main -j1 -v 2>&1 | %FileCheck -check-prefix=CHECK-INITIAL %s
// RUN: cd %t && not %swiftc_driver -c -driver-use-frontend-path "%{python.unquoted};%S/Inputs/update-dependencies-bad.py;%swift-dependency-tool" -output-file-map %t/output.json -incremental -disable-direct-intramodule-dependencies -driver-always-rebuild-dependents ./bad.swift ./main.swift ./other.swift -module-name main -j1 -v 2>&1 | %FileCheck -check-prefix=CHECK-ADDED %s
// RUN: %FileCheck -check-prefix=CHECK-RECORD-ADDED %s < %t/main~buildrecord.swiftdeps
|
apache-2.0
|
f5558cb0c96e5c4bce6112adf6df56b9
| 69.25 | 376 | 0.72242 | 3.188652 | false | false | false | false |
cotkjaer/Silverback
|
Silverback/List.swift
|
1
|
2106
|
//
// List.swift
// Silverback
//
// Created by Christian Otkjær on 08/10/15.
// Copyright © 2015 Christian Otkjær. All rights reserved.
//
private class Link<E>
{
var element: E
var next: Link<E>?
var previous: Link<E>?
init(element: E)
{
self.element = element
}
func append(element: E) -> Link<E>
{
let link = Link(element: element)
self.next = link
link.previous = self
return link
}
func prepend(element: E) -> Link<E>
{
let link = Link(element: element)
self.previous = link
link.next = self
return link
}
}
public struct LinkedList<Element>
{
private var array = Array<Element>()
private var head: Link<Element>?
private var tail: Link<Element>?
var isEmpty : Bool { return head == nil && tail == nil }
mutating func popFirst() -> Element?
{
if let element = head?.element
{
head = head?.next
if head == nil
{
tail = nil
}
return element
}
return nil
}
mutating func popLast() -> Element?
{
if let element = tail?.element
{
tail = tail?.previous
if tail == nil
{
head = nil
}
return element
}
return nil
}
mutating func append(element: Element)
{
if isEmpty
{
let link = Link(element: element)
head = link
tail = link
}
else
{
tail = tail?.append(element)
}
}
mutating func prepend(element: Element)
{
if isEmpty
{
let link = Link(element: element)
head = link
tail = link
}
else
{
head = head?.prepend(element)
}
}
}
|
mit
|
ac4e30fe2cee8fab78f7498720d4c11c
| 17.12931 | 60 | 0.434617 | 4.834483 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.