repo_name
stringlengths 6
91
| ref
stringlengths 12
59
| path
stringlengths 7
936
| license
stringclasses 15
values | copies
stringlengths 1
3
| content
stringlengths 61
714k
| hash
stringlengths 32
32
| line_mean
float64 4.88
60.8
| line_max
int64 12
421
| alpha_frac
float64 0.1
0.92
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
lforme/VisualArts | refs/heads/master | VisualArts/NetworkingLayer/ReactiveDataRequest.swift | mit | 1 | //
// ReactiveDataRequest.swift
// API
//
// Created by ET|冰琳 on 2017/3/24.
// Copyright © 2017年 IB. All rights reserved.
//
import Foundation
import ReactiveSwift
import Alamofire
import Result
let TokenExpired = 401
let RefreshTokenInvalid = 400
enum ITError: Error {
case tokenExpired
case refreshTokenInvalid
case error(err: NSError)
}
// MARK: - ReactiveExtensionsProvider
extension DataRequest: ReactiveExtensionsProvider{}
extension Reactive where Base: DataRequest{
func responseJSONResponse(queue: DispatchQueue? = nil,
options: JSONSerialization.ReadingOptions = .allowFragments) -> SignalProducer<Any, ITError> {
let signal: SignalProducer<DataResponse<Any>, NoError> = SignalProducer {[base = self.base] (observer, dispose) in
let request = base.responseJSON(queue: queue, options: options, completionHandler: { (response) in
observer.send(value: response)
observer.sendCompleted()
})
dispose += {
request.cancel()
}
}
return signal.flatMap(.latest) { (response) -> SignalProducer<Any, ITError> in
switch response.result {
case .success(let value):
#if DEBUG
print("[SUCEED] [URL: \(response.request)] \n ~~~~ \(value)")
#endif
return SignalProducer.init(value: value)
case .failure(let error):
#if DEBUG
print("[Error] [URL: \(response.request)] \n ~~~~ \(error)")
if let data = response.data, let str = String(data: data, encoding: .utf8) {
print("Error msg:",str)
}
#endif
if let err = error as? AFError,
case let AFError.responseValidationFailed(reason: reason) = err,
case let AFError.ResponseValidationFailureReason.unacceptableStatusCode(code: code) = reason {
if code == TokenExpired {
return SignalProducer.init(error: ITError.tokenExpired)
}
if code == RefreshTokenInvalid {
return SignalProducer.init(error: ITError.refreshTokenInvalid)
}
}
return SignalProducer.init(error: ITError.error(err: error as NSError))
}
}
}
/// response JSON
func responseJSON<T: Error>(
queue: DispatchQueue? = nil,
options: JSONSerialization.ReadingOptions = .allowFragments)
-> SignalProducer<Any, T>
{
return SignalProducer {[base = self.base] (observer, dispose) in
let request = base.responseJSON(queue: queue, options: options, completionHandler: { (response) in
switch response.result{
case .failure(let err):
#if DEBUG
print("[Error] [URL: \(response.request)] \n ~~~~ \(err)")
if let data = response.data, let str = String(data: data, encoding: .utf8) {
print("Error msg:",str)
}
#endif
observer.send(error: err as! T)
case .success(let value):
#if DEBUG
print("[SUCEED] [URL: \(response.request)] \n ~~~~ \(value)")
#endif
observer.send(value: value)
observer.sendCompleted()
}
})
dispose += {
request.cancel()
}
}
}
}
| b4d9859ad809c0604931e509aa81f86b | 33.163793 | 122 | 0.492556 | false | false | false | false |
PaystackHQ/paystack-ios | refs/heads/master | Paystack/Validator/Validator.swift | mit | 3 | //
// Validator.swift
//
// Created by Jeff Potter on 11/10/14.
// Copyright (c) 2015 jpotts18. All rights reserved.
//
import Foundation
import UIKit
/**
Class that makes `Validator` objects. Should be added as a parameter to ViewController that will display
validation fields.
*/
public class Validator {
/// Dictionary to hold all fields (and accompanying rules) that will undergo validation.
public var validations = ValidatorDictionary<ValidationRule>()
/// Dictionary to hold fields (and accompanying errors) that were unsuccessfully validated.
public var errors = ValidatorDictionary<ValidationError>()
/// Dictionary to hold fields by their object identifiers
private var fields = ValidatorDictionary<Validatable>()
/// Variable that holds success closure to display positive status of field.
private var successStyleTransform:((_ validationRule:ValidationRule)->Void)?
/// Variable that holds error closure to display negative status of field.
private var errorStyleTransform:((_ validationError:ValidationError)->Void)?
/// - returns: An initialized object, or nil if an object could not be created for some reason that would not result in an exception.
public init(){}
// MARK: Private functions
/**
This method is used to validate all fields registered to Validator. If validation is unsuccessful,
field gets added to errors dictionary.
- returns: No return value.
*/
private func validateAllFields() {
errors = ValidatorDictionary<ValidationError>()
for (_, rule) in validations {
if let error = rule.validateField() {
errors[rule.field] = error
// let the user transform the field if they want
if let transform = self.errorStyleTransform {
transform(error)
}
} else {
// No error
// let the user transform the field if they want
if let transform = self.successStyleTransform {
transform(rule)
}
}
}
}
// MARK: Public functions
/**
This method is used to validate a single field registered to Validator. If validation is unsuccessful,
field gets added to errors dictionary.
- parameter field: Holds validator field data.
- returns: No return value.
*/
public func validateField(_ field: ValidatableField, callback: (_ error:ValidationError?) -> Void){
if let fieldRule = validations[field] {
if let error = fieldRule.validateField() {
errors[field] = error
if let transform = self.errorStyleTransform {
transform(error)
}
callback(error)
} else {
if let transform = self.successStyleTransform {
transform(fieldRule)
}
callback(nil)
}
} else {
callback(nil)
}
}
// MARK: Using Keys
/**
This method is used to style fields that have undergone validation checks. Success callback should be used to show common success styling and error callback should be used to show common error styling.
- parameter success: A closure which is called with validationRule, an object that holds validation data
- parameter error: A closure which is called with validationError, an object that holds validation error data
- returns: No return value
*/
public func styleTransformers(success:((_ validationRule:ValidationRule)->Void)?, error:((_ validationError:ValidationError)->Void)?) {
self.successStyleTransform = success
self.errorStyleTransform = error
}
/**
This method is used to add a field to validator.
- parameter field: field that is to be validated.
- parameter errorLabel: A UILabel that holds error label data
- parameter rules: A Rule array that holds different rules that apply to said field.
- returns: No return value
*/
public func registerField(_ field: ValidatableField, errorLabel:UILabel? = nil, rules:[Rule]) {
validations[field] = ValidationRule(field: field, rules:rules, errorLabel:errorLabel)
fields[field] = field
}
/**
This method is for removing a field validator.
- parameter field: field used to locate and remove field from validator.
- returns: No return value
*/
public func unregisterField(_ field:ValidatableField) {
validations.removeValueForKey(field)
errors.removeValueForKey(field)
}
/**
This method checks to see if all fields in validator are valid.
- returns: No return value.
*/
public func validate(_ delegate:ValidationDelegate) {
self.validateAllFields()
if errors.isEmpty {
delegate.validationSuccessful()
} else {
delegate.validationFailed(errors.map { (fields[$1.field]!, $1) })
}
}
/**
This method validates all fields in validator and sets any errors to errors parameter of callback.
- parameter callback: A closure which is called with errors, a dictionary of type Validatable:ValidationError.
- returns: No return value.
*/
public func validate(_ callback:(_ errors:[(Validatable, ValidationError)])->Void) -> Void {
self.validateAllFields()
callback(errors.map { (fields[$1.field]!, $1) } )
}
}
| c9996c158f8ce418de18ca7599817f1c | 35.857143 | 205 | 0.629845 | false | false | false | false |
apple/swift-llbuild | refs/heads/main | products/llbuild-analyze/Sources/CriticalPathTool.swift | apache-2.0 | 1 | // This source file is part of the Swift.org open source project
//
// Copyright 2019 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for Swift project authors
import TSCBasic
import llbuildAnalysis
import llbuildSwift
import ArgumentParser
import struct Foundation.Data
import class Foundation.FileManager
import class Foundation.JSONEncoder
struct CriticalPathTool: ParsableCommand {
static var configuration = CommandConfiguration(commandName: "critical-path", shouldDisplay: true)
enum OutputFormat: String, ExpressibleByArgument {
case json, graphviz
}
enum GraphvizDisplay: String, ExpressibleByArgument {
case criticalPath
case all
}
@Argument(help: "Path to the build database.", transform: { AbsolutePath($0) })
var database: AbsolutePath
@Option(name: .shortAndLong, help: "Path to generate exported output to.", transform: { AbsolutePath($0) })
var output: AbsolutePath?
@Option
var clientSchemaVersion: Int = 9
@Option(name: [.customShort("f"), .customLong("outputFormat")], help: "The format of the output file.")
var outputFormat: OutputFormat = .json
@Option(name: .customLong("graphvizOutput"))
var graphvizDisplay: GraphvizDisplay = .criticalPath
@Flag(help: "If outputFormat is set to json, it will be pretty formatted.")
var pretty: Bool = false
@Flag(name: .shortAndLong, help: "Set to hide output to stdout and export only.")
var quiet: Bool = false
func run() throws {
let db = try BuildDB(path: database.pathString, clientSchemaVersion: UInt32(clientSchemaVersion))
let allKeysWithResult = try db.getKeysWithResult()
let solver = CriticalBuildPath.Solver(keys: allKeysWithResult)
let path = solver.run()
// Output
if let outputPath = output {
let data: Data
switch outputFormat {
case .json:
data = try json(path, allKeyResults: allKeysWithResult, buildKeyLookup: solver.keyLookup)
case .graphviz:
data = graphViz(path, buildKeyLookup: solver.keyLookup)
}
try verifyOutputPath()
FileManager.default.createFile(atPath: outputPath.pathString, contents: data)
}
if quiet { return }
print(path.elements.isEmpty ? "Couldn't critical path from database at \(database.pathString) because no builds were build." : "Critical Path:\n\(path)")
}
public func json(_ path: CriticalBuildPath, allKeyResults: BuildDBKeysWithResult, buildKeyLookup: IdentifierFactory<BuildKey>) throws -> Data {
let encoder = JSONEncoder()
if pretty {
encoder.outputFormatting = [.prettyPrinted]
if #available(OSX 10.13, *) {
encoder.outputFormatting.insert(.sortedKeys)
}
}
return try encoder.encode(PathOutput(path, allKeyResults: allKeyResults, buildKeyLookup: buildKeyLookup))
}
private func verifyOutputPath() throws {
guard let outputPath = output else { return }
if FileManager.default.fileExists(atPath: outputPath.pathString) {
throw StringError("Can't output critical path to \(outputPath) - file exists.")
}
}
private func graphViz(_ path: CriticalBuildPath, buildKeyLookup: IdentifierFactory<BuildKey>) -> Data {
var result = "digraph G {\n\tedge [style=dotted]\n"
var edges = Set<DirectedEdge>()
if var last = path.first {
for item in path[1..<path.endIndex] {
edges.insert(DirectedEdge(a: last.key, b: item.key, isCritical: true))
last = item
}
}
if graphvizDisplay == .all {
for element in path {
for dep in element.result.dependencies {
edges.insert(DirectedEdge(a: dep, b: element.key, isCritical: false))
}
}
}
result += edges.map{ $0.graphVizString }.joined()
result += "}"
return result.data(using: .utf8) ?? Data()
}
}
| 339c54d59c97cabd1bc476d2bf9383dd | 36.293103 | 161 | 0.639852 | false | false | false | false |
apple/swift | refs/heads/main | test/Generics/unbound.swift | apache-2.0 | 2 | // RUN: %target-typecheck-verify-swift
// Verify the use of unbound generic types. They are permitted in
// certain places where type inference can fill in the generic
// arguments, and banned everywhere else.
// --------------------------------------------------
// Places where generic arguments are always required
// --------------------------------------------------
struct Foo<T> { // expected-note 3{{generic type 'Foo' declared here}}
struct Wibble { }
}
class Dict<K, V> { } // expected-note{{generic type 'Dict' declared here}} expected-note{{generic type 'Dict' declared here}} expected-note{{generic type 'Dict' declared here}}
// The underlying type of a typealias can only have unbound generic arguments
// at the top level.
typealias F = Foo // OK
typealias FW = Foo.Wibble // expected-error{{reference to generic type 'Foo' requires arguments in <...>}}
typealias FFW = () -> Foo // expected-error{{reference to generic type 'Foo' requires arguments in <...>}}
typealias OFW = Optional<() -> Foo> // expected-error{{reference to generic type 'Foo' requires arguments in <...>}}
// Cannot inherit from a generic type without arguments.
class MyDict : Dict { } // expected-error{{reference to generic type 'Dict' requires arguments in <...>}}
// Cannot create variables of a generic type without arguments.
// FIXME: <rdar://problem/14238814> would allow it for local variables
// only
var x : Dict // expected-error{{reference to generic type 'Dict' requires arguments in <...>}}
// Cannot create parameters of generic type without arguments.
func f(x: Dict) {} // expected-error{{reference to generic type 'Dict' requires arguments in <...>}}
class GC<T, U> {
init() {}
func f() -> GC {
let gc = GC()
return gc
}
}
extension GC {
func g() -> GC {
let gc = GC()
return gc
}
}
class SomeClassWithInvalidMethod {
func method<T>() { // expected-note {{in call to function 'method()'}}
// expected-error@-1 {{generic parameter 'T' is not used in function signature}}
self.method()
// expected-error@-1 {{generic parameter 'T' could not be inferred}}
}
}
// <rdar://problem/20792596> QoI: Cannot invoke with argument list (T), expected an argument list of (T)
protocol r20792596P {}
func foor20792596<T: r20792596P>(x: T) -> T { // expected-note {{where 'T' = 'T'}}
return x
}
func callfoor20792596<T>(x: T) -> T {
return foor20792596(x)
// expected-error@-1 {{missing argument label 'x:' in call}}
// expected-error@-2 {{global function 'foor20792596(x:)' requires that 'T' conform to 'r20792596P'}}
}
// <rdar://problem/31181895> parameter "not used in function signature" when part of a superclass constraint
struct X1<T> {
func bar<U>() where T: X2<U> {}
}
class X2<T> {}
// <rdar://problem/67292528> missing check for unbound parent type
struct Outer<K, V> {
struct Inner {}
struct Middle {
typealias Inner = Outer<K, V>.Middle
}
}
func makeInner() -> Outer<String, String>.Middle.Inner {
return .init()
}
var innerProperty: Outer.Middle.Inner = makeInner()
// expected-error@-1 {{reference to generic type 'Outer' requires arguments in <...>}}
// Some nested generic cases
struct OuterStruct<T> { // expected-note 2{{generic type 'OuterStruct' declared here}}
struct InnerStruct<U> {} // expected-note {{generic type 'InnerStruct' declared here}}
}
func nested(_: OuterStruct.InnerStruct) {}
// expected-error@-1 {{reference to generic type 'OuterStruct' requires arguments in <...>}}
func nested(_: OuterStruct.InnerStruct<Int>) {}
// expected-error@-1 {{reference to generic type 'OuterStruct' requires arguments in <...>}}
func nested(_: OuterStruct<Int>.InnerStruct) {}
// expected-error@-1 {{reference to generic type 'OuterStruct<Int>.InnerStruct' requires arguments in <...>}}
func assertExactType<T>(of _: T, is _: T.Type) {}
// https://github.com/apple/swift/issues/51217
protocol P {
associatedtype A
associatedtype B
}
do {
struct Concrete: P {
typealias A = Int
typealias B = Bool
}
struct Generic<A, B>: P {}
struct BinderGenericParams1<T1: P, T2: P>
where T1.A == T2.A, T1.B == T2.B {
static func bind(_: T1, _: T2) -> T2 {}
}
struct BinderGenericParams2 {
static func bind<T1: P, T2: P>(_: T1, _: T2) -> T2
where T1.A == T2.A, T1.B == T2.B {}
}
let x1 = BinderGenericParams1.bind(Concrete(), Generic())
let x2 = BinderGenericParams2.bind(Concrete(), Generic())
assertExactType(of: x1, is: Generic<Int, Bool>.self)
assertExactType(of: x2, is: Generic<Int, Bool>.self)
}
// https://github.com/apple/swift/issues/60922
enum E<T> {}
// expected-note@-1 2 {{generic type 'E' declared here}}
extension E? {}
// expected-error@-1{{reference to generic type 'E' requires arguments in <...>}}
extension Optional<E> {}
// expected-error@-1{{reference to generic type 'E' requires arguments in <...>}}
struct G<T> {}
// expected-note@-1{{generic type 'G' declared here}}
extension G? {}
// expected-error@-1{{reference to generic type 'G' requires arguments in <...>}}
| 58fa2a6e9a53b9328bc3345c1b253876 | 31.535484 | 176 | 0.662899 | false | false | false | false |
Rehsco/SnappingStepper | refs/heads/master | Sources/SnappingStepper+Internal.swift | mit | 1 | /*
* SnappingStepper
*
* Copyright 2015-present Yannick Loriot.
* http://yannickloriot.com
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*/
import UIKit
import StyledLabel
extension SnappingStepper {
// MARK: - Managing the Components
func initComponents() {
self.layer.addSublayer(styleLayer)
hintLabel.font = thumbFont
hintLabel.textColor = thumbTextColor
minusSymbolLabel.text = "−"
minusSymbolLabel.font = symbolFont
minusSymbolLabel.textColor = symbolFontColor
addSubview(minusSymbolLabel)
plusSymbolLabel.text = "+"
plusSymbolLabel.font = symbolFont
plusSymbolLabel.textColor = symbolFontColor
addSubview(plusSymbolLabel)
thumbLabel.font = thumbFont
thumbLabel.textColor = thumbTextColor
addSubview(thumbLabel)
}
func setupGestures() {
let panGesture = UIPanGestureRecognizer(target: self, action: #selector(SnappingStepper.sliderPanned))
thumbLabel.addGestureRecognizer(panGesture)
let touchGesture = UITouchGestureRecognizer(target: self, action: #selector(SnappingStepper.stepperTouched))
touchGesture.require(toFail: panGesture)
addGestureRecognizer(touchGesture)
}
func layoutComponents() {
let bw = self.direction.principalSize(bounds.size)
let bh = self.direction.nonPrincipalSize(bounds.size)
let thumbWidth = bw * thumbWidthRatio
let symbolWidth = (bw - thumbWidth) / 2
// It makes most sense to have the + on the top of the view, when the direction is vertical
let mpPosM: CGFloat
let mpPosP: CGFloat
if self.direction == .horizontal {
mpPosM = 0
mpPosP = symbolWidth + thumbWidth
}
else {
mpPosM = symbolWidth + thumbWidth
mpPosP = 0
}
let minusSymbolLabelFrame = CGRect(x: mpPosM, y: 0, width: symbolWidth, height: bh)
let plusSymbolLabelFrame = CGRect(x: mpPosP, y: 0, width: symbolWidth, height: bh)
let thumbLabelFrame = CGRect(x: symbolWidth, y: 0, width: thumbWidth, height: bh)
let hintLabelFrame = CGRect(x: symbolWidth, y: -bounds.height * 1.5, width: thumbWidth, height: bh)
minusSymbolLabel.frame = CGRect(origin: self.direction.getPosition(minusSymbolLabelFrame.origin), size: self.direction.getSize(minusSymbolLabelFrame.size))
plusSymbolLabel.frame = CGRect(origin: self.direction.getPosition(plusSymbolLabelFrame.origin), size: self.direction.getSize(plusSymbolLabelFrame.size))
thumbLabel.frame = CGRect(origin: self.direction.getPosition(thumbLabelFrame.origin), size: self.direction.getSize(thumbLabelFrame.size))
// The hint label is not direction dependent
hintLabel.frame = hintLabelFrame
snappingBehavior = SnappingStepperBehavior(item: thumbLabel, snapToPoint: CGPoint(x: bounds.size.width * 0.5, y: bounds.size.height * 0.5))
let hsl = StyledShapeLayer.createHintShapeLayer(hintLabel, fillColor: thumbBackgroundColor?.lighter().cgColor)
hintLabel.layer.addSublayer(hsl)
applyThumbStyle(thumbStyle)
applyStyle(style)
applyHintStyle(hintStyle)
}
func applyThumbStyle(_ style: ShapeStyle) {
thumbLabel.style = style
thumbLabel.borderColor = thumbBorderColor
thumbLabel.borderWidth = thumbBorderWidth
}
func applyHintStyle(_ style: ShapeStyle) {
hintLabel.style = style
}
func applyStyle(_ style: ShapeStyle) {
if self.styleLayer.superlayer == nil {
self.layer.addSublayer(styleLayer)
}
let bgColor: UIColor = self.styleColor ?? .clear
let bgsLayer = StyledShapeLayer.createShape(style, bounds: bounds, color: bgColor)
// Add layer with border, if required
if let bLayer = self.createBorderLayer(style, layerRect: bounds) {
bgsLayer.addSublayer(bLayer)
}
if styleLayer.superlayer != nil {
layer.replaceSublayer(styleLayer, with: bgsLayer)
}
styleLayer = bgsLayer
styleLayer.frame = bounds
}
func createBorderLayer(_ style: ShapeStyle, layerRect: CGRect) -> CALayer? {
let borderWidth = self.borderWidth
if borderWidth > 0 && borderColor != nil {
let bLayer = StyledShapeLayer.createShape(style, bounds: layerRect, color: .clear, borderColor: borderColor ?? .clear, borderWidth: borderWidth)
return bLayer
}
return nil
}
// MARK: - Responding to Gesture Events
func stepperTouched(_ sender: UITouchGestureRecognizer) {
let touchLocation = sender.location(in: self)
let hitView = hitTest(touchLocation, with: nil)
factorValue = hitView == minusSymbolLabel ? -1 : 1
switch (sender.state, hitView) {
case (.began, .some(let v)) where v == minusSymbolLabel || v == plusSymbolLabel:
if autorepeat {
startAutorepeat()
}
else {
let value = _value + stepValue * factorValue
updateValue(value, finished: true)
}
v.backgroundColor = styleColor?.darkened()
case (.changed, .some(let v)):
if v == minusSymbolLabel || v == plusSymbolLabel {
v.backgroundColor = styleColor?.darkened()
if autorepeat {
startAutorepeat()
}
}
else {
minusSymbolLabel.backgroundColor = styleColor
plusSymbolLabel.backgroundColor = styleColor
autorepeatHelper.stop()
}
default:
minusSymbolLabel.backgroundColor = .clear
plusSymbolLabel.backgroundColor = .clear
if autorepeat {
autorepeatHelper.stop()
factorValue = 0
updateValue(_value, finished: true)
}
}
}
func sliderPanned(_ sender: UIPanGestureRecognizer) {
switch sender.state {
case .began:
if case .none = hintStyle {} else {
hintLabel.alpha = 0
hintLabel.center = CGPoint(x: center.x, y: center.y - (bounds.size.height * 0.5 + hintLabel.bounds.height))
superview?.addSubview(hintLabel)
UIView.animate(withDuration: 0.2, animations: {
self.hintLabel.alpha = 1.0
})
}
touchesBeganPoint = self.direction.getPosition(sender.translation(in: thumbLabel))
dynamicButtonAnimator.removeBehavior(snappingBehavior)
thumbLabel.backgroundColor = thumbBackgroundColor?.lighter()
hintLabel.backgroundColor = thumbBackgroundColor?.lighter()
if autorepeat {
startAutorepeat(autorepeatCount: Int.max)
}
else {
initialValue = _value
}
case .changed:
let translationInView = self.direction.getPosition(sender.translation(in: thumbLabel))
let bw = self.direction.principalSize(bounds.size)
let tbw = self.direction.principalSize(thumbLabel.bounds.size)
let tcenter = self.direction.getPosition(thumbLabel.center)
var centerX = (bw * 0.5) + ((touchesBeganPoint.x + translationInView.x) * 0.4)
centerX = max(tbw / 2, min(centerX, bw - tbw / 2))
thumbLabel.center = self.direction.getPosition(CGPoint(x: centerX, y: tcenter.y))
let locationRatio: CGFloat
if self.direction == .horizontal {
locationRatio = (tcenter.x - bounds.midX) / ((bounds.width - thumbLabel.bounds.width) / 2)
}
else {
// The + is on top of the control in vertical layout, so the locationRatio must be reversed!
locationRatio = (bounds.midY - tcenter.x) / ((bounds.height - thumbLabel.bounds.height) / 2)
}
let ratio = Double(Int(locationRatio * 10)) / 10
let factorValue = ((maximumValue - minimumValue) / 100) * ratio * stepFactor
if autorepeat {
self.factorValue = factorValue
}
else {
_value = initialValue + stepValue * factorValue
updateValue(_value, finished: true)
}
case .ended, .failed, .cancelled:
if case .none = hintStyle {} else {
UIView.animate(withDuration: 0.2, animations: {
self.hintLabel.alpha = 0.0
}, completion: { _ in
self.hintLabel.removeFromSuperview()
})
}
dynamicButtonAnimator.addBehavior(snappingBehavior)
thumbLabel.backgroundColor = thumbBackgroundColor ?? styleColor?.lighter()
if autorepeat {
autorepeatHelper.stop()
factorValue = 0
updateValue(_value, finished: true)
}
case .possible:
break
}
}
// MARK: - Updating the Value
func startAutorepeat(autorepeatCount count: Int = 0) {
autorepeatHelper.start(autorepeatCount: count) { [weak self] in
if let weakSelf = self {
let value = weakSelf._value + weakSelf.stepValue * weakSelf.factorValue
weakSelf.updateValue(value, finished: false)
}
}
}
func updateValue(_ value: Double, finished: Bool = true) {
if !wraps {
_value = max(minimumValue, min(value, maximumValue))
}
else if value < minimumValue {
_value = maximumValue
}
else if value > maximumValue {
_value = minimumValue
}
if (continuous || finished) && oldValue != _value {
oldValue = _value
sendActions(for: .valueChanged)
if let _valueChangedBlock = valueChangedBlock {
_valueChangedBlock(_value)
}
}
}
func valueAsText() -> String {
if let formatting = self.thumbTextFormatString {
return String.init(format: formatting, value)
}
else {
return value.truncatingRemainder(dividingBy: 1) == 0 ? "\(Int(value))" : "\(value)"
}
}
}
| 095e7e333c957bb805b6c148a75aa3dd | 32.177778 | 159 | 0.673715 | false | false | false | false |
sag333ar/GoogleBooksAPIResearch | refs/heads/master | GoogleBooksApp/GoogleBooksUI/UserInterfaceModules/BookDetails/View/BookDetailsView.swift | apache-2.0 | 1 |
//
// BooksDetailView.swift
// GoogleBooksApp
//
// Created by Kothari, Sagar on 9/9/17.
// Copyright © 2017 Sagar Kothari. All rights reserved.
//
import UIKit
class BookDetailsView: UIViewController {
// MARK:- Properties
@IBOutlet weak var bookThumbImageView: UIImageView!
@IBOutlet weak var bookTitleLabel: UILabel!
@IBOutlet weak var bookAuthorLabel: UILabel!
@IBOutlet weak var bookSubtitleLabel: UILabel!
@IBOutlet weak var stackView: UIStackView!
@IBOutlet weak var scrollView: UIScrollView!
@IBOutlet weak var contentView: UIView!
var book: Book?
var presenter: BookDetailsPresenter!
// MARK:- Common functions
override func viewDidLoad() {
super.viewDidLoad()
setupVIPER()
loadUIData()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
// MARK:- VIPER Setup
extension BookDetailsView {
func setupVIPER() {
if presenter == nil {
presenter = BookDetailsPresenter()
let interactor = BookDetailsInteractor()
let wireframe = BookDetailsWireframe()
presenter.interactor = interactor
presenter.wireframe = wireframe
presenter.view = self
wireframe.view = self
interactor.presenter = presenter
}
}
}
// MARK:- IBActions
extension BookDetailsView {
@IBAction func btnInfoTapped(_ sender: Any?) {
if let urlString = book?.volumeInfo?.previewLink {
presenter.showInfo(urlString)
} else {
}
}
@IBAction func btnWebReadTapped(_ sender: Any?) {
if let urlString = book?.accessInfo?.webReaderLink {
presenter.showWebReader(urlString)
} else {
}
}
}
| 3a172ecfcc3de9daf4dfce7de92bf5af | 20.558442 | 56 | 0.686747 | false | false | false | false |
rsyncOSX/RsyncOSX | refs/heads/master | RsyncOSX/WriteScheduleJSON.swift | mit | 1 | //
// WriteScheduleJSON.swift
// RsyncUI
//
// Created by Thomas Evensen on 27/04/2021.
//
import Combine
import Foundation
class WriteScheduleJSON: NamesandPaths {
var subscriptons = Set<AnyCancellable>()
// Filename for JSON file
var filenamejson = SharedReference.shared.fileschedulesjson
private func writeJSONToPersistentStore(_ data: String?) {
if var atpath = fullpathmacserial {
do {
if profile != nil {
atpath += "/" + (profile ?? "")
}
let folder = try Folder(path: atpath)
let file = try folder.createFile(named: filenamejson)
if let data = data {
try file.write(data)
if SharedReference.shared.menuappisrunning &&
SharedReference.shared.enableschdules
{
Notifications().showNotification(SharedReference.shared.reloadstring)
DistributedNotificationCenter.default()
.postNotificationName(NSNotification.Name(SharedReference.shared.reloadstring),
object: nil, deliverImmediately: true)
}
}
} catch let e {
let error = e as NSError
self.error(errordescription: error.description, errortype: .readerror)
}
}
}
// We have to remove UUID and computed properties ahead of writing JSON file
// done in the .map operator
@discardableResult
init(_ profile: String?, _ schedules: [ConfigurationSchedule]?) {
super.init(.configurations)
// print("WriteScheduleJSON")
// Set profile and filename ahead of encoding an write
self.profile = profile
schedules.publisher
.map { schedules -> [DecodeSchedule] in
var data = [DecodeSchedule]()
for i in 0 ..< schedules.count where schedules[i].delete ?? false == false {
data.append(DecodeSchedule(schedules[i]))
}
return data
}
.encode(encoder: JSONEncoder())
.sink(receiveCompletion: { completion in
switch completion {
case .finished:
// print("The publisher finished normally.")
return
case let .failure(error):
let error = error as NSError
self.error(errordescription: error.description, errortype: .readerror)
}
}, receiveValue: { [unowned self] result in
let jsonfile = String(data: result, encoding: .utf8)
writeJSONToPersistentStore(jsonfile)
subscriptons.removeAll()
})
.store(in: &subscriptons)
}
}
| 445917f80243b8ecda442ce9d1aeb4b9 | 38.026667 | 107 | 0.53741 | false | false | false | false |
apple/swift-tools-support-core | refs/heads/main | Sources/TSCBasic/FileSystem.swift | apache-2.0 | 1 | /*
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 http://swift.org/LICENSE.txt for license information
See http://swift.org/CONTRIBUTORS.txt for Swift project authors
*/
import TSCLibc
import Foundation
import Dispatch
import SystemPackage
public struct FileSystemError: Error, Equatable {
public enum Kind: Equatable {
/// Access to the path is denied.
///
/// This is used when an operation cannot be completed because a component of
/// the path cannot be accessed.
///
/// Used in situations that correspond to the POSIX EACCES error code.
case invalidAccess
/// IO Error encoding
///
/// This is used when an operation cannot be completed due to an otherwise
/// unspecified IO error.
case ioError(code: Int32)
/// Is a directory
///
/// This is used when an operation cannot be completed because a component
/// of the path which was expected to be a file was not.
///
/// Used in situations that correspond to the POSIX EISDIR error code.
case isDirectory
/// No such path exists.
///
/// This is used when a path specified does not exist, but it was expected
/// to.
///
/// Used in situations that correspond to the POSIX ENOENT error code.
case noEntry
/// Not a directory
///
/// This is used when an operation cannot be completed because a component
/// of the path which was expected to be a directory was not.
///
/// Used in situations that correspond to the POSIX ENOTDIR error code.
case notDirectory
/// Unsupported operation
///
/// This is used when an operation is not supported by the concrete file
/// system implementation.
case unsupported
/// An unspecific operating system error at a given path.
case unknownOSError
/// File or folder already exists at destination.
///
/// This is thrown when copying or moving a file or directory but the destination
/// path already contains a file or folder.
case alreadyExistsAtDestination
/// If an unspecified error occurs when trying to change directories.
case couldNotChangeDirectory
/// If a mismatch is detected in byte count when writing to a file.
case mismatchedByteCount(expected: Int, actual: Int)
}
/// The kind of the error being raised.
public let kind: Kind
/// The absolute path to the file associated with the error, if available.
public let path: AbsolutePath?
public init(_ kind: Kind, _ path: AbsolutePath? = nil) {
self.kind = kind
self.path = path
}
}
extension FileSystemError: CustomNSError {
public var errorUserInfo: [String : Any] {
return [NSLocalizedDescriptionKey: "\(self)"]
}
}
public extension FileSystemError {
init(errno: Int32, _ path: AbsolutePath) {
switch errno {
case TSCLibc.EACCES:
self.init(.invalidAccess, path)
case TSCLibc.EISDIR:
self.init(.isDirectory, path)
case TSCLibc.ENOENT:
self.init(.noEntry, path)
case TSCLibc.ENOTDIR:
self.init(.notDirectory, path)
default:
self.init(.ioError(code: errno), path)
}
}
}
/// Defines the file modes.
public enum FileMode {
public enum Option: Int {
case recursive
case onlyFiles
}
case userUnWritable
case userWritable
case executable
internal var setMode: (Int16) -> Int16 {
switch self {
case .userUnWritable:
// r-x rwx rwx
return {$0 & 0o577}
case .userWritable:
// -w- --- ---
return {$0 | 0o200}
case .executable:
// --x --x --x
return {$0 | 0o111}
}
}
}
// FIXME: Design an asynchronous story?
//
/// Abstracted access to file system operations.
///
/// This protocol is used to allow most of the codebase to interact with a
/// natural filesystem interface, while still allowing clients to transparently
/// substitute a virtual file system or redirect file system operations.
///
/// - Note: All of these APIs are synchronous and can block.
public protocol FileSystem: AnyObject {
/// Check whether the given path exists and is accessible.
func exists(_ path: AbsolutePath, followSymlink: Bool) -> Bool
/// Check whether the given path is accessible and a directory.
func isDirectory(_ path: AbsolutePath) -> Bool
/// Check whether the given path is accessible and a file.
func isFile(_ path: AbsolutePath) -> Bool
/// Check whether the given path is an accessible and executable file.
func isExecutableFile(_ path: AbsolutePath) -> Bool
/// Check whether the given path is accessible and is a symbolic link.
func isSymlink(_ path: AbsolutePath) -> Bool
/// Check whether the given path is accessible and readable.
func isReadable(_ path: AbsolutePath) -> Bool
/// Check whether the given path is accessible and writable.
func isWritable(_ path: AbsolutePath) -> Bool
// FIXME: Actual file system interfaces will allow more efficient access to
// more data than just the name here.
//
/// Get the contents of the given directory, in an undefined order.
func getDirectoryContents(_ path: AbsolutePath) throws -> [String]
/// Get the current working directory (similar to `getcwd(3)`), which can be
/// different for different (virtualized) implementations of a FileSystem.
/// The current working directory can be empty if e.g. the directory became
/// unavailable while the current process was still working in it.
/// This follows the POSIX `getcwd(3)` semantics.
var currentWorkingDirectory: AbsolutePath? { get }
/// Change the current working directory.
/// - Parameters:
/// - path: The path to the directory to change the current working directory to.
func changeCurrentWorkingDirectory(to path: AbsolutePath) throws
/// Get the home directory of current user
var homeDirectory: AbsolutePath { get throws }
/// Get the caches directory of current user
var cachesDirectory: AbsolutePath? { get }
/// Get the temp directory
var tempDirectory: AbsolutePath { get throws }
/// Create the given directory.
func createDirectory(_ path: AbsolutePath) throws
/// Create the given directory.
///
/// - recursive: If true, create missing parent directories if possible.
func createDirectory(_ path: AbsolutePath, recursive: Bool) throws
/// Creates a symbolic link of the source path at the target path
/// - Parameters:
/// - path: The path at which to create the link.
/// - destination: The path to which the link points to.
/// - relative: If `relative` is true, the symlink contents will be a relative path, otherwise it will be absolute.
func createSymbolicLink(_ path: AbsolutePath, pointingAt destination: AbsolutePath, relative: Bool) throws
// FIXME: This is obviously not a very efficient or flexible API.
//
/// Get the contents of a file.
///
/// - Returns: The file contents as bytes, or nil if missing.
func readFileContents(_ path: AbsolutePath) throws -> ByteString
// FIXME: This is obviously not a very efficient or flexible API.
//
/// Write the contents of a file.
func writeFileContents(_ path: AbsolutePath, bytes: ByteString) throws
// FIXME: This is obviously not a very efficient or flexible API.
//
/// Write the contents of a file.
func writeFileContents(_ path: AbsolutePath, bytes: ByteString, atomically: Bool) throws
/// Recursively deletes the file system entity at `path`.
///
/// If there is no file system entity at `path`, this function does nothing (in particular, this is not considered
/// to be an error).
func removeFileTree(_ path: AbsolutePath) throws
/// Change file mode.
func chmod(_ mode: FileMode, path: AbsolutePath, options: Set<FileMode.Option>) throws
/// Returns the file info of the given path.
///
/// The method throws if the underlying stat call fails.
func getFileInfo(_ path: AbsolutePath) throws -> FileInfo
/// Copy a file or directory.
func copy(from sourcePath: AbsolutePath, to destinationPath: AbsolutePath) throws
/// Move a file or directory.
func move(from sourcePath: AbsolutePath, to destinationPath: AbsolutePath) throws
/// Execute the given block while holding the lock.
func withLock<T>(on path: AbsolutePath, type: FileLock.LockType, _ body: () throws -> T) throws -> T
}
/// Convenience implementations (default arguments aren't permitted in protocol
/// methods).
public extension FileSystem {
/// exists override with default value.
func exists(_ path: AbsolutePath) -> Bool {
return exists(path, followSymlink: true)
}
/// Default implementation of createDirectory(_:)
func createDirectory(_ path: AbsolutePath) throws {
try createDirectory(path, recursive: false)
}
// Change file mode.
func chmod(_ mode: FileMode, path: AbsolutePath) throws {
try chmod(mode, path: path, options: [])
}
// Unless the file system type provides an override for this method, throw
// if `atomically` is `true`, otherwise fall back to whatever implementation already exists.
func writeFileContents(_ path: AbsolutePath, bytes: ByteString, atomically: Bool) throws {
guard !atomically else {
throw FileSystemError(.unsupported, path)
}
try writeFileContents(path, bytes: bytes)
}
/// Write to a file from a stream producer.
func writeFileContents(_ path: AbsolutePath, body: (WritableByteStream) -> Void) throws {
let contents = BufferedOutputByteStream()
body(contents)
try createDirectory(path.parentDirectory, recursive: true)
try writeFileContents(path, bytes: contents.bytes)
}
func getFileInfo(_ path: AbsolutePath) throws -> FileInfo {
throw FileSystemError(.unsupported, path)
}
func withLock<T>(on path: AbsolutePath, type: FileLock.LockType, _ body: () throws -> T) throws -> T {
throw FileSystemError(.unsupported, path)
}
}
/// Concrete FileSystem implementation which communicates with the local file system.
private class LocalFileSystem: FileSystem {
func isExecutableFile(_ path: AbsolutePath) -> Bool {
// Our semantics doesn't consider directories.
return (self.isFile(path) || self.isSymlink(path)) && FileManager.default.isExecutableFile(atPath: path.pathString)
}
func exists(_ path: AbsolutePath, followSymlink: Bool) -> Bool {
if followSymlink {
return FileManager.default.fileExists(atPath: path.pathString)
}
return (try? FileManager.default.attributesOfItem(atPath: path.pathString)) != nil
}
func isDirectory(_ path: AbsolutePath) -> Bool {
var isDirectory: ObjCBool = false
let exists: Bool = FileManager.default.fileExists(atPath: path.pathString, isDirectory: &isDirectory)
return exists && isDirectory.boolValue
}
func isFile(_ path: AbsolutePath) -> Bool {
guard let path = try? resolveSymlinks(path) else {
return false
}
let attrs = try? FileManager.default.attributesOfItem(atPath: path.pathString)
return attrs?[.type] as? FileAttributeType == .typeRegular
}
func isSymlink(_ path: AbsolutePath) -> Bool {
let attrs = try? FileManager.default.attributesOfItem(atPath: path.pathString)
return attrs?[.type] as? FileAttributeType == .typeSymbolicLink
}
func isReadable(_ path: AbsolutePath) -> Bool {
FileManager.default.isReadableFile(atPath: path.pathString)
}
func isWritable(_ path: AbsolutePath) -> Bool {
FileManager.default.isWritableFile(atPath: path.pathString)
}
func getFileInfo(_ path: AbsolutePath) throws -> FileInfo {
let attrs = try FileManager.default.attributesOfItem(atPath: path.pathString)
return FileInfo(attrs)
}
var currentWorkingDirectory: AbsolutePath? {
let cwdStr = FileManager.default.currentDirectoryPath
#if _runtime(_ObjC)
// The ObjC runtime indicates that the underlying Foundation has ObjC
// interoperability in which case the return type of
// `fileSystemRepresentation` is different from the Swift implementation
// of Foundation.
return try? AbsolutePath(validating: cwdStr)
#else
let fsr: UnsafePointer<Int8> = cwdStr.fileSystemRepresentation
defer { fsr.deallocate() }
return try? AbsolutePath(String(cString: fsr))
#endif
}
func changeCurrentWorkingDirectory(to path: AbsolutePath) throws {
guard isDirectory(path) else {
throw FileSystemError(.notDirectory, path)
}
guard FileManager.default.changeCurrentDirectoryPath(path.pathString) else {
throw FileSystemError(.couldNotChangeDirectory, path)
}
}
var homeDirectory: AbsolutePath {
get throws {
return try AbsolutePath(validating: NSHomeDirectory())
}
}
var cachesDirectory: AbsolutePath? {
return FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask).first.flatMap { try? AbsolutePath(validating: $0.path) }
}
var tempDirectory: AbsolutePath {
get throws {
let override = ProcessEnv.vars["TMPDIR"] ?? ProcessEnv.vars["TEMP"] ?? ProcessEnv.vars["TMP"]
if let path = override.flatMap({ try? AbsolutePath(validating: $0) }) {
return path
}
return try AbsolutePath(validating: NSTemporaryDirectory())
}
}
func getDirectoryContents(_ path: AbsolutePath) throws -> [String] {
#if canImport(Darwin)
return try FileManager.default.contentsOfDirectory(atPath: path.pathString)
#else
do {
return try FileManager.default.contentsOfDirectory(atPath: path.pathString)
} catch let error as NSError {
// Fixup error from corelibs-foundation.
if error.code == CocoaError.fileReadNoSuchFile.rawValue, !error.userInfo.keys.contains(NSLocalizedDescriptionKey) {
var userInfo = error.userInfo
userInfo[NSLocalizedDescriptionKey] = "The folder “\(path.basename)” doesn’t exist."
throw NSError(domain: error.domain, code: error.code, userInfo: userInfo)
}
throw error
}
#endif
}
func createDirectory(_ path: AbsolutePath, recursive: Bool) throws {
// Don't fail if path is already a directory.
if isDirectory(path) { return }
try FileManager.default.createDirectory(atPath: path.pathString, withIntermediateDirectories: recursive, attributes: [:])
}
func createSymbolicLink(_ path: AbsolutePath, pointingAt destination: AbsolutePath, relative: Bool) throws {
let destString = relative ? destination.relative(to: path.parentDirectory).pathString : destination.pathString
try FileManager.default.createSymbolicLink(atPath: path.pathString, withDestinationPath: destString)
}
func readFileContents(_ path: AbsolutePath) throws -> ByteString {
// Open the file.
let fp = fopen(path.pathString, "rb")
if fp == nil {
throw FileSystemError(errno: errno, path)
}
defer { fclose(fp) }
// Read the data one block at a time.
let data = BufferedOutputByteStream()
var tmpBuffer = [UInt8](repeating: 0, count: 1 << 12)
while true {
let n = fread(&tmpBuffer, 1, tmpBuffer.count, fp)
if n < 0 {
if errno == EINTR { continue }
throw FileSystemError(.ioError(code: errno), path)
}
if n == 0 {
let errno = ferror(fp)
if errno != 0 {
throw FileSystemError(.ioError(code: errno), path)
}
break
}
data <<< tmpBuffer[0..<n]
}
return data.bytes
}
func writeFileContents(_ path: AbsolutePath, bytes: ByteString) throws {
// Open the file.
let fp = fopen(path.pathString, "wb")
if fp == nil {
throw FileSystemError(errno: errno, path)
}
defer { fclose(fp) }
// Write the data in one chunk.
var contents = bytes.contents
while true {
let n = fwrite(&contents, 1, contents.count, fp)
if n < 0 {
if errno == EINTR { continue }
throw FileSystemError(.ioError(code: errno), path)
}
if n != contents.count {
throw FileSystemError(.mismatchedByteCount(expected: contents.count, actual: n), path)
}
break
}
}
func writeFileContents(_ path: AbsolutePath, bytes: ByteString, atomically: Bool) throws {
// Perform non-atomic writes using the fast path.
if !atomically {
return try writeFileContents(path, bytes: bytes)
}
try bytes.withData {
try $0.write(to: URL(fileURLWithPath: path.pathString), options: .atomic)
}
}
func removeFileTree(_ path: AbsolutePath) throws {
do {
try FileManager.default.removeItem(atPath: path.pathString)
} catch let error as NSError {
// If we failed because the directory doesn't actually exist anymore, ignore the error.
if !(error.domain == NSCocoaErrorDomain && error.code == NSFileNoSuchFileError) {
throw error
}
}
}
func chmod(_ mode: FileMode, path: AbsolutePath, options: Set<FileMode.Option>) throws {
guard exists(path) else { return }
func setMode(path: String) throws {
let attrs = try FileManager.default.attributesOfItem(atPath: path)
// Skip if only files should be changed.
if options.contains(.onlyFiles) && attrs[.type] as? FileAttributeType != .typeRegular {
return
}
// Compute the new mode for this file.
let currentMode = attrs[.posixPermissions] as! Int16
let newMode = mode.setMode(currentMode)
guard newMode != currentMode else { return }
try FileManager.default.setAttributes([.posixPermissions : newMode],
ofItemAtPath: path)
}
try setMode(path: path.pathString)
guard isDirectory(path) else { return }
guard let traverse = FileManager.default.enumerator(
at: URL(fileURLWithPath: path.pathString),
includingPropertiesForKeys: nil) else {
throw FileSystemError(.noEntry, path)
}
if !options.contains(.recursive) {
traverse.skipDescendants()
}
while let path = traverse.nextObject() {
try setMode(path: (path as! URL).path)
}
}
func copy(from sourcePath: AbsolutePath, to destinationPath: AbsolutePath) throws {
guard exists(sourcePath) else { throw FileSystemError(.noEntry, sourcePath) }
guard !exists(destinationPath)
else { throw FileSystemError(.alreadyExistsAtDestination, destinationPath) }
try FileManager.default.copyItem(at: sourcePath.asURL, to: destinationPath.asURL)
}
func move(from sourcePath: AbsolutePath, to destinationPath: AbsolutePath) throws {
guard exists(sourcePath) else { throw FileSystemError(.noEntry, sourcePath) }
guard !exists(destinationPath)
else { throw FileSystemError(.alreadyExistsAtDestination, destinationPath) }
try FileManager.default.moveItem(at: sourcePath.asURL, to: destinationPath.asURL)
}
func withLock<T>(on path: AbsolutePath, type: FileLock.LockType = .exclusive, _ body: () throws -> T) throws -> T {
try FileLock.withLock(fileToLock: path, type: type, body: body)
}
}
// FIXME: This class does not yet support concurrent mutation safely.
//
/// Concrete FileSystem implementation which simulates an empty disk.
public class InMemoryFileSystem: FileSystem {
/// Private internal representation of a file system node.
/// Not threadsafe.
private class Node {
/// The actual node data.
let contents: NodeContents
init(_ contents: NodeContents) {
self.contents = contents
}
/// Creates deep copy of the object.
func copy() -> Node {
return Node(contents.copy())
}
}
/// Private internal representation the contents of a file system node.
/// Not threadsafe.
private enum NodeContents {
case file(ByteString)
case directory(DirectoryContents)
case symlink(String)
/// Creates deep copy of the object.
func copy() -> NodeContents {
switch self {
case .file(let bytes):
return .file(bytes)
case .directory(let contents):
return .directory(contents.copy())
case .symlink(let path):
return .symlink(path)
}
}
}
/// Private internal representation the contents of a directory.
/// Not threadsafe.
private class DirectoryContents {
var entries: [String: Node]
init(entries: [String: Node] = [:]) {
self.entries = entries
}
/// Creates deep copy of the object.
func copy() -> DirectoryContents {
let contents = DirectoryContents()
for (key, node) in entries {
contents.entries[key] = node.copy()
}
return contents
}
}
/// The root node of the filesytem.
private var root: Node
/// Protects `root` and everything underneath it.
/// FIXME: Using a single lock for this is a performance problem, but in
/// reality, the only practical use for InMemoryFileSystem is for unit
/// tests.
private let lock = NSLock()
/// A map that keeps weak references to all locked files.
private var lockFiles = Dictionary<AbsolutePath, WeakReference<DispatchQueue>>()
/// Used to access lockFiles in a thread safe manner.
private let lockFilesLock = NSLock()
/// Exclusive file system lock vended to clients through `withLock()`.
// Used to ensure that DispatchQueues are releassed when they are no longer in use.
private struct WeakReference<Value: AnyObject> {
weak var reference: Value?
init(_ value: Value?) {
self.reference = value
}
}
public init() {
root = Node(.directory(DirectoryContents()))
}
/// Creates deep copy of the object.
public func copy() -> InMemoryFileSystem {
return lock.withLock {
let fs = InMemoryFileSystem()
fs.root = root.copy()
return fs
}
}
/// Private function to look up the node corresponding to a path.
/// Not threadsafe.
private func getNode(_ path: AbsolutePath, followSymlink: Bool = true) throws -> Node? {
func getNodeInternal(_ path: AbsolutePath) throws -> Node? {
// If this is the root node, return it.
if path.isRoot {
return root
}
// Otherwise, get the parent node.
guard let parent = try getNodeInternal(path.parentDirectory) else {
return nil
}
// If we didn't find a directory, this is an error.
guard case .directory(let contents) = parent.contents else {
throw FileSystemError(.notDirectory, path.parentDirectory)
}
// Return the directory entry.
let node = contents.entries[path.basename]
switch node?.contents {
case .directory, .file:
return node
case .symlink(let destination):
let destination = try AbsolutePath(validating: destination, relativeTo: path.parentDirectory)
return followSymlink ? try getNodeInternal(destination) : node
case .none:
return nil
}
}
// Get the node that corresponds to the path.
return try getNodeInternal(path)
}
// MARK: FileSystem Implementation
public func exists(_ path: AbsolutePath, followSymlink: Bool) -> Bool {
return lock.withLock {
do {
switch try getNode(path, followSymlink: followSymlink)?.contents {
case .file, .directory, .symlink: return true
case .none: return false
}
} catch {
return false
}
}
}
public func isDirectory(_ path: AbsolutePath) -> Bool {
return lock.withLock {
do {
if case .directory? = try getNode(path)?.contents {
return true
}
return false
} catch {
return false
}
}
}
public func isFile(_ path: AbsolutePath) -> Bool {
return lock.withLock {
do {
if case .file? = try getNode(path)?.contents {
return true
}
return false
} catch {
return false
}
}
}
public func isSymlink(_ path: AbsolutePath) -> Bool {
return lock.withLock {
do {
if case .symlink? = try getNode(path, followSymlink: false)?.contents {
return true
}
return false
} catch {
return false
}
}
}
public func isReadable(_ path: AbsolutePath) -> Bool {
self.exists(path)
}
public func isWritable(_ path: AbsolutePath) -> Bool {
self.exists(path)
}
public func isExecutableFile(_ path: AbsolutePath) -> Bool {
// FIXME: Always return false until in-memory implementation
// gets permission semantics.
return false
}
/// Virtualized current working directory.
public var currentWorkingDirectory: AbsolutePath? {
return try? AbsolutePath(validating: "/")
}
public func changeCurrentWorkingDirectory(to path: AbsolutePath) throws {
throw FileSystemError(.unsupported, path)
}
public var homeDirectory: AbsolutePath {
get throws {
// FIXME: Maybe we should allow setting this when creating the fs.
return try AbsolutePath(validating: "/home/user")
}
}
public var cachesDirectory: AbsolutePath? {
return try? self.homeDirectory.appending(component: "caches")
}
public var tempDirectory: AbsolutePath {
get throws {
return try AbsolutePath(validating: "/tmp")
}
}
public func getDirectoryContents(_ path: AbsolutePath) throws -> [String] {
return try lock.withLock {
guard let node = try getNode(path) else {
throw FileSystemError(.noEntry, path)
}
guard case .directory(let contents) = node.contents else {
throw FileSystemError(.notDirectory, path)
}
// FIXME: Perhaps we should change the protocol to allow lazy behavior.
return [String](contents.entries.keys)
}
}
/// Not threadsafe.
private func _createDirectory(_ path: AbsolutePath, recursive: Bool) throws {
// Ignore if client passes root.
guard !path.isRoot else {
return
}
// Get the parent directory node.
let parentPath = path.parentDirectory
guard let parent = try getNode(parentPath) else {
// If the parent doesn't exist, and we are recursive, then attempt
// to create the parent and retry.
if recursive && path != parentPath {
// Attempt to create the parent.
try _createDirectory(parentPath, recursive: true)
// Re-attempt creation, non-recursively.
return try _createDirectory(path, recursive: false)
} else {
// Otherwise, we failed.
throw FileSystemError(.noEntry, parentPath)
}
}
// Check that the parent is a directory.
guard case .directory(let contents) = parent.contents else {
// The parent isn't a directory, this is an error.
throw FileSystemError(.notDirectory, parentPath)
}
// Check if the node already exists.
if let node = contents.entries[path.basename] {
// Verify it is a directory.
guard case .directory = node.contents else {
// The path itself isn't a directory, this is an error.
throw FileSystemError(.notDirectory, path)
}
// We are done.
return
}
// Otherwise, the node does not exist, create it.
contents.entries[path.basename] = Node(.directory(DirectoryContents()))
}
public func createDirectory(_ path: AbsolutePath, recursive: Bool) throws {
return try lock.withLock {
try _createDirectory(path, recursive: recursive)
}
}
public func createSymbolicLink(_ path: AbsolutePath, pointingAt destination: AbsolutePath, relative: Bool) throws {
return try lock.withLock {
// Create directory to destination parent.
guard let destinationParent = try getNode(path.parentDirectory) else {
throw FileSystemError(.noEntry, path.parentDirectory)
}
// Check that the parent is a directory.
guard case .directory(let contents) = destinationParent.contents else {
throw FileSystemError(.notDirectory, path.parentDirectory)
}
guard contents.entries[path.basename] == nil else {
throw FileSystemError(.alreadyExistsAtDestination, path)
}
let destination = relative ? destination.relative(to: path.parentDirectory).pathString : destination.pathString
contents.entries[path.basename] = Node(.symlink(destination))
}
}
public func readFileContents(_ path: AbsolutePath) throws -> ByteString {
return try lock.withLock {
// Get the node.
guard let node = try getNode(path) else {
throw FileSystemError(.noEntry, path)
}
// Check that the node is a file.
guard case .file(let contents) = node.contents else {
// The path is a directory, this is an error.
throw FileSystemError(.isDirectory, path)
}
// Return the file contents.
return contents
}
}
public func writeFileContents(_ path: AbsolutePath, bytes: ByteString) throws {
return try lock.withLock {
// It is an error if this is the root node.
let parentPath = path.parentDirectory
guard path != parentPath else {
throw FileSystemError(.isDirectory, path)
}
// Get the parent node.
guard let parent = try getNode(parentPath) else {
throw FileSystemError(.noEntry, parentPath)
}
// Check that the parent is a directory.
guard case .directory(let contents) = parent.contents else {
// The parent isn't a directory, this is an error.
throw FileSystemError(.notDirectory, parentPath)
}
// Check if the node exists.
if let node = contents.entries[path.basename] {
// Verify it is a file.
guard case .file = node.contents else {
// The path is a directory, this is an error.
throw FileSystemError(.isDirectory, path)
}
}
// Write the file.
contents.entries[path.basename] = Node(.file(bytes))
}
}
public func writeFileContents(_ path: AbsolutePath, bytes: ByteString, atomically: Bool) throws {
// In memory file system's writeFileContents is already atomic, so ignore the parameter here
// and just call the base implementation.
try writeFileContents(path, bytes: bytes)
}
public func removeFileTree(_ path: AbsolutePath) throws {
return lock.withLock {
// Ignore root and get the parent node's content if its a directory.
guard !path.isRoot,
let parent = try? getNode(path.parentDirectory),
case .directory(let contents) = parent.contents else {
return
}
// Set it to nil to release the contents.
contents.entries[path.basename] = nil
}
}
public func chmod(_ mode: FileMode, path: AbsolutePath, options: Set<FileMode.Option>) throws {
// FIXME: We don't have these semantics in InMemoryFileSystem.
}
/// Private implementation of core copying function.
/// Not threadsafe.
private func _copy(from sourcePath: AbsolutePath, to destinationPath: AbsolutePath) throws {
// Get the source node.
guard let source = try getNode(sourcePath) else {
throw FileSystemError(.noEntry, sourcePath)
}
// Create directory to destination parent.
guard let destinationParent = try getNode(destinationPath.parentDirectory) else {
throw FileSystemError(.noEntry, destinationPath.parentDirectory)
}
// Check that the parent is a directory.
guard case .directory(let contents) = destinationParent.contents else {
throw FileSystemError(.notDirectory, destinationPath.parentDirectory)
}
guard contents.entries[destinationPath.basename] == nil else {
throw FileSystemError(.alreadyExistsAtDestination, destinationPath)
}
contents.entries[destinationPath.basename] = source
}
public func copy(from sourcePath: AbsolutePath, to destinationPath: AbsolutePath) throws {
return try lock.withLock {
try _copy(from: sourcePath, to: destinationPath)
}
}
public func move(from sourcePath: AbsolutePath, to destinationPath: AbsolutePath) throws {
return try lock.withLock {
// Get the source parent node.
guard let sourceParent = try getNode(sourcePath.parentDirectory) else {
throw FileSystemError(.noEntry, sourcePath.parentDirectory)
}
// Check that the parent is a directory.
guard case .directory(let contents) = sourceParent.contents else {
throw FileSystemError(.notDirectory, sourcePath.parentDirectory)
}
try _copy(from: sourcePath, to: destinationPath)
contents.entries[sourcePath.basename] = nil
}
}
public func withLock<T>(on path: AbsolutePath, type: FileLock.LockType = .exclusive, _ body: () throws -> T) throws -> T {
let resolvedPath: AbsolutePath = try lock.withLock {
if case let .symlink(destination) = try getNode(path)?.contents {
return try AbsolutePath(validating: destination, relativeTo: path.parentDirectory)
} else {
return path
}
}
let fileQueue: DispatchQueue = lockFilesLock.withLock {
if let queueReference = lockFiles[resolvedPath], let queue = queueReference.reference {
return queue
} else {
let queue = DispatchQueue(label: "org.swift.swiftpm.in-memory-file-system.file-queue", attributes: .concurrent)
lockFiles[resolvedPath] = WeakReference(queue)
return queue
}
}
return try fileQueue.sync(flags: type == .exclusive ? .barrier : .init() , execute: body)
}
}
/// A rerooted view on an existing FileSystem.
///
/// This is a simple wrapper which creates a new FileSystem view into a subtree
/// of an existing filesystem. This is useful for passing to clients which only
/// need access to a subtree of the filesystem but should otherwise remain
/// oblivious to its concrete location.
///
/// NOTE: The rerooting done here is purely at the API level and does not
/// inherently prevent access outside the rerooted path (e.g., via symlinks). It
/// is designed for situations where a client is only interested in the contents
/// *visible* within a subpath and is agnostic to the actual location of those
/// contents.
public class RerootedFileSystemView: FileSystem {
/// The underlying file system.
private var underlyingFileSystem: FileSystem
/// The root path within the containing file system.
private let root: AbsolutePath
public init(_ underlyingFileSystem: FileSystem, rootedAt root: AbsolutePath) {
self.underlyingFileSystem = underlyingFileSystem
self.root = root
}
/// Adjust the input path for the underlying file system.
private func formUnderlyingPath(_ path: AbsolutePath) throws -> AbsolutePath {
if path == AbsolutePath.root {
return root
} else {
// FIXME: Optimize?
return try AbsolutePath(validating: String(path.pathString.dropFirst(1)), relativeTo: root)
}
}
// MARK: FileSystem Implementation
public func exists(_ path: AbsolutePath, followSymlink: Bool) -> Bool {
guard let underlying = try? formUnderlyingPath(path) else {
return false
}
return underlyingFileSystem.exists(underlying, followSymlink: followSymlink)
}
public func isDirectory(_ path: AbsolutePath) -> Bool {
guard let underlying = try? formUnderlyingPath(path) else {
return false
}
return underlyingFileSystem.isDirectory(underlying)
}
public func isFile(_ path: AbsolutePath) -> Bool {
guard let underlying = try? formUnderlyingPath(path) else {
return false
}
return underlyingFileSystem.isFile(underlying)
}
public func isSymlink(_ path: AbsolutePath) -> Bool {
guard let underlying = try? formUnderlyingPath(path) else {
return false
}
return underlyingFileSystem.isSymlink(underlying)
}
public func isReadable(_ path: AbsolutePath) -> Bool {
guard let underlying = try? formUnderlyingPath(path) else {
return false
}
return underlyingFileSystem.isReadable(underlying)
}
public func isWritable(_ path: AbsolutePath) -> Bool {
guard let underlying = try? formUnderlyingPath(path) else {
return false
}
return underlyingFileSystem.isWritable(underlying)
}
public func isExecutableFile(_ path: AbsolutePath) -> Bool {
guard let underlying = try? formUnderlyingPath(path) else {
return false
}
return underlyingFileSystem.isExecutableFile(underlying)
}
/// Virtualized current working directory.
public var currentWorkingDirectory: AbsolutePath? {
return try? AbsolutePath(validating: "/")
}
public func changeCurrentWorkingDirectory(to path: AbsolutePath) throws {
throw FileSystemError(.unsupported, path)
}
public var homeDirectory: AbsolutePath {
fatalError("homeDirectory on RerootedFileSystemView is not supported.")
}
public var cachesDirectory: AbsolutePath? {
fatalError("cachesDirectory on RerootedFileSystemView is not supported.")
}
public var tempDirectory: AbsolutePath {
fatalError("tempDirectory on RerootedFileSystemView is not supported.")
}
public func getDirectoryContents(_ path: AbsolutePath) throws -> [String] {
return try underlyingFileSystem.getDirectoryContents(formUnderlyingPath(path))
}
public func createDirectory(_ path: AbsolutePath, recursive: Bool) throws {
let path = try formUnderlyingPath(path)
return try underlyingFileSystem.createDirectory(path, recursive: recursive)
}
public func createSymbolicLink(_ path: AbsolutePath, pointingAt destination: AbsolutePath, relative: Bool) throws {
let path = try formUnderlyingPath(path)
let destination = try formUnderlyingPath(destination)
return try underlyingFileSystem.createSymbolicLink(path, pointingAt: destination, relative: relative)
}
public func readFileContents(_ path: AbsolutePath) throws -> ByteString {
return try underlyingFileSystem.readFileContents(formUnderlyingPath(path))
}
public func writeFileContents(_ path: AbsolutePath, bytes: ByteString) throws {
let path = try formUnderlyingPath(path)
return try underlyingFileSystem.writeFileContents(path, bytes: bytes)
}
public func removeFileTree(_ path: AbsolutePath) throws {
try underlyingFileSystem.removeFileTree(formUnderlyingPath(path))
}
public func chmod(_ mode: FileMode, path: AbsolutePath, options: Set<FileMode.Option>) throws {
try underlyingFileSystem.chmod(mode, path: path, options: options)
}
public func copy(from sourcePath: AbsolutePath, to destinationPath: AbsolutePath) throws {
try underlyingFileSystem.copy(from: formUnderlyingPath(sourcePath), to: formUnderlyingPath(sourcePath))
}
public func move(from sourcePath: AbsolutePath, to destinationPath: AbsolutePath) throws {
try underlyingFileSystem.move(from: formUnderlyingPath(sourcePath), to: formUnderlyingPath(sourcePath))
}
public func withLock<T>(on path: AbsolutePath, type: FileLock.LockType = .exclusive, _ body: () throws -> T) throws -> T {
return try underlyingFileSystem.withLock(on: formUnderlyingPath(path), type: type, body)
}
}
/// Public access to the local FS proxy.
public var localFileSystem: FileSystem = LocalFileSystem()
extension FileSystem {
/// Print the filesystem tree of the given path.
///
/// For debugging only.
public func dumpTree(at path: AbsolutePath = .root) {
print(".")
do {
try recurse(fs: self, path: path)
} catch {
print("\(error)")
}
}
/// Write bytes to the path if the given contents are different.
public func writeIfChanged(path: AbsolutePath, bytes: ByteString) throws {
try createDirectory(path.parentDirectory, recursive: true)
// Return if the contents are same.
if isFile(path), try readFileContents(path) == bytes {
return
}
try writeFileContents(path, bytes: bytes)
}
/// Helper method to recurse and print the tree.
private func recurse(fs: FileSystem, path: AbsolutePath, prefix: String = "") throws {
let contents = try fs.getDirectoryContents(path)
for (idx, entry) in contents.enumerated() {
let isLast = idx == contents.count - 1
let line = prefix + (isLast ? "└── " : "├── ") + entry
print(line)
let entryPath = path.appending(component: entry)
if fs.isDirectory(entryPath) {
let childPrefix = prefix + (isLast ? " " : "│ ")
try recurse(fs: fs, path: entryPath, prefix: String(childPrefix))
}
}
}
}
#if !os(Windows)
extension dirent {
/// Get the directory name.
///
/// This returns nil if the name is not valid UTF8.
public var name: String? {
var d_name = self.d_name
return withUnsafePointer(to: &d_name) {
String(validatingUTF8: UnsafeRawPointer($0).assumingMemoryBound(to: CChar.self))
}
}
}
#endif
| f8772b4b181ce7124a1dd89cece9d692 | 35.5 | 140 | 0.624411 | false | false | false | false |
tuttinator/nz-mps-swift | refs/heads/master | NZ MPs/MasterViewController.swift | mit | 1 | //
// MasterViewController.swift
// NZ MPs
//
// Created by Caleb Tutty on 12/08/14.
// Copyright (c) 2014 Supervillains and Associates. All rights reserved.
//
import UIKit
class MasterViewController: UITableViewController {
var objects = NSMutableArray()
override func awakeFromNib() {
super.awakeFromNib()
}
override func viewDidLoad() {
super.viewDidLoad()
requestItems()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func requestItems() {
Alamofire.request(.GET, "http://politicians.org.nz/parliament/current/mps.json")
.responseJSON { (request, response, JSON, error) in
println(JSON)
let json = JSON as NSArray
for item in json {
let mp = item as NSDictionary
let firstName = mp["first_name"] as String
let lastName = mp["last_name"] as String
let fullName = "\(firstName) \(lastName)"
self.insertNewObject(mp)
}
}
}
func insertNewObject(sender: AnyObject) {
if objects == nil {
objects = NSMutableArray()
}
objects.insertObject(sender, atIndex: objects.count)
let indexPath = NSIndexPath(forRow: objects.count - 1, inSection: 0)
self.tableView.insertRowsAtIndexPaths([indexPath], withRowAnimation: .Automatic)
}
// MARK: - Segues
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "showDetail" {
let indexPath = self.tableView.indexPathForSelectedRow()
let object = objects[indexPath.row] as NSDictionary
(segue.destinationViewController as DetailViewController).detailItem = object
}
}
// MARK: - Table View
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return objects.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let object = objects[indexPath.row] as NSDictionary
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as UITableViewCell
let firstName = object["first_name"] as String
let lastName = object["last_name"] as String
cell.textLabel.text = "\(firstName) \(lastName)"
return cell
}
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return false
}
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
objects.removeObjectAtIndex(indexPath.row)
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
} else if editingStyle == .Insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view.
}
}
}
| d4d2a70ae854a66f01febed8938ecea0 | 32.950495 | 157 | 0.642461 | false | false | false | false |
EvsenevDev/SmartReceiptsiOS | refs/heads/master | SmartReceipts/Reports/PDF/PDFImageView.swift | agpl-3.0 | 2 | //
// PDFImageView.swift
// SmartReceipts
//
// Created by Bogdan Evsenev on 01/12/2017.
// Copyright © 2017 Will Baumann. All rights reserved.
//
import Foundation
private let DEFAULT_COMPRESSION_QUALITY: CGFloat = 0.7
class PDFImageView: UIView {
@IBOutlet var titleLabel: UILabel!
@IBOutlet var imageView: UIImageView!
override func awakeFromNib() {
super.awakeFromNib()
titleLabel.font = PDFFontStyle.small.font
}
func fitImageView() {
let imageSize = imageView.image!.size
if imageSize.height > imageSize.width {
//do nothing for portrait images
return
}
let ratio = imageSize.height/imageSize.width
let height = imageView.frame.width * ratio
var imageFrame = imageView.frame
imageFrame.size.height = height
imageView.frame = imageFrame
}
func adjustImageSize() {
let image = imageView.image
let scaled = WBImageUtils.image(image!, scaledToFit: bounds.size)
if let scaledAndCompressed = WBImageUtils.compressImage(scaled, withRatio: DEFAULT_COMPRESSION_QUALITY) {
imageView.image = scaledAndCompressed
if !scaledAndCompressed.hasContent {
Logger.error("Actually no image content! Label: \(titleLabel.text ?? "")")
}
}
}
}
| 2664c68a393ab79c805260ebd7c74ab4 | 28.340426 | 113 | 0.634518 | false | false | false | false |
aikizoku/Library-iOS | refs/heads/master | LibrarySample/Pods/SwiftDate/Sources/SwiftDate/DateComponents+Extension.swift | mit | 2 | //
// SwiftDate, Full featured Swift date library for parsing, validating, manipulating, and formatting dates and timezones.
// Created by: Daniele Margutti
// Main contributors: Jeroen Houtzager
//
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
// MARK: - DateComponents Extension
/// Invert the value expressed by a `DateComponents` instance
///
/// - parameter dateComponents: instance to invert (ie. days=5 will become days=-5)
///
/// - returns: a new `DateComponents` with inverted values
public prefix func - (dateComponents: DateComponents) -> DateComponents {
var invertedCmps = DateComponents()
DateComponents.allComponents.forEach { component in
let value = dateComponents.value(for: component)
if value != nil && value != Int(NSDateComponentUndefined) {
invertedCmps.setValue(-value!, for: component)
}
}
return invertedCmps
}
/// Sum two date components; allows us to make `"5.days + 3.hours"` by producing a single `DateComponents`
/// where both `.days` and `.hours` are set.
///
/// - parameter lhs: first date component
/// - parameter rhs: second date component
///
/// - returns: a new `DateComponents`
public func + (lhs: DateComponents, rhs: DateComponents) -> DateComponents {
return lhs.add(components: rhs)
}
/// Same as su but with diff
///
/// - parameter lhs: first date component
/// - parameter rhs: second date component
///
/// - returns: a new `DateComponents`
public func - (lhs: DateComponents, rhs: DateComponents) -> DateComponents {
return lhs.add(components: rhs, multipler: -1)
}
public extension DateComponents {
/// A shortcut to produce a `DateInRegion` instance from an instance of `DateComponents`.
/// It's the same of `DateInRegion(components:)` init func but it may return nil (instead of throwing an exception)
/// if a valid date cannot be produced.
public var dateInRegion: DateInRegion? {
do {
return try DateInRegion(components: self)
} catch {
return nil
}
}
/// Internal function helper for + and - operators between two `DateComponents`
///
/// - parameter components: components
/// - parameter multipler: optional multipler for each component
///
/// - returns: a new `DateComponents` instance
internal func add(components: DateComponents, multipler: Int = 1) -> DateComponents {
let lhs = self
let rhs = components
var newCmps = DateComponents()
let flagSet = DateComponents.allComponents
flagSet.forEach { component in
let left = lhs.value(for: component)
let right = rhs.value(for: component)
if left != nil && right != nil && left != Int(NSDateComponentUndefined) && right != Int(NSDateComponentUndefined) {
let value = left! + (right! * multipler)
newCmps.setValue(value, for: component)
}
}
return newCmps
}
/// Transform a `DateComponents` instance to a dictionary where key is the `Calendar.Component` and value is the
/// value associated.
///
/// - returns: a new `[Calendar.Component : Int]` dict representing source `DateComponents` instance
internal func toComponentsDict() -> [Calendar.Component : Int] {
var list: [Calendar.Component : Int] = [:]
DateComponents.allComponents.forEach { component in
let value = self.value(for: component)
if value != nil && value != Int(NSDateComponentUndefined) {
list[component] = value!
}
}
return list
}
}
public extension DateComponents {
/// Create a new `Date` in absolute time from a specific date by adding self components
///
/// - parameter date: reference date
/// - parameter region: optional region to define the timezone and calendar. If not specified, Region.GMT() will be used instead.
///
/// - returns: a new `Date`
public func from(date: Date, in region: Region? = nil) -> Date? {
let srcRegion = region ?? Region.GMT()
return srcRegion.calendar.date(byAdding: self, to: date)
}
/// Create a new `DateInRegion` from another `DateInRegion` by adding self components
/// Returned object has the same `Region` of the source.
///
/// - parameter dateInRegion: reference `DateInRegion`
///
/// - returns: a new `DateInRegion`
public func from(dateInRegion: DateInRegion) -> DateInRegion? {
guard let absDate = dateInRegion.region.calendar.date(byAdding: self, to: dateInRegion.absoluteDate) else {
return nil
}
let newDateInRegion = DateInRegion(absoluteDate: absDate, in: dateInRegion.region)
return newDateInRegion
}
/// Create a new `Date` in absolute time from a specific date by subtracting self components
///
/// - parameter date: reference date
/// - parameter region: optional region to define the timezone and calendar. If not specific, Region.GTM() will be used instead
///
/// - returns: a new `Date`
public func ago(from date: Date, in region: Region? = nil) -> Date? {
let srcRegion = region ?? Region.GMT()
return srcRegion.calendar.date(byAdding: -self, to: date)
}
/// Create a new `DateInRegion` from another `DateInRegion` by subtracting self components
/// Returned object has the same `Region` of the source.
///
/// - parameter dateInRegion: reference `DateInRegion`
///
/// - returns: a new `DateInRegion`
public func ago(fromDateInRegion date: DateInRegion) -> DateInRegion? {
guard let absDate = date.region.calendar.date(byAdding: -self, to: date.absoluteDate) else {
return nil
}
let newDateInRegion = DateInRegion(absoluteDate: absDate, in: date.region)
return newDateInRegion
}
/// Create a new `Date` in absolute time from current date by adding self components
///
/// - parameter region: optional region to define the timezone and calendar. If not specified, Region.GMT() will be used instead.
///
/// - returns: a new `Date`
public func fromNow(in region: Region? = nil) -> Date? {
return self.from(date: Date(), in: region)
}
/// Create a new `DateInRegion` from current by subtracting self components
/// Returned object has the same `Region` of the source.
///
/// - parameter dateInRegion: reference `DateInRegion`
///
/// - returns: a new `DateInRegion`
public func ago(in region: Region? = nil) -> Date? {
return self.ago(from: Date(), in: region)
}
}
// MARK: - DateComponents Private Extension
extension DateComponents {
/// Define a list of all calendar components as a set
internal static let allComponentsSet: Set<Calendar.Component> = [.nanosecond, .second, .minute, .hour,
.day, .month, .year, .yearForWeekOfYear, .weekOfYear, .weekday, .quarter, .weekdayOrdinal,
.weekOfMonth]
/// Define a list of all calendar components as array
internal static let allComponents: [Calendar.Component] = [.nanosecond, .second, .minute, .hour,
.day, .month, .year, .yearForWeekOfYear, .weekOfYear, .weekday, .quarter, .weekdayOrdinal,
.weekOfMonth]
}
| 5f29ecc2ca86699d699e55999b4ef1ba | 36.630841 | 156 | 0.692164 | false | false | false | false |
KrishMunot/swift | refs/heads/master | validation-test/stdlib/WatchKit.swift | apache-2.0 | 5 | // RUN: %target-run-simple-swift
// REQUIRES: executable_test
// REQUIRES: objc_interop
// REQUIRES: OS=watchos
import StdlibUnittest
import WatchKit
var WatchKitTests = TestSuite("WatchKit")
if #available(iOS 8.2, *) {
// This is a very weak test, but we can't do better without spawning a GUI app.
WatchKitTests.test("WKInterfaceController/reloadRootControllers(_:)") {
WKInterfaceController.reloadRootControllers([])
}
// This is a very weak test, but we can't do better without spawning a GUI app.
WatchKitTests.test("WKInterfaceController/presentController(_:)") {
let curried = WKInterfaceController.presentController(_:)
typealias ExpectedType =
(WKInterfaceController) -> ([(name: String, context: AnyObject)]) -> Void
let checkType: ExpectedType = curried
_blackHole(checkType)
// FIXME: can't write the following line: rdar://20985062
// expectType(ExpectedType.self, &curried)
let curried2 = WKInterfaceController.presentController as ExpectedType
}
} // #available(iOS 8.2, *)
runAllTests()
| 8f112d7d39ec6528cbb391dd9620608e | 26.972973 | 79 | 0.742029 | false | true | false | false |
wenghengcong/Coderpursue | refs/heads/master | BeeFun/BeeFun/SystemManager/Network/SVGProcessor.swift | mit | 1 | //
// SVGProcessor.swift
// BeeFun
//
// Created by WengHengcong on 04/07/2017.
// Copyright © 2017 JungleSong. All rights reserved.
//
import UIKit
import Kingfisher
/*
struct SVGProcessor: ImageProcessor {
let imgSize: CGSize?
init(size: CGSize? = CGSize(width:250, height:250)) {
imgSize = size
}
// `identifier` should be the same for processors with same properties/functionality
// It will be used when storing and retrieving the image to/from cache.
let identifier = "com.junglesong.beefun"
// Convert input data/image to target image and return it.
func process(item: ImageProcessItem, options: KingfisherOptionsInfo) -> Image? {
switch item {
case .image(let image):
//already an image
return image
case .data(let data):
return generateSVGImage(data: data, size: imgSize) ?? DefaultImageProcessor().process(item: item, options: options)
}
}
}
struct SVGCacheSerializer: CacheSerializer {
func data(with image: Image, original: Data?) -> Data? {
return original
}
func image(with data: Data, options: KingfisherOptionsInfo?) -> Image? {
return generateSVGImage(data: data) ?? image(with: data, options: options)
}
}
func generateSVGImage(svgXml: String, size: CGSize? = CGSize(width:250, height:250)) -> UIImage?{
let frame = CGRect(x: 0, y: 0, width: size!.width, height: size!.height)
if let _ = svgXml.base64Decoded {
let svgLayer = SVGLayer(svgSource: svgXml)
svgLayer.frame = frame
return snapshotImage(for: svgLayer)
}
return nil
}
func generateSVGImage(data: Data, size: CGSize? = CGSize(width:250, height:250)) -> UIImage?{
let frame = CGRect(x: 0, y: 0, width: size!.width, height: size!.height)
if let svgString = String(data: data, encoding: .utf8){
let svgLayer = SVGLayer(svgSource: svgString)
svgLayer.frame = frame
return snapshotImage(for: svgLayer)
}
return nil
}
func snapshotImage(for layer: CALayer) -> UIImage? {
UIGraphicsBeginImageContextWithOptions(layer.bounds.size, false, UIScreen.main.scale)
guard let context = UIGraphicsGetCurrentContext() else { return nil }
layer.render(in: context)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
*/
| 5ba203ba2c4139f55023a96a15c4323c | 31.093333 | 127 | 0.665143 | false | false | false | false |
Roommate-App/roomy | refs/heads/master | InkChat/Pods/IBAnimatable/IBAnimatable/BorderType.swift | apache-2.0 | 3 | //
// BorderType.swift
// IBAnimatable
//
// Created by Tom Baranes on 13/01/2017.
// Copyright © 2017 IBAnimatable. All rights reserved.
//
import Foundation
public enum BorderType: IBEnum {
case solid
case dash(dashLength: Int, spaceLength: Int)
case none
}
extension BorderType {
public init(string: String?) {
guard let string = string else {
self = .none
return
}
let (name, params) = AnimationType.extractNameAndParams(from: string)
switch name {
case "solid":
self = .solid
case "dash":
self = .dash(dashLength: params[safe: 0]?.toInt() ?? 1, spaceLength: params[safe: 1]?.toInt() ?? 1)
default:
self = .none
}
}
}
extension BorderType: Equatable {
}
public func == (lhs: BorderType, rhs: BorderType) -> Bool {
switch (lhs, rhs) {
case (.solid, .solid):
return true
case (.dash, .dash):
return true
default:
return false
}
}
| fb2c090aa23fbf3880f713091e2eeb4e | 18.122449 | 105 | 0.624333 | false | false | false | false |
tlax/looper | refs/heads/master | looper/View/Camera/Main/VCameraCellControlsButton.swift | mit | 1 | import UIKit
class VCameraCellControlsButton:UIButton
{
private let kBorderWidth:CGFloat = 1
init(image:UIImage, border:Bool)
{
super.init(frame:CGRect.zero)
backgroundColor = UIColor.genericLight
translatesAutoresizingMaskIntoConstraints = false
setImage(
image.withRenderingMode(UIImageRenderingMode.alwaysOriginal),
for:UIControlState.normal)
setImage(
image.withRenderingMode(UIImageRenderingMode.alwaysTemplate),
for:UIControlState.highlighted)
imageView!.tintColor = UIColor(white:0, alpha:0.1)
imageView!.clipsToBounds = true
imageView!.contentMode = UIViewContentMode.center
if border
{
let viewBorder:VBorder = VBorder(color:UIColor.black)
addSubview(viewBorder)
NSLayoutConstraint.equalsVertical(
view:viewBorder,
toView:self)
NSLayoutConstraint.leftToLeft(
view:viewBorder,
toView:self)
NSLayoutConstraint.width(
view:viewBorder,
constant:kBorderWidth)
}
}
required init?(coder:NSCoder)
{
return nil
}
}
| b60be9847bcdb64b98566afd3df38948 | 28.674419 | 73 | 0.59953 | false | false | false | false |
authme-org/authme | refs/heads/master | authme-iphone/AuthMe/Src/Controllers/ConfigurationMainMenuController.swift | apache-2.0 | 1 | /*
*
* Copyright 2015 Berin Lautenbach
*
* 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.
*
*/
//
// ConfigurationMainMenuController.swift
// AuthMe
//
// Created by Berin Lautenbach on 6/09/2014.
// Copyright (c) 2014 Berin Lautenbach. All rights reserved.
//
import UIKit
import Foundation
class ConfigurationMainMenuController: UITableViewController {
var logger = Log()
var firstAppearance = true
let configTemplatePlist = "ConfigurationSetup"
var currentIndexPath: IndexPath? = nil
var detailMenuController: ConfigurationDetailMenuController? = nil
var storedEditFields: NSMutableDictionary? = nil
// MARK: Setup and teardown
override func awakeFromNib() {
super.awakeFromNib()
if UIDevice.current.userInterfaceIdiom == .pad {
self.clearsSelectionOnViewWillAppear = false
self.preferredContentSize = CGSize(width: 320.0, height: 600.0)
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.navigationItem.title = "Config"
if let split = self.splitViewController {
let controllers = split.viewControllers
self.detailMenuController = (controllers[controllers.count-1] as! UINavigationController).topViewController as? ConfigurationDetailMenuController
}
self.tableView.estimatedRowHeight = 44;
self.tableView.rowHeight = UITableViewAutomaticDimension;
}
override func viewDidAppear(_ animated: Bool) {
if firstAppearance {
firstAppearance = false
let appConfiguration = AppConfiguration.getInstance()
if appConfiguration.getConfigItem("serviceUsername") as! String? == nil ||
appConfiguration.getConfigItem("serviceUsername") as! String? == "" {
logger.log(.debug, message: "Loading for no username")
self.tableView.selectRow(at: IndexPath(item: 0, section: 0), animated: true, scrollPosition: UITableViewScrollPosition.bottom)
self.performSegue(withIdentifier: "showConfigDetail", sender: self)
//self.tableView(self.tableView, selectRowAtIndexPath: NSIndexPath(forItem: 0, inSection: 0))
// Tell the user they need to take some action
let alert = UIAlertController(title: "Credentials Required",
message: "Please enter credentials or create a new account for the AuthMe service", preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil))
self.present(alert, animated: true, completion: nil)
}
}
}
override func viewWillAppear(_ animated: Bool) {
// If we were swapped out - reload
if let visibleCells = self.tableView.indexPathsForVisibleRows {
self.tableView.reloadRows(at: visibleCells, with: UITableViewRowAnimation.automatic)
}
if self.splitViewController != nil {
if (currentIndexPath != nil) && !(self.splitViewController!.isCollapsed) {
storedEditFields = detailMenuController?.editFields
self.tableView.selectRow(at: currentIndexPath, animated: false, scrollPosition: UITableViewScrollPosition.none)
self.performSegue(withIdentifier: "showConfigDetail", sender: self)
storedEditFields = nil
}
}
}
override var shouldAutorotate : Bool {
return true
}
// MARK: - Segues
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "showConfigDetail" && self.splitViewController != nil {
if let indexPath = self.tableView.indexPathForSelectedRow {
currentIndexPath = indexPath
//let object = self.feedUpdateController.feedAtIndexPath(indexPath)
let controller = (segue.destination as! UINavigationController).topViewController as! ConfigurationDetailMenuController
var _config: NSDictionary? = nil
if let dict = configTemplate.object(at: indexPath.section) as? NSDictionary {
if let array = dict.object(forKey: "ConfigurationItems") as? NSArray {
_config = array.object(at: indexPath.row) as? NSDictionary
}
}
let newConfigArray = _config?.object(forKey: "SubMenu") as? NSArray
controller.configTemplate = newConfigArray
detailMenuController = controller
//controller.detailItem = object
//controller.masterViewController = self
//controller.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "test", style: UIBarButtonItemStyle.Plain, target: self.splitViewController!.displayModeButtonItem().target, action: self.splitViewController!.displayModeButtonItem().action)// self.splitViewController!.displayModeButtonItem()
if let subTitle = _config?.object(forKey: "DisplayNameShort") as? NSString {
controller.navigationItem.title = subTitle as String
}
else {
controller.navigationItem.title = "Configuration"
}
controller.editFields = storedEditFields
}
}
}
// MARK: Data Source
override func numberOfSections(in tableView: UITableView) -> Int {
// Return the number of sections.
return configTemplate.count
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if let dict = configTemplate.object(at: section) as? NSDictionary {
if let array = dict.object(forKey: "ConfigurationItems") as? NSArray {
return array.count
}
}
return 0
}
override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String {
if let dict = configTemplate.object(at: section) as? NSDictionary {
if let str = dict.object(forKey: "GroupName") as? String {
return str
}
}
return "Unknown Group"
}
override func tableView(_ tableView: UITableView, titleForFooterInSection section: Int) -> String {
if let dict = configTemplate.object(at: section) as? NSDictionary {
if let str = dict.object(forKey: "GroupDescription") as? String {
return str
}
}
return ""
}
/*
override func tableView(tableView: UITableView!, heightForRowAtIndexPath indexPath: NSIndexPath!) -> CGFloat {
return 44.0
}
*/
// MARK: Cell Configurer
// Customize the appearance of table view cells.
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
logger.log(.fine, message: "At start of cellForRowAtIndexPath")
/* Load the specific configuration section for where we are */
var _config: NSDictionary? = nil
if let dict = configTemplate.object(at: indexPath.section) as? NSDictionary {
if let array = dict.object(forKey: "ConfigurationItems") as? NSArray {
_config = array.object(at: indexPath.row) as? NSDictionary
}
}
if _config == nil {
logger.log(.error, message: "Error loading configTemplate")
return UITableViewCell()
}
let config = _config! as NSDictionary
/* At the base menu all cells are either for sub menus or selectors */
let LEFT_LABEL_TAG = 1001
let cellIdentifier = "MainMenuSelectorCell"
var leftLabel: UILabel? = nil
let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier) as UITableViewCell?
leftLabel = cell?.viewWithTag(LEFT_LABEL_TAG) as? UILabel
if let str = config.object(forKey: "DisplayNameShort") as? String {
leftLabel?.text = str
}
else {
leftLabel?.text = ""
}
// This doesn't work in IOS7 and above
//cell?.selectionStyle = UITableViewCellSelectionStyle.Blue
// From http://stackoverflow.com/questions/18794080/ios7-uitableviewcell-selectionstyle-wont-go-back-to-blue
let bgColourView = UIView()
bgColourView.backgroundColor = UIColor(red: (76.0/255), green: (161.0/255.0), blue: 1.0, alpha: 1.0)
bgColourView.layer.masksToBounds = true;
cell?.selectedBackgroundView = bgColourView;
return cell!
}
// MARK: Load the configuration template
var configTemplate: NSArray {
if _configTemplate != nil {
return _configTemplate!
}
if let path = Bundle.main.path(forResource: configTemplatePlist, ofType: "plist") {
_configTemplate = NSArray(contentsOfFile: path)
}
else {
_configTemplate = NSArray()
}
/* If we are in release mode, remove anything debug related */
#if DEBUG
logger.log(.debug, message: "Loading DEBUG Configuration Items")
#else
let newConfigTemplate = NSMutableArray()
for item in _configTemplate as! [NSDictionary] {
if let confElementIsDebug = item.value(forKey: "DebugOnly") as? Bool {
if !confElementIsDebug {
newConfigTemplate.add(item)
}
}
else {
newConfigTemplate.add(item)
}
}
_configTemplate = newConfigTemplate
#endif
return _configTemplate!
}
var _configTemplate: NSArray? = nil
}
| e2b38400b75d6e3307b0f7d7d2aafe77 | 36.498294 | 313 | 0.598617 | false | true | false | false |
devpunk/velvet_room | refs/heads/master | Source/View/Connect/VConnectWalk.swift | mit | 1 | import UIKit
final class VConnectWalk:VCollection<
ArchConnect,
VConnectWalkCell>
{
private weak var viewPage:UIPageControl!
private var cellSize:CGSize?
private let kPageBottom:CGFloat = -170
required init(controller:CConnect)
{
super.init(controller:controller)
collectionView.isPagingEnabled = true
collectionView.alwaysBounceHorizontal = true
if let flow:VCollectionFlow = collectionView.collectionViewLayout as? VCollectionFlow
{
flow.scrollDirection = UICollectionViewScrollDirection.horizontal
}
factoryPages()
}
required init?(coder:NSCoder)
{
return nil
}
override func scrollViewDidEndDecelerating(
_ scrollView:UIScrollView)
{
updatePage()
}
override func collectionView(
_ collectionView:UICollectionView,
layout collectionViewLayout:UICollectionViewLayout,
sizeForItemAt indexPath:IndexPath) -> CGSize
{
guard
let cellSize:CGSize = self.cellSize
else
{
let width:CGFloat = collectionView.bounds.width
let height:CGFloat = collectionView.bounds.height
let cellSize:CGSize = CGSize(
width:width,
height:height)
self.cellSize = cellSize
return cellSize
}
return cellSize
}
override func numberOfSections(
in collectionView:UICollectionView) -> Int
{
return 1
}
override func collectionView(
_ collectionView:UICollectionView,
numberOfItemsInSection section:Int) -> Int
{
let count:Int = controller.model.itemsWalk.count
return count
}
override func collectionView(
_ collectionView:UICollectionView,
cellForItemAt indexPath:IndexPath) -> UICollectionViewCell
{
let item:MConnectWalkProtocol = modelAtIndex(
index:indexPath)
let cell:VConnectWalkCell = cellAtIndex(
indexPath:indexPath)
cell.config(model:item)
return cell
}
override func collectionView(
_ collectionView:UICollectionView,
shouldSelectItemAt indexPath:IndexPath) -> Bool
{
return false
}
override func collectionView(
_ collectionView:UICollectionView,
shouldHighlightItemAt indexPath:IndexPath) -> Bool
{
return false
}
//MARK: private
private func factoryPages()
{
let pages:Int = controller.model.itemsWalk.count
let viewPage:UIPageControl = UIPageControl()
viewPage.isUserInteractionEnabled = false
viewPage.translatesAutoresizingMaskIntoConstraints = false
viewPage.numberOfPages = pages
viewPage.currentPageIndicatorTintColor = UIColor(
red:1,
green:0.23529411764705888,
blue:0.3686274509803924,
alpha:1)
viewPage.pageIndicatorTintColor = UIColor.colourBackgroundGray
self.viewPage = viewPage
if pages > 0
{
viewPage.currentPage = 0
}
addSubview(viewPage)
NSLayoutConstraint.bottomToBottom(
view:viewPage,
toView:self,
constant:kPageBottom)
NSLayoutConstraint.equalsHorizontal(
view:viewPage,
toView:self)
}
private func modelAtIndex(index:IndexPath) -> MConnectWalkProtocol
{
let item:MConnectWalkProtocol = controller.model.itemsWalk[
index.item]
return item
}
private func updatePage()
{
let offset:CGFloat = collectionView.contentOffset.x
let width_2:CGFloat = bounds.midX
let height_2:CGFloat = bounds.midY
let midPoint:CGPoint = CGPoint(
x:width_2 + offset,
y:height_2)
guard
let index:IndexPath = collectionView.indexPathForItem(
at:midPoint)
else
{
return
}
viewPage.currentPage = index.item
}
}
| 7c24631337e6eb5267a8380d17bdae32 | 25.187879 | 93 | 0.587364 | false | false | false | false |
jordandobson/Frameless | refs/heads/master | Frameless/AppDelegate.swift | mit | 1 | //
// AppDelegate.swift
// Unframed
//
// Created by Jay Stakelon on 10/23/14.
// Copyright (c) 2014 Jay Stakelon. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
self.window = UIWindow(frame: UIScreen.mainScreen().bounds)
self.window!.backgroundColor = UIColor.whiteColor()
setUserSettingsDefaults()
if let lastIntro: AnyObject = NSUserDefaults.standardUserDefaults().objectForKey(AppDefaultKeys.IntroVersionSeen.rawValue) {
setupAppViewController(false)
} else {
self.window!.rootViewController = createIntroViewController()
self.window!.makeKeyAndVisible()
}
UIButton.appearance().tintColor = UIColorFromHex(0x9178E2)
return true
}
func setUserSettingsDefaults() {
NSUserDefaults.standardUserDefaults().registerDefaults([
AppDefaultKeys.ShakeGesture.rawValue: true,
AppDefaultKeys.PanFromBottomGesture.rawValue: true,
AppDefaultKeys.TripleTapGesture.rawValue: true,
AppDefaultKeys.ForwardBackGesture.rawValue: true,
AppDefaultKeys.FramerBonjour.rawValue: true,
AppDefaultKeys.KeepAwake.rawValue: true,
AppDefaultKeys.SearchEngine.rawValue: SearchEngineType.DuckDuckGo.rawValue
])
let isIdleTimer = NSUserDefaults.standardUserDefaults().objectForKey(AppDefaultKeys.KeepAwake.rawValue) as? Bool
UIApplication.sharedApplication().idleTimerDisabled = isIdleTimer!
}
func createIntroViewController() -> OnboardingViewController {
let page01: OnboardingContentViewController = OnboardingContentViewController(title: nil, body: "Frameless is a chromeless,\nfull-screen web browser. Load a\npage and everything else hides", image: UIImage(named: "introimage01"), buttonText: nil) {
}
page01.iconWidth = 158
page01.iconHeight = 258.5
let page02: OnboardingContentViewController = OnboardingContentViewController(title: nil, body: "Swipe up, tap with three fingers\nor shake the device to show\nthe browser bar and keyboard", image: UIImage(named: "introimage02"), buttonText: nil) {
}
page02.iconWidth = 158
page02.iconHeight = 258.5
let page03: OnboardingContentViewController = OnboardingContentViewController(title: nil, body: "Swipe left and right to go\nforward and back in your\nsession history", image: UIImage(named: "introimage03"), buttonText: nil) {
self.introCompletion()
}
page03.iconWidth = 158
page03.iconHeight = 258.5
let page04: OnboardingContentViewController = OnboardingContentViewController(title: nil, body: "And disable any of the gestures\nif they get in your way", image: UIImage(named: "introimage04"), buttonText: "LET'S GO!") {
self.introCompletion()
}
page04.iconWidth = 158
page04.iconHeight = 258.5
let bgImage = UIImage.withColor(UIColorFromHex(0x9178E2))
let onboardingViewController = PortraitOnboardingViewController(
backgroundImage: bgImage,
contents: [page01, page02, page03, page04])
onboardingViewController.fontName = "ClearSans"
onboardingViewController.bodyFontSize = 16
onboardingViewController.titleFontName = "ClearSans-Bold"
onboardingViewController.titleFontSize = 22
onboardingViewController.buttonFontName = "ClearSans-Bold"
onboardingViewController.buttonFontSize = 20
onboardingViewController.topPadding = 60+(self.window!.frame.height/12)
onboardingViewController.underTitlePadding = 8
onboardingViewController.shouldMaskBackground = false
return onboardingViewController
}
func introCompletion() {
NSUserDefaults.standardUserDefaults().setValue(1, forKey: AppDefaultKeys.IntroVersionSeen.rawValue)
setupAppViewController(true)
}
func setupAppViewController(animated : Bool) {
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let appViewController = storyboard.instantiateViewControllerWithIdentifier("mainViewController") as! UIViewController
if animated {
UIView.transitionWithView(self.window!, duration: 0.5, options:UIViewAnimationOptions.TransitionFlipFromBottom, animations: { () -> Void in
self.window!.rootViewController = appViewController
}, completion:nil)
}
else {
self.window?.rootViewController = appViewController
}
self.window!.makeKeyAndVisible()
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
}
}
| 3820dfa89b0a235ccad5735400f980d8 | 47.702899 | 285 | 0.705252 | false | false | false | false |
eCrowdMedia/MooApi | refs/heads/develop | Sources/model/StoreModel/StoreBannerSet.swift | mit | 1 | //
// StoreBannerItem.swift
// MooApi
//
// Created by Apple on 2017/11/21.
// Copyright © 2017年 ecrowdmedia.com. All rights reserved.
//
import Foundation
public struct StoreBannerSet: Codable, StoreDataProtocal {
public enum CodingKeys: String, CodingKey {
case title = "title"
case image = "image"
case startTime = "start_time"
case endTime = "end_time"
case page = "page"
}
public var title: String
public var image: String
public var startTime: String
public var endTime: String
public var page: StoreDataBasePageItem
}
| e667196514f379a7f1f2da46383d35ee | 20.222222 | 59 | 0.691099 | false | false | false | false |
CodeEagle/RainbowTransition | refs/heads/master | DemoForRainbow/ViewController.swift | mit | 1 | //
// ViewController.swift
// SD
//
// Created by LawLincoln on 2016/11/1.
// Copyright © 2016年 LawLincoln. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let v = UIView(frame: UIScreen.main.bounds)
v.backgroundColor = .white
view.addSubview(v)
navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .search, target: self, action: #selector(ViewController.p))
navBarBgAlpha = 0
// 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.
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
// navigationController?.disableDrag(in: type(of: self))
}
@IBAction func p() {
let vc = TBViewController(nibName: nil, bundle: nil)
show(vc, sender: nil)
}
}
class TBViewController: UIViewController {
private lazy var tableView = UITableView(frame: UIScreen.main.bounds, style: .plain)
private lazy var collectionview: UICollectionView = {
let layout = UICollectionViewFlowLayout()
layout.scrollDirection = .horizontal
layout.itemSize = CGSize(width: UIScreen.main.bounds.width, height: 300)
let cv = UICollectionView(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 300), collectionViewLayout: layout)
cv.delegate = self
cv.dataSource = self
cv.alwaysBounceHorizontal = true
cv.isPagingEnabled = true
cv.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "cell")
return cv
}()
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(tableView)
// navigationController?.navigationBar.shadow(enable: true)
view.backgroundColor = .white
automaticallyAdjustsScrollViewInsets = false
collectionview.backgroundColor = .green
tableView.tableHeaderView = collectionview
tableView.delegate = self
tableView.dataSource = self
tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
navBarTintColor = .blue
navBarBgAlpha = 0
navBarBgShadow = true
navBarBGColor = .green
transparent(with: tableView)
// fd_interactivePopDisabled = true
// Do any additional setup after loading the view, typically from a nib.
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
// navigationController?.disableDrag(in: TBViewController.self)
}
override var preferredStatusBarStyle: UIStatusBarStyle {
return navBarBgAlpha > 0.6 ? .default : .lightContent
}
}
extension TBViewController: UICollectionViewDelegate, UICollectionViewDataSource {
func numberOfSections(in _: UICollectionView) -> Int {
return 1
}
func collectionView(_: UICollectionView, numberOfItemsInSection _: Int) -> Int {
return 10
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath)
cell.backgroundColor = UIColor.orange
return cell
}
}
extension TBViewController: UITableViewDataSource, UITableViewDelegate {
func numberOfSections(in _: UITableView) -> Int {
return 1
}
func tableView(_: UITableView, numberOfRowsInSection _: Int) -> Int {
return 30
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell")
cell?.textLabel?.text = "\(indexPath.row)"
return cell!
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
let vc = DTBViewController(nibName: nil, bundle: nil)
show(vc, sender: nil)
}
func tableView(_: UITableView, canEditRowAt _: IndexPath) -> Bool {
return true
}
func tableView(_: UITableView, editingStyleForRowAt _: IndexPath) -> UITableViewCellEditingStyle {
return .delete
}
func tableView(_: UITableView, commit _: UITableViewCellEditingStyle, forRowAt _: IndexPath) {
}
}
class DTBViewController: UIViewController {
private lazy var tableView = UITableView(frame: UIScreen.main.bounds, style: .plain)
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(tableView)
view.backgroundColor = .white
automaticallyAdjustsScrollViewInsets = false
let v = UIView(frame: CGRect(x: 0, y: 0, width: view.bounds.width, height: 300))
v.backgroundColor = .blue
tableView.tableHeaderView = v
tableView.delegate = self
tableView.dataSource = self
tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
navBarBgAlpha = 0
navBarTintColor = .orange
navBarBgShadow = false
transparent(with: tableView)
// fd_interactivePopDisabled = true
// Do any additional setup after loading the view, typically from a nib.
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
}
override var preferredStatusBarStyle: UIStatusBarStyle {
return .lightContent
}
}
extension DTBViewController: UITableViewDataSource, UITableViewDelegate {
func numberOfSections(in _: UITableView) -> Int {
return 1
}
func tableView(_: UITableView, numberOfRowsInSection _: Int) -> Int {
return 30
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell")
cell?.textLabel?.text = "\(indexPath.row)"
return cell!
}
}
class TTTViewController: UIViewController {
weak var lastVC: VC?
private lazy var _pageVC: UIPageViewController = {
let vc = UIPageViewController(transitionStyle: .scroll, navigationOrientation: .horizontal, options: nil)
vc.dataSource = self
vc.delegate = self
return vc
}()
override func viewDidLoad() {
super.viewDidLoad()
let vc = VC(index: 999)
view.backgroundColor = UIColor.orange
view.addSubview(_pageVC.view)
_pageVC.setViewControllers([vc], direction: .forward, animated: false, completion: nil)
navigationController?.enableRainbowTransition()
navBarBgAlpha = 0
lastVC = vc
transparent(with: vc._scrollView, force: true)
// 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.
}
}
extension TTTViewController: UIPageViewControllerDataSource, UIPageViewControllerDelegate {
func pageViewController(_: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? {
guard let idx = (viewController as? VC)?.idx else { return nil }
return VC(index: idx - 1)
}
func pageViewController(_: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? {
guard let idx = (viewController as? VC)?.idx else { return nil }
return VC(index: idx + 1)
}
func pageViewController(_ pageViewController: UIPageViewController, didFinishAnimating _: Bool, previousViewControllers _: [UIViewController], transitionCompleted _: Bool) {
if let vc = pageViewController.viewControllers?.first as? VC {
transparent(with: vc._scrollView, force: true, setAlphaForFirstTime: false)
let al = rt_alpha(for: vc._scrollView)
navigationController?.setNeedsNavigationBackground(alpha: al, animated: true)
setNeedsStatusBarAppearanceUpdate()
lastVC = vc
}
}
}
final class VC: UIViewController {
var idx: Int = 0
deinit {
print("deinit \(idx)")
}
lazy var _scrollView: UIScrollView = {
let sc = UIScrollView()
sc.frame = UIScreen.main.bounds
return sc
}()
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
}
required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) }
convenience init(index: Int) {
self.init(nibName: nil, bundle: nil)
print("init \(index)")
idx = index
if idx % 2 == 0 {
view.backgroundColor = UIColor.gray
} else {
view.backgroundColor = UIColor.orange
}
_scrollView.tag = idx
}
override func viewDidLoad() {
super.viewDidLoad()
_scrollView.contentSize = CGSize(width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height * 4)
view.addSubview(_scrollView)
}
}
| d2e0359fe718939b3104297a166d904e | 33.04 | 177 | 0.666916 | false | false | false | false |
xdliu002/TAC_communication | refs/heads/master | Swift3/Structures.playground/Contents.swift | mit | 1 | //: Playground - noun: a place where people can play
import Foundation
struct Coordinate {
var latitude: Double
var longitude: Double
var location: Double {
get {
return latitude + longitude
}
set {
print(newValue)
}
}
init(latitude: Double, longitude: Double) {
self.latitude = latitude
self.longitude = longitude
}
init () {
latitude = 0
longitude = 0
}
init?(lat: Double, long: Double) {
guard lat > 0 && long > 0 else {
return nil
}
guard lat > 180 || long > 90 else {
return nil
}
// The simple expression
guard
lat > 0 && long > 0,
lat > 180 || long > 90 else {
return nil
}
self.latitude = lat
self.longitude = long
}
func toString() -> String {
return "Latitude:\(latitude), Longitude:\(longitude)"
}
}
var test = Coordinate()
test.location = 1
test.location
let myLocation = Coordinate(latitude: 39.0, longitude: 119.1)
print(myLocation.toString())
let errorLocation = Coordinate(lat: -10, long: 10)
print("\(errorLocation)")
class Student {
var name: String
var age: Int
init(name: String, age: Int) {
self.name = name
self.age = age
}
func growUp() {
self.age += 1
}
func getAge() -> Int {
return self.age
}
var currentAge: Int {
get {
return self.age
}
set {
age = newValue
}
}
}
let xiaoming = Student(name: "Xiao Ming", age: 12)
xiaoming.growUp()
print(xiaoming.getAge())
print(xiaoming.currentAge)
xiaoming.currentAge = 10
xiaoming.age
var coordi = Coordinate()
coordi.latitude = 10.0
| c590ca14eb3f81ae75efb7ecffaefbdf | 17.821782 | 61 | 0.516044 | false | false | false | false |
geeksweep/stormviewer | refs/heads/master | StormViewer/MainViewController/ViewModels/ViewControllerViewModel.swift | mit | 1 | //
// ViewControllerViewModel.swift
// StormViewer
//
// Created by Chad Saxon on 3/8/17.
// Copyright © 2017 Chad Saxon. All rights reserved.
//
import UIKit
class ViewControllerViewModel: NSObject {
private var vcModel: PicturesModel!
override init(){
super.init()
loadPictureImages()
}
private func loadPictureImages(){
var pictureFiles = [String]()
let fm = FileManager.default
let path = Bundle.main.resourcePath!
let items = try! fm.contentsOfDirectory(atPath: path)
for item in items{
if item.hasPrefix("nssl"){
pictureFiles.append(item)
}
}
vcModel = PicturesModel(pictures: pictureFiles)
}
private func getImageFileWithSelectedFile(_ str : String) -> String?{
if let imageIndex = vcModel.pictures.index(of: str){
return vcModel.pictures[imageIndex]
}
return nil;
}
func getImageFiles()->[String]{
return vcModel.pictures
}
func getImageFileWithString(_ str : String) -> UIImageView?{
let imageView = UIImageView()
if let imageToLoad = getImageFileWithSelectedFile(str){
imageView.image = UIImage(named: imageToLoad)
return imageView
}
return nil
}
}
| bdba899c0a5d24e9150421384d59e5f3 | 21.68254 | 73 | 0.56683 | false | false | false | false |
onevcat/CotEditor | refs/heads/develop | CotEditor/Sources/EncodingManager.swift | apache-2.0 | 2 | //
// EncodingManager.swift
//
// CotEditor
// https://coteditor.com
//
// Created by 1024jp on 2014-09-24.
//
// ---------------------------------------------------------------------------
//
// © 2004-2007 nakamuxu
// © 2014-2021 1024jp
//
// 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
//
// https://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 Combine
import Cocoa
@objc protocol EncodingHolder: AnyObject {
func changeEncoding(_ sender: NSMenuItem)
}
// MARK: -
final class EncodingManager {
// MARK: Public Properties
static let shared = EncodingManager()
@Published private(set) var encodings: [String.Encoding?] = []
// MARK: Private Properties
private var encodingListObserver: AnyCancellable?
// MARK: -
// MARK: Lifecycle
private init() {
// -> UserDefaults.standard[.encodingList] can be empty if the user's list contains negative values.
// It seems to be possible if the setting was made a long time ago. (2018-01 CotEditor 3.3.0)
if UserDefaults.standard[.encodingList].isEmpty {
self.sanitizeEncodingListSetting()
}
self.encodingListObserver = UserDefaults.standard.publisher(for: .encodingList, initial: true)
.map { $0.map { $0 != kCFStringEncodingInvalidId ? String.Encoding(cfEncoding: $0) : nil } }
.sink { [weak self] in self?.encodings = $0 }
}
// MARK: Public Methods
/// returns corresponding NSStringEncoding from an encoding name
func encoding(name encodingName: String) -> String.Encoding? {
return DefaultSettings.encodings.lazy
.filter { $0 != kCFStringEncodingInvalidId } // = separator
.map { String.Encoding(cfEncoding: $0) }
.first { encodingName == String.localizedName(of: $0) }
}
/// returns corresponding NSStringEncoding from an IANA char set name
func encoding(ianaCharSetName: String) -> String.Encoding? {
return DefaultSettings.encodings.lazy
.filter { $0 != kCFStringEncodingInvalidId } // = separator
.map { String.Encoding(cfEncoding: $0) }
.first { $0.ianaCharSetName?.caseInsensitiveCompare(ianaCharSetName) == .orderedSame }
}
/// return copied encoding menu items
func createEncodingMenuItems() -> [NSMenuItem] {
return self.encodings.map { encoding in
guard let encoding = encoding else {
return .separator()
}
let item = NSMenuItem()
item.title = String.localizedName(of: encoding)
item.tag = Int(encoding.rawValue)
return item
}
}
/// set available encoding menu items with action to passed-in menu
func updateChangeEncodingMenu(_ menu: NSMenu) {
menu.items.removeAll { $0.action == #selector(EncodingHolder.changeEncoding) }
for item in self.createEncodingMenuItems() {
item.action = #selector(EncodingHolder.changeEncoding)
item.target = nil
menu.addItem(item)
// add "UTF-8 with BOM" item just after the normal UTF-8
if item.tag == FileEncoding(encoding: .utf8).tag {
let fileEncoding = FileEncoding(encoding: .utf8, withUTF8BOM: true)
let bomItem = NSMenuItem(title: fileEncoding.localizedName,
action: #selector(EncodingHolder.changeEncoding),
keyEquivalent: "")
bomItem.tag = fileEncoding.tag
menu.addItem(bomItem)
}
}
}
// MARK: Private Methods
/// convert invalid encoding values (-1) to `kCFStringEncodingInvalidId`
private func sanitizeEncodingListSetting() {
guard
let list = UserDefaults.standard.array(forKey: DefaultKeys.encodingList.rawValue) as? [Int],
!list.isEmpty else {
// just restore to default if failed
UserDefaults.standard.restore(key: .encodingList)
return
}
UserDefaults.standard[.encodingList] = list.map { CFStringEncoding(exactly: $0) ?? kCFStringEncodingInvalidId }
}
}
| acbe7d0a575022f79a7695a8b22cdd30 | 31.85906 | 119 | 0.591912 | false | false | false | false |
coder-zyp/SeparatorLine | refs/heads/master | SeparatorLine/SeparatorLine.swift | mit | 1 | //
// ZYPLine.swift
// testCode
//
// Created by yunpeng zhang on 2017/4/15.
// Copyright © 2017年 yunpeng zhang. All rights reserved.
//
import Foundation
import UIKit
func RGBA (r:CGFloat, g:CGFloat, b:CGFloat, a:CGFloat) -> UIColor { return UIColor (red: r/255.0, green: g/255.0, blue: b/255.0, alpha: a) }
struct SuperConstraint {
var centerX : NSLayoutConstraint! = nil
var centerY : NSLayoutConstraint! = nil
var top : NSLayoutConstraint! = nil
var bottom : NSLayoutConstraint! = nil
var left : NSLayoutConstraint! = nil
var right : NSLayoutConstraint! = nil
var height : NSLayoutConstraint! = nil
var width : NSLayoutConstraint! = nil
}
enum ZYPPosition {
case leading
case trailing
case center
}
extension UIViewContentMode {
}
extension UIView {
public class Line : UIView {
//线条默认值
private var color : UIColor = RGBA (r: 210, g: 210, b: 210, a: 1)
private var width : CGFloat = 1
//方法接受的值
private var position: UIViewContentMode! = nil
private var space :CGFloat = 0 {
didSet{
if position == .right || position == .bottom {
space = -space
}
}
}
private var toView: UIView?
private var dashWidth : CGFloat = 0 //初始化的值不要换
var superConstraint = SuperConstraint()
private var leadInset : CGFloat = 0
private var trailInset : CGFloat = 0{
didSet{
trailInset = -trailInset
}
}
private var leadOrTrail : ZYPPosition! = nil
private var leadOrTrailView : UIView?
private var length :CGFloat? = nil
private var inset :CGFloat = 0{
didSet {
leadInset = inset
trailInset = inset
}
}
public func color (color:UIColor) -> Line{
self.backgroundColor = color
self.color = color
return self
}
//变成虚线的方法,默认虚实10px, 改变了view的背景颜色,所以只能最后使用
public func dash() -> Line {
self.backgroundColor = .white
self.dashWidth = 10
return self
}
public func dash(dashWidth: CGFloat) -> Line {
self.backgroundColor = .white
self.dashWidth = dashWidth
return self
}
public func width(width: CGFloat) -> Line {
self.width = width
superConstraint.height.constant = width
superConstraint.width.constant = width
return self
}
public func space(space: CGFloat) -> Line {
self.space = space
self.constraintsUpdate()
return self
}
public func spaceToView( view:UIView ,space: CGFloat) -> Line {
self.toView = view
self.space = space
self.constraintsChange()
return self
}
public func inset (inset:CGFloat) -> Line {
self.inset = inset
self.constraintsUpdate()
return self
}
func leadInset(inset:CGFloat) -> Line {
leadOrTrail = .leading
leadInset = space
self.constraintsUpdate()
return self
}
func trailInset(inset:CGFloat) -> Line {
leadOrTrail = .trailing
trailInset = inset
self.constraintsUpdate()
return self
}
func leadToView(view:UIView,inset:CGFloat) -> Line {
leadOrTrail = .leading
leadOrTrailView = view
leadInset = inset
self.constraintsChange()
return self
}
func trailToView(view:UIView,inset:CGFloat) -> Line {
leadOrTrail = .trailing
leadOrTrailView = view
trailInset = inset
self.constraintsChange()
return self
}
func length(ZYPPosition:ZYPPosition,length:CGFloat) -> Line {
leadOrTrail = ZYPPosition
self.length = length
switch ZYPPosition {
case .leading:
switch (position!){
case .top ,.bottom:
self.superview?.removeConstraint(superConstraint.right)
let width = NSLayoutConstraint (item: self, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 0, constant: length)
self.superview?.addConstraint(width)
case .left , .right:
self.superview?.removeConstraint(superConstraint.bottom)
let height = NSLayoutConstraint (item: self, attribute: .height, relatedBy: .equal, toItem: nil , attribute: .notAnAttribute, multiplier: 0 , constant: length)
self.superview?.addConstraint(height)
default:
break
}
case .trailing:
switch (position!){
case .top ,.bottom:
self.superview?.removeConstraint(superConstraint.left)
let width = NSLayoutConstraint (item: self, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 0, constant: length)
self.superview?.addConstraint(width)
case .left , .right:
self.superview?.removeConstraint(superConstraint.top)
let height = NSLayoutConstraint (item: self, attribute: .height, relatedBy: .equal, toItem: nil , attribute: .notAnAttribute, multiplier: 0 , constant: length)
self.superview?.addConstraint(height)
default:
break
}
case .center:
switch (position!){
case .top ,.bottom:
self.superview?.removeConstraint(superConstraint.left)
self.superview?.removeConstraint(superConstraint.right)
let width = NSLayoutConstraint (item: self, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 0, constant: length)
self.superview?.addConstraint(width)
self.superview?.addConstraint(superConstraint.centerX)
case .left , .right:
self.superview?.removeConstraint(superConstraint.top)
self.superview?.removeConstraint(superConstraint.bottom)
let height = NSLayoutConstraint (item: self, attribute: .height, relatedBy: .equal, toItem: nil , attribute: .notAnAttribute, multiplier: 0 , constant: length)
self.superview?.addConstraint(height)
self.superview?.addConstraint(superConstraint.centerY)
default:
break
}
}
return self
}
public override func draw(_ rect: CGRect) {
super.draw(rect)
if dashWidth>0 {
let context = UIGraphicsGetCurrentContext()!
context.setLineCap(CGLineCap.square)
let lengths:[CGFloat] = [dashWidth,dashWidth*2] // 绘制 跳过 无限循环
context.setStrokeColor(self.color.cgColor)
context.setLineWidth(2.0)
context.setLineDash(phase: 0, lengths: lengths)
switch position! {
case .top,.bottom:
context.move(to: CGPoint(x: 0, y: self.frame.height/2))
context.addLine(to: CGPoint(x: self.frame.width, y: self.frame.height/2))
context.strokePath()
case .left, .right:
context.move(to: CGPoint(x: self.frame.width/2, y: 0))
context.addLine(to: CGPoint(x:self.frame.width/2 , y: self.frame.height))
context.strokePath()
default:
break
}
}
}
private func constraintsChange() {
if let view = toView {
switch (position!){
case .top:
self.superview?.removeConstraint(superConstraint.top)
superConstraint.top = NSLayoutConstraint (item: self, attribute: .top, relatedBy: .equal, toItem: view, attribute: .bottom, multiplier: 1, constant: space)
self.superview?.addConstraint(superConstraint.top)
case .bottom:
self.superview?.removeConstraint(superConstraint.top)
superConstraint.bottom = NSLayoutConstraint (item: self, attribute: .top, relatedBy: .equal, toItem: view, attribute: .bottom, multiplier: 1, constant: space)
self.superview?.addConstraint(superConstraint.top)
case .left:
self.superview?.removeConstraint(superConstraint.left)
superConstraint.left = NSLayoutConstraint (item: self, attribute: .left, relatedBy: .equal, toItem: view, attribute: .right, multiplier: 1, constant: space)
self.superview?.addConstraint(superConstraint.left)
case .right:
self.superview?.removeConstraint(superConstraint.right)
superConstraint.right = NSLayoutConstraint (item: self, attribute: .right, relatedBy: .equal, toItem: view, attribute: .left, multiplier: 1, constant: space)
self.superview?.addConstraint(superConstraint.right)
default:
break
}
}
if let view = leadOrTrailView {
switch (position!){
case .top ,.bottom:
if leadOrTrail == .leading {
self.superview?.removeConstraint(superConstraint.left)
superConstraint.left = NSLayoutConstraint (item: self, attribute: .left, relatedBy: .equal, toItem: view, attribute: .right, multiplier: 1, constant: leadInset)
self.superview?.addConstraint(superConstraint.left)
}else{
self.superview?.removeConstraint(superConstraint.right)
superConstraint.right = NSLayoutConstraint (item: self, attribute: .right, relatedBy: .equal, toItem: view, attribute: .left, multiplier: 1, constant: trailInset)
self.superview?.addConstraint(superConstraint.right)
}
case .left , .right:
if leadOrTrail == .leading {
self.superview?.removeConstraint(superConstraint.top)
superConstraint.top = NSLayoutConstraint (item: self, attribute: .top, relatedBy: .equal, toItem: view, attribute: .bottom, multiplier: 1, constant: leadInset)
self.superview?.addConstraint(superConstraint.top)
}else{
self.superview?.removeConstraint(superConstraint.bottom)
superConstraint.bottom = NSLayoutConstraint (item: self, attribute: .bottom, relatedBy: .equal, toItem: view, attribute: .top, multiplier: 1, constant: trailInset)
self.superview?.addConstraint(superConstraint.bottom)
}
default:
break
}
}
}
private func constraintsUpdate() {
switch position! {
case .top:
superConstraint.top.constant = space
superConstraint.left.constant = leadInset
superConstraint.right.constant = trailInset
case .bottom:
superConstraint.bottom.constant = space
superConstraint.left.constant = leadInset
superConstraint.right.constant = trailInset
case .left:
superConstraint.left.constant = space
superConstraint.top.constant = leadInset
superConstraint.bottom.constant = trailInset
case .right:
superConstraint.right.constant = space
superConstraint.top.constant = leadInset
superConstraint.bottom.constant = trailInset
default:
break
}
}
public init( superView: UIView, position: UIViewContentMode) {
super.init(frame: CGRect.zero)
superView.addSubview(self)
self.translatesAutoresizingMaskIntoConstraints = false
backgroundColor = color
self.position = position
superConstraint.top = NSLayoutConstraint (item: self, attribute: .top, relatedBy: .equal, toItem: superView, attribute: .top, multiplier: 1, constant: 0)
superConstraint.bottom = NSLayoutConstraint (item: self, attribute: .bottom, relatedBy: .equal, toItem: superView, attribute: .bottom, multiplier: 1, constant: 0)
superConstraint.left = NSLayoutConstraint (item: self, attribute: .left, relatedBy: .equal, toItem: superView, attribute: .left, multiplier: 1, constant: 0)
superConstraint.right = NSLayoutConstraint (item: self, attribute: .right, relatedBy: .equal, toItem: superView, attribute: .right, multiplier: 1, constant: 0)
superConstraint.height = NSLayoutConstraint (item: self, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .height, multiplier: 0, constant: width)
superConstraint.width = NSLayoutConstraint (item: self, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .width, multiplier: 0, constant: width)
superConstraint.centerX = NSLayoutConstraint (item: self, attribute: .centerX, relatedBy: .equal, toItem: superView, attribute: .centerX, multiplier: 1, constant: 0)
superConstraint.centerY = NSLayoutConstraint (item: self, attribute: .centerY, relatedBy: .equal, toItem: superView, attribute: .centerY, multiplier: 1, constant: 0)
switch (position){
case .top:
self.superview?.addConstraints([superConstraint.right,superConstraint.left,superConstraint.top,superConstraint.height])
case .bottom:
self.superview?.addConstraints([superConstraint.right,superConstraint.left,superConstraint.bottom,superConstraint.height])
case .left:
self.superview?.addConstraints([superConstraint.top,superConstraint.left,superConstraint.bottom,superConstraint.width])
case .right:
self.superview?.addConstraints([superConstraint.right,superConstraint.bottom,superConstraint.top,superConstraint.width])
default:
break
}
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
public func separator(position: UIViewContentMode ) -> UIView.Line {
self.translatesAutoresizingMaskIntoConstraints = false
let line = Line (superView: self, position: position)
return line
}
}
| 9cb17bafefcb58f9ce372c14eabc4faa | 43.7851 | 187 | 0.560525 | false | false | false | false |
bobbymay/HouseAds | refs/heads/master | Ads/Files/Internet.swift | mit | 1 | import Foundation
import SystemConfiguration
enum InternetStatus {
case offline, wwan, wifi
init(InternetFlags flags: SCNetworkReachabilityFlags) {
let connectionRequired = flags.contains(.connectionRequired)
let isReachable = flags.contains(.reachable)
let isWWAN = flags.contains(.isWWAN)
if !connectionRequired && isReachable {
if isWWAN { self = .wwan } else { self = .wifi }
} else {
self = .offline
}
}
}
public class Internet {
/// Checks Internet connection status
static var available: Bool {
switch Internet().checkConnection() {
case .offline: return false
case .wwan: return true
case .wifi: return true
}
}
/// Checks Internet connection type: .offline .wwan .wifi
static var connectedBy: InternetStatus {
switch Internet().checkConnection() {
case .offline: return .offline
case .wwan: return .wwan
case .wifi: return .wifi
}
}
/// Monitor Internet and run code in SCNetworkReachabilitySetCallback when connection is established
func monitorInternet() {
var context = SCNetworkReachabilityContext(version: 0, info: nil, retain: nil, release: nil, copyDescription: nil)
let reachable = SCNetworkReachabilityCreateWithName(nil, "apple.com")!
SCNetworkReachabilitySetCallback(reachable, { ( _, _, _) in
guard Internet.available else { return }
if !Banners.File.downloaded && !Banners.File.trying && !Banners.File.attempted { Banners.getFile() }
}, &context)
SCNetworkReachabilityScheduleWithRunLoop(reachable, CFRunLoopGetMain(), RunLoopMode.commonModes as CFString)
}
/// Check Internet status
private func checkConnection() -> InternetStatus {
if let flags = getFlags() { return InternetStatus(InternetFlags: flags) }
return .offline
}
private func getFlags() -> SCNetworkReachabilityFlags? {
guard let reachability = ipv4() ?? ipv6() else { return nil }
var flags = SCNetworkReachabilityFlags()
if !SCNetworkReachabilityGetFlags(reachability, &flags) { return nil }
return flags
}
private func ipv6() -> SCNetworkReachability? {
var zeroAddress = sockaddr_in6()
zeroAddress.sin6_len = UInt8(MemoryLayout<sockaddr_in>.size)
zeroAddress.sin6_family = sa_family_t(AF_INET6)
return withUnsafePointer(to: &zeroAddress, {
$0.withMemoryRebound(to: sockaddr.self, capacity: 1) {
SCNetworkReachabilityCreateWithAddress(nil, $0)
}
})
}
private func ipv4() -> SCNetworkReachability? {
var zeroAddress = sockaddr_in()
zeroAddress.sin_len = UInt8(MemoryLayout<sockaddr_in>.size)
zeroAddress.sin_family = sa_family_t(AF_INET)
return withUnsafePointer(to: &zeroAddress, {
$0.withMemoryRebound(to: sockaddr.self, capacity: 1) {
SCNetworkReachabilityCreateWithAddress(nil, $0)
}
})
}
}
| 7b5c002e31cdbc4746e5b6ffd53cbff0 | 23.758929 | 116 | 0.717634 | false | false | false | false |
overtake/TelegramSwift | refs/heads/master | Telegram-Mac/FasterStarsView.swift | gpl-2.0 | 1 | //
// FasterStarsView.swift
// Telegram
//
// Created by Mike Renoir on 14.06.2022.
// Copyright © 2022 Telegram. All rights reserved.
//
import Foundation
import TGUIKit
import SceneKit
final class FasterStarsView: NSView, PremiumDecorationProtocol {
private let sceneView: SCNView
private var particles: SCNNode?
override init(frame: CGRect) {
self.sceneView = SCNView(frame: CGRect(origin: .zero, size: frame.size))
self.sceneView.backgroundColor = .clear
if let url = Bundle.main.url(forResource: "lightspeed", withExtension: "scn") {
self.sceneView.scene = try? SCNScene(url: url, options: nil)
}
super.init(frame: frame)
wantsLayer = true
self.layer?.opacity = 0.0
self.addSubview(self.sceneView)
self.particles = self.sceneView.scene?.rootNode.childNode(withName: "particles", recursively: false)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
deinit {
self.particles = nil
}
func setVisible(_ visible: Bool) {
if visible, let particles = self.particles, particles.parent == nil {
self.sceneView.scene?.rootNode.addChildNode(particles)
}
self._change(opacity: visible ? 0.4 : 0.0, animated: true, completion: { [weak self] finished in
if let strongSelf = self, finished && !visible && strongSelf.particles?.parent != nil {
strongSelf.particles?.removeFromParentNode()
}
})
}
private var playing = false
func startAnimation() {
guard !self.playing, let scene = self.sceneView.scene, let node = scene.rootNode.childNode(withName: "particles", recursively: false), let particles = node.particleSystems?.first else {
return
}
self.playing = true
let speedAnimation = CABasicAnimation(keyPath: "speedFactor")
speedAnimation.fromValue = 1.0
speedAnimation.toValue = 1.8
speedAnimation.duration = 0.8
speedAnimation.fillMode = .forwards
particles.addAnimation(speedAnimation, forKey: "speedFactor")
particles.speedFactor = 3.0
let stretchAnimation = CABasicAnimation(keyPath: "stretchFactor")
stretchAnimation.fromValue = 0.05
stretchAnimation.toValue = 0.3
stretchAnimation.duration = 0.8
stretchAnimation.fillMode = .forwards
particles.addAnimation(stretchAnimation, forKey: "stretchFactor")
particles.stretchFactor = 0.3
}
func resetAnimation() {
guard self.playing, let scene = self.sceneView.scene, let node = scene.rootNode.childNode(withName: "particles", recursively: false), let particles = node.particleSystems?.first else {
return
}
self.playing = false
let speedAnimation = CABasicAnimation(keyPath: "speedFactor")
speedAnimation.fromValue = 3.0
speedAnimation.toValue = 1.0
speedAnimation.duration = 0.35
speedAnimation.fillMode = .forwards
particles.addAnimation(speedAnimation, forKey: "speedFactor")
particles.speedFactor = 1.0
let stretchAnimation = CABasicAnimation(keyPath: "stretchFactor")
stretchAnimation.fromValue = 0.3
stretchAnimation.toValue = 0.05
stretchAnimation.duration = 0.35
stretchAnimation.fillMode = .forwards
particles.addAnimation(stretchAnimation, forKey: "stretchFactor")
particles.stretchFactor = 0.05
}
override func layout() {
super.layout()
self.sceneView.frame = CGRect(origin: .zero, size: frame.size)
}
}
| f7534fbfae5c04ecb963caa424f10b89 | 33.324324 | 193 | 0.632808 | false | false | false | false |
lllyyy/LY | refs/heads/master | ParallaxHeader/UIScrollView+ParallaxHeader.swift | mit | 2 | //
// UIScrollView+ParallaxHeader.swift
// ParallaxHeader
//
// Created by Roman Sorochak on 6/23/17.
// Copyright © 2017 MagicLab. All rights reserved.
//
import UIKit
import ObjectiveC.runtime
/**
A UIScrollView extension with a ParallaxHeader.
*/
extension UIScrollView {
private struct AssociatedKeys {
static var descriptiveName = "AssociatedKeys.DescriptiveName.parallaxHeader"
}
/**
The parallax header.
*/
public var parallaxHeader: ParallaxHeader {
get {
if let header = objc_getAssociatedObject(
self,
&AssociatedKeys.descriptiveName
) as? ParallaxHeader {
return header
}
let header = ParallaxHeader()
self.parallaxHeader = header
return header
}
set(parallaxHeader) {
parallaxHeader.scrollView = self
objc_setAssociatedObject(
self,
&AssociatedKeys.descriptiveName,
parallaxHeader,
.OBJC_ASSOCIATION_RETAIN_NONATOMIC
)
}
}
}
| b3c74ffd5dd676b3d74f363c7bb7eb9c | 22.979167 | 84 | 0.571677 | false | false | false | false |
Jakintosh/WWDC-2015-Application | refs/heads/master | Jak-Tiano/Jak-Tiano/Entities/Button.swift | mit | 1 | //
// NHCSButton.swift
// wwShootProto
//
// Created by Jak Tiano on 10/20/14.
// Copyright (c) 2014 not a hipster coffee shop. All rights reserved.
//
import Foundation
import SpriteKit
class Button : NHCNode {
// MARK: - Properties
var activated: Bool = true
var selected: Bool = false
// MARK: - Initializers
override init() {
super.init()
userInteractionEnabled = true
}
required init?(coder aDecoder: NSCoder) {
fatalError("shouldn't use init(coder:)")
}
// MARK: - Methods
func activate() {
activated = true
}
func deactivate() {
activated = false
}
func completionAction() {
// fill in in subclasses
println("completion")
}
override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
if activated {
selected = true
}
}
override func touchesMoved(touches: Set<NSObject>, withEvent event: UIEvent) {
if activated {
var touch: UITouch = touches.first as! UITouch
var location: CGPoint = touch.locationInNode(self)
if containsPoint(location) {
selected = true
} else {
selected = false
}
}
}
override func touchesEnded(touches: Set<NSObject>, withEvent event: UIEvent) {
if activated {
var touch: UITouch = touches.first as! UITouch
var location: CGPoint = touch.locationInNode(scene!)
if containsPoint(location) {
completionAction()
}
selected = false
}
}
override func touchesCancelled(touches: Set<NSObject>!, withEvent event: UIEvent!) {
if activated {
selected = false
}
}
} | dd3790d0f8304f6d7c96b945a16d8be1 | 22.725 | 88 | 0.545598 | false | false | false | false |
icepy/AFImageHelper | refs/heads/master | Demo AF+Image+Helper/Demo AF+Image+Helper/ViewController.swift | mit | 1 | //
// ViewController.swift
// Swift Demo UIImage+AF+Additions
//
// Created by Melvin Rivera on 7/5/14.
// Copyright (c) 2014 All Forces. All rights reserved.
//
import UIKit
import CoreImage
struct CellItem {
let text: String
let image: UIImage
}
class Cell: UICollectionViewCell {
@IBOutlet weak var imageView: UIImageView!
@IBOutlet weak var textLabel: UILabel!
}
class ViewController: UICollectionViewController {
let imageWidth = 140.0
let imageHeight = 140.0
var sections = [String]()
var items = [[CellItem]]()
override func viewDidLoad() {
super.viewDidLoad()
// Colors & Gradients
sections.append("Colors & Gradients")
var colors = [CellItem]()
if let image = UIImage(color: UIColor(red: 0.0, green: 0.502, blue: 1.0, alpha: 1.0), size: CGSize(width: imageWidth, height: imageHeight)) {
colors.append(CellItem(text: "Solid Color", image: image))
}
if let image = UIImage(gradientColors: [UIColor(red: 0.808, green: 0.863, blue: 0.902, alpha: 1.0), UIColor(red: 0.349, green: 0.412, blue: 0.443, alpha: 1.0)], size: CGSize(width: imageWidth, height: imageHeight)) {
colors.append(CellItem(text: "Gradient Color", image: image))
}
if let image = UIImage(named: "beach")?.applyGradientColors([UIColor(red: 0.996, green: 0.769, blue: 0.494, alpha: 1.0), UIColor(red: 0.969, green: 0.608, blue: 0.212, alpha: 0.2)]) {
colors.append(CellItem(text: "Gradient Overlay", image: image))
}
if let image = UIImage(startColor: UIColor(red: 0.996, green: 1.0, blue: 1.0, alpha: 1.0), endColor: UIColor(red: 0.627, green: 0.835, blue: 0.922, alpha: 1.0), radialGradientCenter: CGPoint(x: 0.5, y: 0.5), radius: 0.5, size: CGSize(width: imageWidth, height: imageHeight)) {
colors.append(CellItem(text: "Radial Gradient", image: image))
}
items.append(colors)
// Text
sections.append("Text")
var text = [CellItem]()
if let image = UIImage(text: "M", font: UIFont.systemFontOfSize(64), color: UIColor.whiteColor(), backgroundColor: UIColor.redColor(), size: CGSize(width: imageWidth, height: imageHeight), offset: CGPoint(x: 0.0, y: 30.0)) {
text.append(CellItem(text: "Text Image", image: image))
}
items.append(text)
// Rounded Edges & Borders
sections.append("Rounded Edges & Borders")
var corners = [CellItem]()
if let image = UIImage(named: "beach")?.roundCornersToCircle() {
corners.append(CellItem(text: "Circle", image: image))
}
if let image = UIImage(named: "beach")?.roundCornersToCircle(border: 60.0, color: UIColor.grayColor()) {
corners.append(CellItem(text: "Circle + Border", image: image))
}
if let image = UIImage(named: "beach")?.roundCorners(12.0) {
corners.append(CellItem(text: "Round Corners", image: image))
}
items.append(corners)
// Cropping
sections.append("Cropping")
var cropping = [CellItem]()
if let image = UIImage(named: "beach")?.crop(CGRect(x: 40.0, y: 40.0, width: 320.0, height: 100.0))?.applyPadding(6.0) {
cropping.append(CellItem(text: "Crop + Resize", image: image))
}
items.append(cropping)
// Screenshot
sections.append("Screenshot")
var screenshot = [CellItem]()
if let image = UIImage(fromView: self.view)?.resize(CGSize(width: imageWidth, height: imageHeight), contentMode: .ScaleAspectFill) {
screenshot.append(CellItem(text: "From View", image: image))
}
items.append(screenshot)
// Web Image
sections.append("Web Image")
var web = [CellItem]()
if let image = UIImage(color: UIColor.redColor()) {
web.append(CellItem(text: "From URL", image: image))
}
items.append(web)
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
}
override func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
return items.count
}
override func collectionView(collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionReusableView {
let headerView:UICollectionReusableView! = collectionView.dequeueReusableSupplementaryViewOfKind(kind, withReuseIdentifier: "Header", forIndexPath: indexPath) as! UICollectionReusableView
let textLabel = headerView.viewWithTag(1) as! UILabel
textLabel.text = sections[indexPath.section]
return headerView
}
override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int
{
return items[section].count
}
override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell
{
let cellID = "Cell"
let cell:Cell! = collectionView.dequeueReusableCellWithReuseIdentifier(cellID, forIndexPath: indexPath) as! Cell
let item: CellItem = items[indexPath.section][indexPath.item]
cell.textLabel.text = item.text
if (indexPath.section == items.count-1) {
cell.imageView.imageFromURL("https://c2.staticflickr.com/4/3212/3130969018_ed7516c288_n.jpg", placeholder: item.image, fadeIn: true) {
(image: UIImage?) in
if image != nil {
cell.imageView.image = image!
}
}
} else {
cell.imageView.image = item.image
}
return cell
}
}
| e786ddd2cbf112cf80ac488798528616 | 38.125828 | 284 | 0.619499 | false | false | false | false |
KosyanMedia/Aviasales-iOS-SDK | refs/heads/master | AviasalesSDKTemplate/Source/HotelsSource/Sort/SortItemsFactories/HotellookSortItemsFactory.swift | mit | 1 | class HotellookSortItemsFactory: SortItemsFactory {
override func sortTypesForFilter(_ filter: Filter) -> [SortType] {
var items = super.sortTypesForFilter(filter)
let index = min(items.count, 1)
items.insert(.rating, at: index)
let discountVariantsCount = filter.discountVariants()?.count ?? 0
let privatePriceVariantsCount = filter.privatePriceVariants()?.count ?? 0
let shouldAddDiscountItem = discountVariantsCount > 0 || privatePriceVariantsCount > 0
if shouldAddDiscountItem {
items.append(SortType.discount)
}
return items
}
}
| 04956fb438c8e7e6524783e36d62454b | 32.210526 | 94 | 0.671949 | false | false | false | false |
xiaomudegithub/viossvc | refs/heads/master | viossvc/General/Helper/CurrentUserHelper.swift | apache-2.0 | 1 | //
// CurrentUserHelper.swift
// viossvc
//
// Created by yaowang on 2016/11/24.
// Copyright © 2016年 com.yundian. All rights reserved.
//
import UIKit
class CurrentUserHelper: NSObject {
static let shared = CurrentUserHelper()
private let keychainItem:OEZKeychainItemWrapper = OEZKeychainItemWrapper(identifier: "com.yundian.viossvc.account", accessGroup:nil)
private var _userInfo:UserInfoModel!
private var _password:String!
private var _deviceToken:String!
var deviceToken:String! {
get {
return _deviceToken
}
set {
_deviceToken = newValue
updateDeviceToken()
}
}
var userInfo:UserInfoModel! {
get {
return _userInfo
}
}
var isLogin : Bool {
return _userInfo != nil
}
var uid : Int {
return _userInfo.uid
}
func userLogin(phone:String,password:String,complete:CompleteBlock,error:ErrorBlock) {
let loginModel = LoginModel()
loginModel.phone_num = phone
loginModel.passwd = password
_password = password
AppAPIHelper.userAPI().login(loginModel, complete: { [weak self] (model) in
self?.loginComplete(model)
complete(model)
}, error:error)
}
func autoLogin(complete:CompleteBlock,error:ErrorBlock) -> Bool {
let account = lastLoginAccount()
if !NSString.isEmpty(account.phone) && !NSString.isEmpty(account.password) {
userLogin(account.phone!, password:account.password!, complete: complete, error: error)
return true
}
return false
}
private func loginComplete(model:AnyObject?) {
self._userInfo = model as? UserInfoModel
keychainItem.resetKeychainItem()
keychainItem.setObject(_userInfo.phone_num, forKey: kSecAttrAccount)
keychainItem.setObject(_password, forKey: kSecValueData)
initChatHelper()
updateDeviceToken()
}
private func initChatHelper() {
ChatDataBaseHelper.shared.open(_userInfo.uid)
ChatSessionHelper.shared.findHistorySession()
ChatMsgHepler.shared.chatSessionHelper = ChatSessionHelper.shared
ChatMsgHepler.shared.offlineMsgs()
}
func logout() {
AppAPIHelper.userAPI().logout(_userInfo.uid)
nodifyPassword("")
self._userInfo = nil
ChatDataBaseHelper.shared.close()
}
func nodifyPassword(password:String) {
keychainItem.setObject(password, forKey: kSecValueData)
}
func lastLoginAccount()->(phone:String?,password:String?){
return (keychainItem.objectForKey(kSecAttrAccount) as? String,keychainItem.objectForKey(kSecValueData) as? String)
}
private func updateDeviceToken() {
if isLogin && !NSString.isEmpty(_deviceToken) {
AppAPIHelper.userAPI().updateDeviceToken(uid, deviceToken: _deviceToken, complete: nil, error: nil)
}
}
}
| 8008bb0dac3b46c79ea76e1a531ddb1d | 28.625 | 136 | 0.627394 | false | false | false | false |
SandcastleApps/partyup | refs/heads/master | PartyUP/VideoUtilities.swift | mit | 1 | //
// VideoUtilities.swift
// PartyUP
//
// Created by Fritz Vander Heide on 2016-05-01.
// Copyright © 2016 Sandcastle Application Development. All rights reserved.
//
import AVFoundation
typealias VideoEffectApplicator = (AVMutableVideoComposition) -> Void
typealias VideoExportCompletion = (AVAssetExportSessionStatus) -> Void
func applyToVideo(fromInput input: NSURL, toOutput output: NSURL, effectApplicator effect: VideoEffectApplicator, exportCompletionHander exportHandler: VideoExportCompletion) -> AVAssetExportSession? {
var export: AVAssetExportSession?
let asset = AVAsset(URL: input)
let composition = AVMutableComposition()
let video = composition.addMutableTrackWithMediaType(AVMediaTypeVideo, preferredTrackID: kCMPersistentTrackID_Invalid)
let audio = composition.addMutableTrackWithMediaType(AVMediaTypeAudio, preferredTrackID: kCMPersistentTrackID_Invalid)
do {
if let videoAssetTrack = asset.tracksWithMediaType(AVMediaTypeVideo).first, audioAssetTrack = asset.tracksWithMediaType(AVMediaTypeAudio).first
{
try video.insertTimeRange(CMTimeRangeMake(kCMTimeZero, asset.duration), ofTrack: videoAssetTrack, atTime: kCMTimeZero)
try audio.insertTimeRange(CMTimeRangeMake(kCMTimeZero, asset.duration), ofTrack: audioAssetTrack, atTime: kCMTimeZero)
let videoInstruction = AVMutableVideoCompositionInstruction()
videoInstruction
videoInstruction.timeRange = CMTimeRangeMake(kCMTimeZero, asset.duration)
let videoComposition = AVMutableVideoComposition()
videoComposition.renderSize = videoAssetTrack.naturalSize
videoComposition.instructions = [videoInstruction]
videoComposition.frameDuration = CMTimeMake(1, 30)
let track = composition.tracksWithMediaType(AVMediaTypeVideo).first!
let layerInstruction = AVMutableVideoCompositionLayerInstruction(assetTrack: track)
layerInstruction.setTransform(track.preferredTransform, atTime: kCMTimeZero)
videoInstruction.layerInstructions = [layerInstruction]
videoComposition.instructions = [videoInstruction]
effect(videoComposition)
export = AVAssetExportSession(asset: composition, presetName: AVAssetExportPresetMediumQuality)
if let export = export {
export.outputURL = output
export.outputFileType = AVFileTypeQuickTimeMovie
export.shouldOptimizeForNetworkUse = true
export.videoComposition = videoComposition
export.exportAsynchronouslyWithCompletionHandler({
dispatch_async(dispatch_get_main_queue(),{
exportHandler(export.status)
})
})
}
}
} catch {
export = nil
}
return export
} | 96c25477a0c41a4741ffcd972549c952 | 40.21875 | 201 | 0.783466 | false | false | false | false |
jigneshsheth/Datastructures | refs/heads/master | DataStructure/Swift_Interivew_QA.playground/Contents.swift | mit | 1 | import UIKit
//https://www.raywenderlich.com/762435-swift-interview-questions-and-answers
//Question #1
//What are the values of tutorial1.difficulty and tutorial2.difficulty?
//Would this be any different if Tutorial was a class? Why or why not?
struct Tutorial {
var difficulty: Int = 1
}
var tutorial1 = Tutorial()
var tutorial2 = tutorial1
tutorial2.difficulty = 2
/*
tutorial1.difficulty is 1, whereas tutorial2.difficulty is 2.
Structures in Swift are value types. You copy value types by value rather than reference. The following code creates a copy of tutorial1 and assigns it to tutorial2:
var tutorial2 = tutorial1
A change to tutorial2 is not reflected in tutorial1.
If Tutorial were a class, both tutorial1.difficulty and tutorial2.difficulty would be 2. Classes in Swift are reference types. When you change a property of tutorial1, you’ll see it reflected in tutorial2 and vice versa.
*/
//Question #2
//You’ve declared view1 with var, and you’ve declared view2 with let.
//What’s the difference, and will the last line compile?
var view1 = UIView()
view1.alpha = 0.5
let view2 = UIView()
view2.alpha = 0.5 // Will this line compile?
//Yes, the last line will compile. view1 is a variable, and you can reassign it to a new instance of UIView. With let, you can assign a value only once, so the following code would not compile:
//view2 = view1 // Error: view2 is immutable
//However, UIView is a class with reference semantics, so you can mutate the properties of view2 — which means that the last line will compile:
//let view2 = UIView()
//view2.alpha = 0.5 // Yes!
//#### --------
//Question #3
//This complicated code sorts an array of names alphabetically. Simplify the closure as much as you can.
var animals = ["fish", "cat", "chicken", "dog"]
animals.sort { (one: String, two: String) -> Bool in
return one < two
}
print(animals)
animals.sort{$0<$1}
print(animals)
/**
The type inference system automatically calculates both the type of the parameters in the closure and the return type, so you can get rid of them:
animals.sort { (one, two) in return one < two }
You can substitute the $i notation for the parameter names:
animals.sort { return $0 < $1 }
In single statement closures, you can omit the return keyword. The value of the last statement becomes the return value of the closure:
animals.sort { $0 < $1 }
Finally, since Swift knows that the elements of the array conform to Equatable, you can simply write:
animals.sort(by: <)
*/
//Question #4
//This code creates two classes: Address and Person.
//It then creates two Person instances to represent Ray and Brian.
class Address {
var fullAddress: String
var city: String
init(fullAddress: String, city: String) {
self.fullAddress = fullAddress
self.city = city
}
}
class Person {
var name: String
var address: Address
init(name: String, address: Address) {
self.name = name
self.address = address
}
}
var headquarters = Address(fullAddress: "123 Tutorial Street", city: "Appletown")
var ray = Person(name: "Ray", address: headquarters)
var brian = Person(name: "Brian", address: headquarters)
//Suppose Brian moves to the new building across the street; you'll want to update his record like this:
brian.address.fullAddress = "148 Tutorial Street"
//This compiles and runs without error. If you check the address of Ray now, he's also moved to the new building
print (ray.address.fullAddress)
//What's going on here? How can you fix the problem?
/*
Address is a class and has reference semantics so headquarters is the same instance, whether you access it via ray or brian. Changing the address of headquarters will change it for both. Can you imagine what would happen if Brian got Ray's mail or vice versa? :]
The solution is to create a new Address to assign to Brian, or to declare Address as a struct instead of a class.
**/
//Question #1
//What is an optional and which problem do optionals solve?
//An optional lets a variable of any type represent a lack of value. In Objective-C, the absence of value is available only in reference types using the nil special value. Value types, such as int or float, do not have this ability.
//Swift extends the lack of value concept to both reference and value types with optionals. An optional variable can hold either a value or nil, indicating a lack of value.
//Question #2
//Summarize the main differences between a structure and a class.
//You can summarize the differences as:
//Classes support inheritance; structures don't.
//Classes are reference types; structures are value types.
//Question #3
//What are generics and which problem do they solve?
//In Swift, you can use generics in both functions and data types, e.g. in classes, structures or enumerations.
//Generics solve the problem of code duplication. When you have a method that takes one type of parameter, it's common to duplicate it to accommodate a parameter of a different type.
//For example, in the following code the second function is a "clone" of the first, except it accepts strings instead of integers.
func areIntEqual(_ x: Int, _ y: Int) -> Bool {
return x == y
}
func areStringsEqual(_ x: String, _ y: String) -> Bool {
return x == y
}
areStringsEqual("ray", "ray") // true
areIntEqual(1, 1) // true
//By adopting generics, you can combine the two functions into one and keep type safety at the same time. Here's the generic implementation:
func areTheyEqual<T: Equatable>(_ x: T, _ y: T) -> Bool {
return x == y
}
areTheyEqual("ray", "ray")
areTheyEqual(1, 1)
//Since you're testing equality in this case, you restrict the parameters to any type that implements the Equatable protocol. This code achieves the intended result and prevents passing parameters of a different type.
//Question #4
//In some cases, you can't avoid using implicitly unwrapped optionals. When? Why?
//The most common reasons to use implicitly unwrapped optionals are:
//When you cannot initialize a property that is not nil by nature at instantiation time. A typical example is an Interface Builder outlet, which always initializes after its owner. In this specific case — assuming it's properly configured in Interface Builder — you've guaranteed that the outlet is non-nil before you use it.
//To solve the strong reference cycle problem, which is when two instances refer to each other and require a non-nil reference to the other instance. In such a case, you mark one side of the reference as unowned, while the other uses an implicitly unwrapped optional.
//Question #5
//What are the various ways to unwrap an optional? How do they rate in terms of safety?
var x : String? = "Test"
//Hint: There are seven ways.
//Forced unwrapping — unsafe.
//
let a: String = x!
//
//Implicitly unwrapped variable declaration — unsafe in many cases.
//
//var a = x!
//
//Optional binding — safe.
//
if let a = x {
print("x was successfully unwrapped and is = \(a)")
}
//
//Optional chaining — safe.
//
//let a = x?.count
//
//Nil coalescing operator — safe.
//
//let a = x ?? ""
//
//Guard statement — safe.
//
//guard let a = x else {
// return
//}
//
//Optional pattern — safe.
//
//if case let a? = x {
// print(a)
//}
//Intermediate Written Questions
//############################################
//Question #1
//
//There is no difference, as Optional.none (.none for short) and nil are equivalent.
//
//In fact, this statement outputs true:
//
//nil == .none
//
//The use of nil is more common and is the recommended convention.
//Question #2
//Here's a model of a thermometer as a class and a struct. The compiler will complain about the last line. Why does it fail to compile?
public class ThermometerClass {
private(set) var temperature: Double = 0.0
public func registerTemperature(_ temperature: Double) {
self.temperature = temperature
}
}
let thermometerClass = ThermometerClass()
thermometerClass.registerTemperature(56.0)
public struct ThermometerStruct {
private(set) var temperature: Double = 0.0
public mutating func registerTemperature(_ temperature: Double) {
self.temperature = temperature
}
}
let thermometerStruct = ThermometerStruct()
//thermometerStruct.registerTemperature(56.0)
/**
The ThermometerStruct is correctly declared with a mutating function to change its internal variable temperature. The compiler complains because you've invoked registerTemperature on an instance created via let, which is therefore immutable. Change let to var to make the example compile.
With structures, you must mark methods that change the internal state as mutating, but you cannot invoke them from immutable variables.
*/
//Question #3
//What will this code print and why?
var thing = "cars"
let closure = { [thing] in
print("I love \(thing)")
}
thing = "airplanes"
closure()
//
//It'll print: I love cars. The capture list creates a copy of thing when you declare the closure. This means that captured value doesn't change even if you assign a new value to thing.
//
//If you omit the capture list in the closure, then the compiler uses a reference instead of a copy. Therefore, when you invoke the closure, it reflects any change to the variable. You can see this in the following code:
thing = "cars"
let closure_nonCapture = {
print("I love \(thing)")
}
thing = "airplanes"
closure_nonCapture() // Prints: "I love airplanes"
//Question #4
//Here's a global function that counts the number of unique values in an array:
func countUniques<T: Comparable>(_ array: Array<T>) -> Int {
let sorted = array.sorted()
let initial: (T?, Int) = (.none, 0)
let reduced = sorted.reduce(initial) {
($1, $0.0 == $1 ? $0.1 : $0.1 + 1)
}
return reduced.1
}
//It uses sorted, so it restricts T to types that conform to Comparable.
//
//You call it like this:
countUniques([1, 2, 3, 3]) // result is 3
//Rewrite this function as an extension method on Array so that you can write something like this
//You can rewrite the global countUniques(_:) as an Array extension:
extension Array where Element: Comparable {
func countUniques() -> Int {
let sortedValues = sorted()
let initial: (Element?, Int) = (.none, 0)
let reduced = sortedValues.reduce(initial) {
($1, $0.0 == $1 ? $0.1 : $0.1 + 1)
}
return reduced.1
}
}
//Note that the new method is available only when the generic Element type conforms to Comparable.
[1, 2, 3, 3].countUniques() // should print 3
//Question #5
//Here's a function to divide two optional doubles. There are three preconditions to verify before performing the actual division:
//
//The dividend must contain a non nil value.
//The divisor must contain a non nil value.
//The divisor must not be zero.
func divide(_ dividend: Double?, by divisor: Double?) -> Double? {
if dividend == nil {
return nil
}
if divisor == nil {
return nil
}
if divisor == 0 {
return nil
}
return dividend! / divisor!
}
//Improve this function by using the guard statement and without using forced unwrapping.
/*
The guard statement introduced in Swift 2.0 provides an exit path when a condition is not met. It's very helpful when checking preconditions because it lets you express them in a clear way — without the pyramid of doom of nested if statements. Here is an example:
guard dividend != nil else { return nil }
You can also use the guard statement for optional binding, which makes the unwrapped variable accessible after the guard statement:
guard let dividend = dividend else { return .none }
So you can rewrite the divide function as:
func divide(_ dividend: Double?, by divisor: Double?) -> Double? {
guard let dividend = dividend else { return nil }
guard let divisor = divisor else { return nil }
guard divisor != 0 else { return nil }
return dividend / divisor
}
Notice the absence of the implicitly unwrapped operators on the last line because you've unwrapped both dividend and divisor and stored them in non-optional immutable variables.
Note that the results of the unwrapped optionals in a guard statement are available for the rest of the code block that the statement appears in.
You can can simplify this further by grouping the guard statements:
*/
func divide_improved(_ dividend: Double?, by divisor: Double?) -> Double? {
guard let divisor = divisor,let dividend = dividend, divisor == 0 else {
return nil
}
return dividend / divisor
}
//Question #6
//Rewrite the method from question five using an if let statement.
/*The if let statement lets you unwrap optionals and use the value within that code block. Note that you cannot access the unwrapped optional outside the block. You can write the function using an if let statement such as:
*/
func divide_improved_if(_ dividend: Double?, by divisor: Double?) -> Double? {
if let divisor = divisor,let dividend = dividend, divisor == 0{
return dividend / divisor
} else {
return nil
}
}
//Question #1
//In Objective-C, you declare a constant like this:
//
//const int number = 0;
//
//Here is the Swift counterpart:
//
let number = 0
//
//What are the differences between them?
//A const is a variable initialized at compile time with a value or an expression that must be resolved at compilation time.
//
//An immutable created with let is a constant determined at runtime. You can initialize it with a static or a dynamic expression. This allows a declaration such as:
//
let higherNumber = number + 5
//
//Note that you can only assign its value once.
//Question #2
//To declare a static property or function, you use the static modifier on value types. Here's an example for a structure:
//struct Sun {
// static func illuminate() {}
//}
//For classes, it's possible to use either the static or the class modifier. They achieve the same goal, but in different ways. Can you explain how they differ?
//
//static makes a property or a function static and not overridable. Using class lets you override the property or function.
//
//When applied to classes, static becomes an alias for class final.
//
//For example, in this code the compiler will complain when you try to override illuminate():
class Star {
class func spin() {}
static func illuminate() {}
}
class Sun : Star {
override class func spin() {
super.spin()
}
// error: class method overrides a 'final' class method
// override static func illuminate() {
// super.illuminate()
// }
}
//Question #3
//Can you add a stored property to a type by using an extension? How or why not?
/*
No, it's not possible. You can use an extension to add new behavior to an existing type, but not to alter either the type itself or its interface. If you add a stored property, you'd need extra memory to store the new value. An extension cannot manage such a task.
*/
//Question #4
//What is a protocol in Swift?
/*
A protocol is a type that defines a blueprint of methods, properties and other requirements. A class, structure or enumeration can then adopt the protocol to implement those requirements.
A type that adopts the requirements of a protocol conforms to that protocol. The protocol doesn't implement any functionality itself, but rather defines the functionality. You can extend a protocol to provide a default implementation of some of the requirements or additional functionality that conforming types can take advantage of.
*/
//############################################
//Advanced Written Questions
//############################################
//Question #1
//Consider the following structure that models a thermometer:
public struct Thermometer {
public var temperature: Double
public init(temperature: Double) {
self.temperature = temperature
}
}
//To create an instance, you can use this code:
var t: Thermometer = Thermometer(temperature:56.8)
//But it would be nicer to initialize it this way:
//var thermometer: Thermometer = 56.8
//Can you? How?
/*
Swift defines protocols that enable you to initialize a type with literal values by using the assignment operator. Adopting the corresponding protocol and providing a public initializer allows literal initialization of a specific type. In the case of Thermometer, you implement ExpressibleByFloatLiteral as follows:
extension Thermometer: ExpressibleByFloatLiteral {
public init(floatLiteral value: FloatLiteralType) {
self.init(temperature: value)
}
}
Now, you can create an instance by using a float.
var thermometer: Thermometer = 56.8
*/
//Are closures value or reference types?
//Closures are reference types. If you assign a closure to a variable and you copy the variable into another variable, you also copy a reference to the same closure and its capture list.
//You use the UInt type to store unsigned integers. It implements the following initializer to convert from a signed integer:
//init(_ value: Int)
//However, the following code generates a compile time error exception if you provide a negative value:
//let myNegative = UInt(-1)
//An unsigned integer by definition cannot be negative. However, it's possible to use the memory representation of a negative number to translate to an unsigned integer. How can you convert an Int negative number into an UInt while keeping its memory representation?
//There's an initializer for that:
//UInt(bitPattern: Int)
//making the implementation:
//let myNegative = UInt(bitPattern: -1)
//Question #3
//Can you describe a circular reference in Swift? How can you solve it?
//A circular reference happens when two instances hold a strong reference to each other, causing a memory leak because neither of the two instances will ever be deallocated. The reason is that you cannot deallocate an instance as long as there's a strong reference to it, but each instance keeps the other alive because of its strong reference.
//You'd solve the problem by breaking the strong circular reference by replacing one of the strong references with a weak or an unowned reference.
//Question #4
//Swift allows the creation of recursive enumerations. Here's an example of such an enumeration with a Node case that takes two associated value types, T and List:
//enum List<T> {
// case node(T, List<T>)
//}
//This returns a compilation error. What is the missing keyword?
/*
It's the indirect keyword that allows for recursive enumeration cases like this:
*/
enum List<T> {
indirect case node(T, List<T>)
}
/*
Question #2
Swift has a set of pre-defined operators to perform arithmetic or logic operations. It also allows the creation of custom operators, either unary or binary.
Define and implement a custom ^^ power operator with the following specifications:
Takes two Ints as parameters.
Returns the first parameter raised to the power of the second.
Correctly evaluates the equation using the standard algebraic order of operations.
Ignores the potential for overflow errors.
You create a new custom operator in two steps: Declaration and implementation.
The declaration uses the operator keyword to specify the type (unary or binary), the sequence of characters composing the operator, its associativity and precedence. Swift 3.0 changed the implementation of precedence to use a precedence group.
Here, the operator is ^^ and the type is infix (binary). Associativity is right; in other words, equal precedence ^^ operators should evaluate the equation from right to left.
There is no predefined standard precedence for exponential operations in Swift. In the standard order of operations for algebra, exponents should calculate before multiplication/division. So you'll need to create a custom precedence that places them higher than multiplication.
Here's the declaration:
*/
precedencegroup ExponentPrecedence {
higherThan: MultiplicationPrecedence
associativity: right
}
infix operator ^^: ExponentPrecedence
//The implementation follows:
func ^^(base: Int, exponent: Int) -> Int {
let l = Double(base)
let r = Double(exponent)
let p = pow(l, r)
return Int(p)
}
//Note that since the code doesn't take overflows into account, if the operation produces a result that Int can't represent, such as a value greater than Int.max, then a runtime error occurs.
/*
Question #3
Consider the following code that defines Pizza as a struct and Pizzeria as a protocol with an extension that includes a default implementation for makeMargherita():
*/
struct Pizza {
let ingredients: [String]
}
protocol Pizzeria {
func makePizza(_ ingredients: [String]) -> Pizza
func makeMargherita() -> Pizza
}
extension Pizzeria {
func makeMargherita() -> Pizza {
return makePizza(["tomato", "mozzarella"])
}
}
//You'll now define the restaurant Lombardi’s as follows:
struct Lombardis: Pizzeria {
func makePizza(_ ingredients: [String]) -> Pizza {
return Pizza(ingredients: ingredients)
}
func makeMargherita() -> Pizza {
return makePizza(["tomato", "basil", "mozzarella"])
}
}
///The following code creates two instances of Lombardi's. Which of the two will make a margherita with basil?
let lombardis1: Pizzeria = Lombardis()
let lombardis2: Lombardis = Lombardis()
lombardis1.makeMargherita()
lombardis2.makeMargherita()
/*
They both do. The Pizzeria protocol declares the makeMargherita() method and provides a default implementation. The Lombardis implementation overrides the default method. Since you declare the method in the protocol in both cases, you'll invoke the correct implementation at runtime.
What if the protocol doesn't declare the makeMargherita() method but the extension still provides a default implementation, like this?
protocol Pizzeria {
func makePizza(_ ingredients: [String]) -> Pizza
}
extension Pizzeria {
func makeMargherita() -> Pizza {
return makePizza(["tomato", "mozzarella"])
}
}
Here, only lombardis2 would make the pizza with basil, whereas lombardis1 would make a pizza without it, because it would use the method defined in the extension.
*/
//Question #4
//The following code has a compile time error. Can you spot it and explain why it happens? What are some ways you could fix it?
//struct Kitten {
//}
//
//func showKitten(kitten: Kitten?) {
// guard let k = kitten else {
// print("There is no kitten")
// // return is not there
// }
// print(k)
//}
/*
The else block of a guard requires an exit path, either by using return, throwing an exception or calling a @noreturn. The easiest solution is to add a return statement.
func showKitten(kitten: Kitten?) {
guard let k = kitten else {
print("There is no kitten")
return
}
print(k)
}
Here's a version that throws an exception.
enum KittenError: Error {
case NoKitten
}
struct Kitten {
}
func showKitten(kitten: Kitten?) throws {
guard let k = kitten else {
print("There is no kitten")
throw KittenError.NoKitten
}
print(k)
}
try showKitten(kitten: nil)
Finally, here's an implementation calling fatalError(), which is a @noreturn function.
struct Kitten {
}
func showKitten(kitten: Kitten?) {
guard let k = kitten else {
print("There is no kitten")
fatalError()
}
print(k)
}
*/
//############################################
| ead5837447cd4cf7beca81f033f819e1 | 30.914483 | 344 | 0.7355 | false | false | false | false |
kevin-zqw/play-swift | refs/heads/master | swift-lang/12. Subscripts.playground/section-1.swift | apache-2.0 | 1 | // ------------------------------------------------------------------------------------------------
// Things to know:
//
// * Subscripts allow you to declare functionality for instances to make use of the subscript
// operator ( [] ).
//
// * Subscripts are available for classes, structures and enumerations.
//
// * Subscripts are declared much like getters and setters for properties.
// ------------------------------------------------------------------------------------------------
// Subscripts are declared like getters and setters, and follow the same syntax rules for
// read-only and read-write variants. They also can employ the same syntactic simplifications
// available for getters and setters.
//
// Here's a structure that utilizes a subscript so that we can see the syntax of the declaration.
struct TimesTable
{
let multiplier: Int
// Read-only subscript using simplified getter syntax
subscript(index: Int) -> Int
{
return multiplier * index
}
// Overloaded subscript for type Double, also read-only using the simplified getter syntax
subscript(index: Double) -> Int
{
return multiplier * Int(index)
}
}
// We can now make use of our newly created subscripts
let threeTimesTable = TimesTable(multiplier: 3)
threeTimesTable[3]
threeTimesTable[4.0]
// Subscripts can take any parameter type and variadic parameters, but cannot use inout or default
// parameters.
//
// Here's a more complex example:
// Subscripts cannot use in-out parameters or provide default paraemter values.
// Subscripts can overloading, and use any paramters type and variadic parameters.
struct Matrix
{
let rows: Int
let columns: Int
var grid: [Double]
init (rows: Int, columns: Int)
{
self.rows = rows
self.columns = columns
grid = Array(count: rows * columns, repeatedValue: 0.0)
}
func indexIsValidForRow(row: Int, column: Int) -> Bool
{
return row >= 0 && row < rows && column >= 0 && column < columns
}
// Subscript with getter & setter as well as dual-parameter subscript
subscript(row: Int, column: Int) -> Double
{
get
{
assert(indexIsValidForRow(row, column: column), "Index out of range")
return grid[row * columns + column]
}
set
{
assert(indexIsValidForRow(row, column: column), "Index out of range")
grid[row * columns + column] = newValue
}
}
}
// We'll create a standard 4x4 identity matrix
var matrix = Matrix(rows: 4, columns: 4)
matrix[0,0] = 1
matrix[1,1] = 1
matrix[2,2] = 1
matrix[3,3] = 1
| b39a6fc798b839c99c7cd20c8fc961d5 | 27.528736 | 99 | 0.657534 | false | false | false | false |
fleurdeswift/video-clip-annotation-editor | refs/heads/master | VideoClipAnnotationEditor/VideoClipPreviewCache.swift | mit | 1 | //
// VideoClipPreviewCache.swift
// VideoClipAnnotationEditor
//
// Copyright © 2015 Fleur de Swift. All rights reserved.
//
import ExtraDataStructures
import Foundation
public let VideoClipPreviewCacheUpdated = "VideoClipPreviewCacheUpdated";
public class VideoClipPreviewCache : NSObject {
private struct Entry : Hashable {
let clip: VideoClip;
let time: Int;
init(clip: VideoClip, time: NSTimeInterval) {
self.clip = clip;
self.time = Int(time * 10);
}
var hashValue: Int {
get {
return unsafeAddressOf(clip).hashValue ^ time;
}
}
}
private var disposed = false;
private let sampleRate: NSTimeInterval;
private func allocCaptureBlock(current: VideoClip, remaining: [VideoClip]) -> (image: CGImageRef?, error: NSError?) -> NSTimeInterval {
var time: NSTimeInterval = 0;
return {
(image: CGImageRef?, error: NSError?) -> NSTimeInterval in
if self.disposed || (error != nil) {
return -1;
}
if let image = image {
self.set(current, time: time, image: image)
}
time += self.sampleRate;
if time >= current.duration {
self.captureNextBlock(remaining);
return -1;
}
return time;
}
}
private func captureNextBlock(clips: [VideoClip]) {
if clips.count == 0 {
return;
}
var remaining = clips;
let current = clips[0];
remaining.removeAtIndex(0);
current.imageAtTime(0, completionBlock: allocCaptureBlock(current, remaining: remaining));
}
public init(clips: [VideoClip], sampleRate: NSTimeInterval) {
self.sampleRate = sampleRate;
super.init();
self.captureNextBlock(clips);
}
public func dispose() {
return dispatch_async(queue) {
self.disposed = true;
self.cache.removeAll();
}
}
private let queue = dispatch_queue_create("VideoClipCache", DISPATCH_QUEUE_SERIAL);
private var cache = [Entry: CGImageRef]();
public func get(clip: VideoClip, time: NSTimeInterval) -> CGImageRef? {
let entry = Entry(clip: clip, time: time);
return dispatch_sync(queue) {
return self.cache[entry];
}
}
public func set(clip: VideoClip, time: NSTimeInterval, image: CGImageRef) -> Void {
let entry = Entry(clip: clip, time: time);
dispatch_async(queue) {
self.cache[entry] = image;
dispatch_async_main {
NSNotificationCenter.defaultCenter().postNotificationName(VideoClipPreviewCacheUpdated, object: self, userInfo: [
"Time": time,
"Image": image
]);
}
}
}
}
private func == (e1: VideoClipPreviewCache.Entry, e2: VideoClipPreviewCache.Entry) -> Bool {
return e1.clip === e2.clip && e1.time == e2.time;
}
| d5efd8b50abd611f091252f74103e5e3 | 27.198198 | 139 | 0.563259 | false | false | false | false |
urbanthings/urbanthings-sdk-apple | refs/heads/master | UrbanThingsAPI/Internal/JSON/UTColor+JSON.swift | apache-2.0 | 1 | //
// UTColor+JSON.swift
// UrbanThingsAPI
//
// Created by Mark Woollard on 01/05/2016.
// Copyright © 2016 UrbanThings. All rights reserved.
//
#if os(OSX)
import AppKit
public typealias UTColor = NSColor
#else
import UIKit
public typealias UTColor = UIColor
#endif
extension UTColor {
public class func fromJSON(required: Any?) throws -> UTColor {
guard let string = required as? String else {
throw UTAPIError(expected:String.self, not:required, file:#file, function:#function, line:#line)
}
guard let value = string.hexValue else {
throw UTAPIError(jsonParseError:"Invalid hex string \(string)", file:#file, function:#function, line:#line)
}
#if os(OSX)
return UTColor(deviceRed:CGFloat((value & 0xff0000) >> 16)/255.0,
green:CGFloat((value & 0xff00) >> 8)/255.0,
blue:CGFloat(value & 0xff)/255.0,
alpha:1.0)
#else
return UTColor(red:CGFloat((value & 0xff0000) >> 16)/255.0,
green:CGFloat((value & 0xff00) >> 8)/255.0,
blue:CGFloat(value & 0xff)/255.0,
alpha:1.0)
#endif
}
public class func fromJSON(optional: Any?) throws -> UTColor? {
guard let required = optional else {
return nil
}
return try UTColor.fromJSON(required:required)
}
}
| 943307ef795f772266a29c452ec7051b | 30.652174 | 119 | 0.572802 | false | false | false | false |
biohazardlover/NintendoEverything | refs/heads/master | Pods/SwiftSoup/Sources/Tag.swift | mit | 1 | //
// Tag.swift
// SwiftSoup
//
// Created by Nabil Chatbi on 15/10/16.
// Copyright © 2016 Nabil Chatbi.. All rights reserved.
//
import Foundation
open class Tag: Hashable {
// map of known tags
static var tags: Dictionary<String, Tag> = {
do {
return try Tag.initializeMaps()
} catch {
preconditionFailure("This method must be overridden")
}
return Dictionary<String, Tag>()
}()
fileprivate var _tagName: String
fileprivate var _tagNameNormal: String
fileprivate var _isBlock: Bool = true // block or inline
fileprivate var _formatAsBlock: Bool = true // should be formatted as a block
fileprivate var _canContainBlock: Bool = true // Can this tag hold block level tags?
fileprivate var _canContainInline: Bool = true // only pcdata if not
fileprivate var _empty: Bool = false // can hold nothing e.g. img
fileprivate var _selfClosing: Bool = false // can self close (<foo />). used for unknown tags that self close, without forcing them as empty.
fileprivate var _preserveWhitespace: Bool = false // for pre, textarea, script etc
fileprivate var _formList: Bool = false // a control that appears in forms: input, textarea, output etc
fileprivate var _formSubmit: Bool = false // a control that can be submitted in a form: input etc
public init(_ tagName: String) {
self._tagName = tagName
self._tagNameNormal = tagName.lowercased()
}
/**
* Get this tag's name.
*
* @return the tag's name
*/
open func getName() -> String {
return self._tagName
}
open func getNameNormal() -> String {
return self._tagNameNormal
}
/**
* Get a Tag by name. If not previously defined (unknown), returns a new generic tag, that can do anything.
* <p>
* Pre-defined tags (P, DIV etc) will be ==, but unknown tags are not registered and will only .equals().
* </p>
*
* @param tagName Name of tag, e.g. "p". Case insensitive.
* @param settings used to control tag name sensitivity
* @return The tag, either defined or new generic.
*/
open static func valueOf(_ tagName: String, _ settings: ParseSettings)throws->Tag {
var tagName = tagName
var tag: Tag? = Tag.tags[tagName]
if (tag == nil) {
tagName = settings.normalizeTag(tagName)
try Validate.notEmpty(string: tagName)
tag = Tag.tags[tagName]
if (tag == nil) {
// not defined: create default; go anywhere, do anything! (incl be inside a <p>)
tag = Tag(tagName)
tag!._isBlock = false
tag!._canContainBlock = true
}
}
return tag!
}
/**
* Get a Tag by name. If not previously defined (unknown), returns a new generic tag, that can do anything.
* <p>
* Pre-defined tags (P, DIV etc) will be ==, but unknown tags are not registered and will only .equals().
* </p>
*
* @param tagName Name of tag, e.g. "p". <b>Case sensitive</b>.
* @return The tag, either defined or new generic.
*/
open static func valueOf(_ tagName: String)throws->Tag {
return try valueOf(tagName, ParseSettings.preserveCase)
}
/**
* Gets if this is a block tag.
*
* @return if block tag
*/
open func isBlock() -> Bool {
return _isBlock
}
/**
* Gets if this tag should be formatted as a block (or as inline)
*
* @return if should be formatted as block or inline
*/
open func formatAsBlock() -> Bool {
return _formatAsBlock
}
/**
* Gets if this tag can contain block tags.
*
* @return if tag can contain block tags
*/
open func canContainBlock() -> Bool {
return _canContainBlock
}
/**
* Gets if this tag is an inline tag.
*
* @return if this tag is an inline tag.
*/
open func isInline() -> Bool {
return !_isBlock
}
/**
* Gets if this tag is a data only tag.
*
* @return if this tag is a data only tag
*/
open func isData() -> Bool {
return !_canContainInline && !isEmpty()
}
/**
* Get if this is an empty tag
*
* @return if this is an empty tag
*/
open func isEmpty() -> Bool {
return _empty
}
/**
* Get if this tag is self closing.
*
* @return if this tag should be output as self closing.
*/
open func isSelfClosing() -> Bool {
return _empty || _selfClosing
}
/**
* Get if this is a pre-defined tag, or was auto created on parsing.
*
* @return if a known tag
*/
open func isKnownTag() -> Bool {
return Tag.tags[_tagName] != nil
}
/**
* Check if this tagname is a known tag.
*
* @param tagName name of tag
* @return if known HTML tag
*/
open static func isKnownTag(_ tagName: String) -> Bool {
return Tag.tags[tagName] != nil
}
/**
* Get if this tag should preserve whitespace within child text nodes.
*
* @return if preserve whitepace
*/
public func preserveWhitespace() -> Bool {
return _preserveWhitespace
}
/**
* Get if this tag represents a control associated with a form. E.g. input, textarea, output
* @return if associated with a form
*/
public func isFormListed() -> Bool {
return _formList
}
/**
* Get if this tag represents an element that should be submitted with a form. E.g. input, option
* @return if submittable with a form
*/
public func isFormSubmittable() -> Bool {
return _formSubmit
}
@discardableResult
func setSelfClosing() -> Tag {
_selfClosing = true
return self
}
/// Returns a Boolean value indicating whether two values are equal.
///
/// Equality is the inverse of inequality. For any values `a` and `b`,
/// `a == b` implies that `a != b` is `false`.
///
/// - Parameters:
/// - lhs: A value to compare.
/// - rhs: Another value to compare.
static public func ==(lhs: Tag, rhs: Tag) -> Bool {
let this = lhs
let o = rhs
if (this === o) {return true}
if (type(of:this) != type(of:o)) {return false}
let tag: Tag = o
if (lhs._tagName != tag._tagName) {return false}
if (lhs._canContainBlock != tag._canContainBlock) {return false}
if (lhs._canContainInline != tag._canContainInline) {return false}
if (lhs._empty != tag._empty) {return false}
if (lhs._formatAsBlock != tag._formatAsBlock) {return false}
if (lhs._isBlock != tag._isBlock) {return false}
if (lhs._preserveWhitespace != tag._preserveWhitespace) {return false}
if (lhs._selfClosing != tag._selfClosing) {return false}
if (lhs._formList != tag._formList) {return false}
return lhs._formSubmit == tag._formSubmit
}
public func equals(_ tag: Tag) -> Bool {
return self == tag
}
/// The hash value.
///
/// Hash values are not guaranteed to be equal across different executions of
/// your program. Do not save hash values to use during a future execution.
public var hashValue: Int {
return _tagName.hashValue ^ _isBlock.hashValue ^ _formatAsBlock.hashValue ^ _canContainBlock.hashValue ^ _canContainInline.hashValue ^ _empty.hashValue ^ _selfClosing.hashValue ^ _preserveWhitespace.hashValue ^ _formList.hashValue ^ _formSubmit.hashValue
}
open func toString() -> String {
return _tagName
}
// internal static initialisers:
// prepped from http://www.w3.org/TR/REC-html40/sgml/dtd.html and other sources
private static let blockTags: [String] = [
"html", "head", "body", "frameset", "script", "noscript", "style", "meta", "link", "title", "frame",
"noframes", "section", "nav", "aside", "hgroup", "header", "footer", "p", "h1", "h2", "h3", "h4", "h5", "h6",
"ul", "ol", "pre", "div", "blockquote", "hr", "address", "figure", "figcaption", "form", "fieldset", "ins",
"del", "s", "dl", "dt", "dd", "li", "table", "caption", "thead", "tfoot", "tbody", "colgroup", "col", "tr", "th",
"td", "video", "audio", "canvas", "details", "menu", "plaintext", "template", "article", "main",
"svg", "math"
]
private static let inlineTags: [String] = [
"object", "base", "font", "tt", "i", "b", "u", "big", "small", "em", "strong", "dfn", "code", "samp", "kbd",
"var", "cite", "abbr", "time", "acronym", "mark", "ruby", "rt", "rp", "a", "img", "br", "wbr", "map", "q",
"sub", "sup", "bdo", "iframe", "embed", "span", "input", "select", "textarea", "label", "button", "optgroup",
"option", "legend", "datalist", "keygen", "output", "progress", "meter", "area", "param", "source", "track",
"summary", "command", "device", "area", "basefont", "bgsound", "menuitem", "param", "source", "track",
"data", "bdi"
]
private static let emptyTags: [String] = [
"meta", "link", "base", "frame", "img", "br", "wbr", "embed", "hr", "input", "keygen", "col", "command",
"device", "area", "basefont", "bgsound", "menuitem", "param", "source", "track"
]
private static let formatAsInlineTags: [String] = [
"title", "a", "p", "h1", "h2", "h3", "h4", "h5", "h6", "pre", "address", "li", "th", "td", "script", "style",
"ins", "del", "s"
]
private static let preserveWhitespaceTags: [String] = [
"pre", "plaintext", "title", "textarea"
// script is not here as it is a data node, which always preserve whitespace
]
// todo: I think we just need submit tags, and can scrub listed
private static let formListedTags: [String] = [
"button", "fieldset", "input", "keygen", "object", "output", "select", "textarea"
]
private static let formSubmitTags: [String] = [
"input", "keygen", "object", "select", "textarea"
]
static private func initializeMaps()throws->Dictionary<String, Tag> {
var dict = Dictionary<String, Tag>()
// creates
for tagName in blockTags {
let tag = Tag(tagName)
dict[tag._tagName] = tag
}
for tagName in inlineTags {
let tag = Tag(tagName)
tag._isBlock = false
tag._canContainBlock = false
tag._formatAsBlock = false
dict[tag._tagName] = tag
}
// mods:
for tagName in emptyTags {
let tag = dict[tagName]
try Validate.notNull(obj: tag)
tag?._canContainBlock = false
tag?._canContainInline = false
tag?._empty = true
}
for tagName in formatAsInlineTags {
let tag = dict[tagName]
try Validate.notNull(obj: tag)
tag?._formatAsBlock = false
}
for tagName in preserveWhitespaceTags {
let tag = dict[tagName]
try Validate.notNull(obj: tag)
tag?._preserveWhitespace = true
}
for tagName in formListedTags {
let tag = dict[tagName]
try Validate.notNull(obj: tag)
tag?._formList = true
}
for tagName in formSubmitTags {
let tag = dict[tagName]
try Validate.notNull(obj: tag)
tag?._formSubmit = true
}
return dict
}
}
| f5adb1e239823100a2aafac62b33935c | 33.284024 | 262 | 0.570331 | false | false | false | false |
TakeScoop/SwiftyRSA | refs/heads/master | Pods/SwiftyRSA/Source/Asn1Parser.swift | mit | 2 | //
// Asn1Parser.swift
// SwiftyRSA
//
// Created by Lois Di Qual on 5/9/17.
// Copyright © 2017 Scoop. All rights reserved.
//
import Foundation
/// Simple data scanner that consumes bytes from a raw data and keeps an updated position.
private class Scanner {
enum ScannerError: Error {
case outOfBounds
}
let data: Data
var index: Int = 0
/// Returns whether there is no more data to consume
var isComplete: Bool {
return index >= data.count
}
/// Creates a scanner with provided data
///
/// - Parameter data: Data to consume
init(data: Data) {
self.data = data
}
/// Consumes data of provided length and returns it
///
/// - Parameter length: length of the data to consume
/// - Returns: data consumed
/// - Throws: ScannerError.outOfBounds error if asked to consume too many bytes
func consume(length: Int) throws -> Data {
guard length > 0 else {
return Data()
}
guard index + length <= data.count else {
throw ScannerError.outOfBounds
}
let subdata = data.subdata(in: index..<index + length)
index += length
return subdata
}
/// Consumes a primitive, definite ASN1 length and returns its value.
///
/// See http://luca.ntop.org/Teaching/Appunti/asn1.html,
///
/// - Short form. One octet. Bit 8 has value "0" and bits 7-1 give the length.
/// - Long form. Two to 127 octets. Bit 8 of first octet has value "1" and
/// bits 7-1 give the number of additional length octets.
/// Second and following octets give the length, base 256, most significant digit first.
///
/// - Returns: Length that was consumed
/// - Throws: ScannerError.outOfBounds error if asked to consume too many bytes
func consumeLength() throws -> Int {
let lengthByte = try consume(length: 1).firstByte
// If the first byte's value is less than 0x80, it directly contains the length
// so we can return it
guard lengthByte >= 0x80 else {
return Int(lengthByte)
}
// If the first byte's value is more than 0x80, it indicates how many following bytes
// will describe the length. For instance, 0x85 indicates that 0x85 - 0x80 = 0x05 = 5
// bytes will describe the length, so we need to read the 5 next bytes and get their integer
// value to determine the length.
let nextByteCount = lengthByte - 0x80
let length = try consume(length: Int(nextByteCount))
return length.integer
}
}
private extension Data {
/// Returns the first byte of the current data
var firstByte: UInt8 {
var byte: UInt8 = 0
copyBytes(to: &byte, count: MemoryLayout<UInt8>.size)
return byte
}
/// Returns the integer value of the current data.
/// @warning: this only supports data up to 4 bytes, as we can only extract 32-bit integers.
var integer: Int {
guard count > 0 else {
return 0
}
var int: UInt32 = 0
var offset: Int32 = Int32(count - 1)
forEach { byte in
let byte32 = UInt32(byte)
let shifted = byte32 << (UInt32(offset) * 8)
int = int | shifted
offset -= 1
}
return Int(int)
}
}
/// A simple ASN1 parser that will recursively iterate over a root node and return a Node tree.
/// The root node can be any of the supported nodes described in `Node`. If the parser encounters a sequence
/// it will recursively parse its children.
enum Asn1Parser {
/// An ASN1 node
enum Node {
case sequence(nodes: [Node])
case integer(data: Data)
case objectIdentifier(data: Data)
case null
case bitString(data: Data)
case octetString(data: Data)
}
enum ParserError: Error {
case noType
case invalidType(value: UInt8)
}
/// Parses ASN1 data and returns its root node.
///
/// - Parameter data: ASN1 data to parse
/// - Returns: Root ASN1 Node
/// - Throws: A ParserError if anything goes wrong, or if an unknown node was encountered
static func parse(data: Data) throws -> Node {
let scanner = Scanner(data: data)
let node = try parseNode(scanner: scanner)
return node
}
/// Parses an ASN1 given an existing scanne.
/// @warning: this will modify the state (ie: position) of the provided scanner.
///
/// - Parameter scanner: Scanner to use to consume the data
/// - Returns: Parsed node
/// - Throws: A ParserError if anything goes wrong, or if an unknown node was encountered
private static func parseNode(scanner: Scanner) throws -> Node {
let firstByte = try scanner.consume(length: 1).firstByte
// Sequence
if firstByte == 0x30 {
let length = try scanner.consumeLength()
let data = try scanner.consume(length: length)
let nodes = try parseSequence(data: data)
return .sequence(nodes: nodes)
}
// Integer
if firstByte == 0x02 {
let length = try scanner.consumeLength()
let data = try scanner.consume(length: length)
return .integer(data: data)
}
// Object identifier
if firstByte == 0x06 {
let length = try scanner.consumeLength()
let data = try scanner.consume(length: length)
return .objectIdentifier(data: data)
}
// Null
if firstByte == 0x05 {
_ = try scanner.consume(length: 1)
return .null
}
// Bit String
if firstByte == 0x03 {
let length = try scanner.consumeLength()
// There's an extra byte (0x00) after the bit string length in all the keys I've encountered.
// I couldn't find a specification that referenced this extra byte, but let's consume it and discard it.
_ = try scanner.consume(length: 1)
let data = try scanner.consume(length: length - 1)
return .bitString(data: data)
}
// Octet String
if firstByte == 0x04 {
let length = try scanner.consumeLength()
let data = try scanner.consume(length: length)
return .octetString(data: data)
}
throw ParserError.invalidType(value: firstByte)
}
/// Parses an ASN1 sequence and returns its child nodes
///
/// - Parameter data: ASN1 data
/// - Returns: A list of ASN1 nodes
/// - Throws: A ParserError if anything goes wrong, or if an unknown node was encountered
private static func parseSequence(data: Data) throws -> [Node] {
let scanner = Scanner(data: data)
var nodes: [Node] = []
while !scanner.isComplete {
let node = try parseNode(scanner: scanner)
nodes.append(node)
}
return nodes
}
}
| 63d2f418acc0fa5d78c651424f3e69d6 | 31.909091 | 116 | 0.583287 | false | false | false | false |
Miridescen/M_365key | refs/heads/master | 365KEY_swift/365KEY_swift/extension/commomClass.swift | apache-2.0 | 1 | //
// commomClass.swift
// 365KEY_swift
//
// Created by 牟松 on 2016/11/7.
// Copyright © 2016年 DoNews. All rights reserved.
//
import Foundation
import UIKit
// 沙盒路径
let SKDocumentFilePath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first
// 存储登录的用户信息的路径
let SKUserSharedFilePath = (SKDocumentFilePath! as NSString).appendingPathComponent("userShared.json")
// -------------------------------------------------------------------------------------
// 屏幕宽
let SKScreenWidth = UIScreen.main.screenWidth
// 屏幕高
let SKScreenHeight = UIScreen.main.screenHeight
// 主题色
let SKMainColor = UIColor().mainColor
// 通知 -----------------------------------------------------------------------------------------
// 用户登录成功通知
let SKUserLoginSuccessNotifiction = "SKUserLoginSuccessNotifiction"
// 当前没有用户登录通知,用于弹出登录界面(接收到该通知时需要弹出登录界面)
let SKNoUserLoginNotifiction = "SKNoUserLoginNotifiction"
// 用户退出登录通知
let SKUserLogoutNotifiction = "SKUserLogoutNotifiction"
// 友盟 -------------------------------------------------------------------------------------
// 友盟分享appkey
let SKUmengAppkey = "56a5cb6b67e58efe070012bc"
// 友盟推送Scret
let SKUmengPushScret = "woilje10dvrdwrttdzuaem02znmqhcgu"
// --------------------------------------------------------------------------------------------
// 根据给定的宽,字体大小和内容,给出label的大小
func SKLabelSizeWith(labelText: String, font: UIFont = UIFont.systemFont(ofSize: 17), width: CGFloat) -> CGSize {
let attrs = [NSFontAttributeName: font]
let cString = NSString(cString: labelText.cString(using: String.Encoding.utf8)!, encoding: String.Encoding.utf8.rawValue)
return (cString?.boundingRect(with: CGSize(width: width, height: CGFloat(MAXFLOAT)), options: NSStringDrawingOptions.usesLineFragmentOrigin, attributes: attrs, context: nil).size)!
}
func SKlabelSizeWith(labelText: String, font: UIFont = UIFont.systemFont(ofSize: 17)) -> CGSize {
let attrs = [NSFontAttributeName: font]
let cString = NSString(cString: labelText.cString(using: String.Encoding.utf8)!, encoding: String.Encoding.utf8.rawValue)
return (cString?.boundingRect(with: CGSize(width: CGFloat(MAXFLOAT), height: CGFloat(MAXFLOAT)), options: NSStringDrawingOptions.usesLineFragmentOrigin, attributes: attrs, context: nil).size)!
}
| 7bbc0ef91975306821cb240065317899 | 38.067797 | 196 | 0.649024 | false | false | false | false |
WLChopSticks/weibo-swift- | refs/heads/master | weibo(swift)/weibo(swift)/Classes/Tools/NetworkTool.swift | mit | 2 |
//
// NetworkTool.swift
// weibo(swift)
//
// Created by 王 on 15/12/21.
// Copyright © 2015年 王. All rights reserved.
//
import AFNetworking
let dataErrorDomain = "com.baidu.data.error"
enum HTTPMethod: String {
case GET = "GET"
case POST = "POST"
}
class NetworkTool: AFHTTPSessionManager {
//设置一个单例
static let sharedTool: NetworkTool = {
let urlString = "https://api.weibo.com/"
let url = NSURL(string: urlString)
let share = NetworkTool(baseURL: url)
//添加请求支持类型
share.responseSerializer.acceptableContentTypes?.insert("text/plain")
return share
}()
//封装请求方法
func requestJSONDict(method: HTTPMethod, urlString: String, parameters: [String: String]?, finish: (dic: [String: AnyObject]?, error: NSError?) ->()) {
if method == HTTPMethod.POST {
POST(urlString, parameters: parameters, success: { (_, result) -> Void in
// print(result)
guard let dic = result as? [String: AnyObject] else {
//设置出错信息
let myError = NSError(domain: dataErrorDomain, code: -10000, userInfo: [NSLocalizedDescriptionKey : "数据不合法"])
print(myError)
finish(dic: nil, error: myError)
return
}
finish(dic: dic, error: nil)
}) { (_, error) -> Void in
print(error)
}
} else {
GET(urlString, parameters: parameters, success: { (_, result) -> Void in
guard let dic = result as? [String: AnyObject] else {
//设置出错信息
let myError = NSError(domain: dataErrorDomain, code: -10000, userInfo: [NSLocalizedDescriptionKey : "数据不合法"])
print(myError)
finish(dic: nil, error: myError)
return
}
finish(dic: dic, error: nil)
}) { (_, error) -> Void in
print(error)
}
}
}
// func uploadImage(urlString: String,parameters:[String : String]?,imageData: NSData, finished: (dict: [String : AnyObject]?, error: NSError?) -> ()) {
//
// POST(urlString, parameters: parameters, constructingBodyWithBlock: { (formData) -> Void in
// //将图片的二进制数据添加formData中
// /**
// * data 需要上传的文件的二进制数据
// name: 服务器接收上传文件的需要对应字段
// fileName: 服务器存储的名称 随便取 新浪微博 会自己去更改名字
// mimeType: 上传的文件的类型
// */
// formData.appendPartWithFileData(imageData, name: "pic", fileName: "xxoo", mimeType: "image/jpeg")
// }, progress: { (p) -> Void in
// print(p)
// }, success: { (_, result) -> Void in
// //上传成功
// print(result)
// if let dict = result as? [String : AnyObject] {
// finished(dict: dict, error: nil)
// }
//
// }) { (_, error) -> Void in
// //上传失败
// finished(dict: nil, error: error)
// print(error)
// }
// }
func uploadImage(urlString: String, parameters: [String:String]?,imageData: NSData, finish: (dic: [String:AnyObject]?, error: NSError?) -> ()) {
POST(urlString, parameters: parameters, constructingBodyWithBlock: { (formData) -> Void in
//将图片的二进制数据添加formData中
/**
* data 需要上传的文件的二进制数据
name: 服务器接收上传文件的需要对应字段
fileName: 服务器存储的名称 随便取 新浪微博 会自己去更改名字
mimeType: 上传的文件的类型
*/
formData.appendPartWithFileData(imageData, name: "pic", fileName: "xxoo", mimeType: "image/jpeg")
}, success: { (_, result) -> Void in
//上传成功
print(result)
if let dict = result as? [String : AnyObject] {
finish(dic: dict, error: nil)
}
}) { (_, error) -> Void in
//上传失败
finish(dic: nil, error: error)
print(error)
}
// POST(urlString, parameters: parameters, constructingBodyWithBlock: { (formData) -> Void in
//// POST(urlString, parameters: parameters, constructingBodyWithBlock: { (formData) -> Void in
//// formData.appendPartWithFileData(imageData, name: "pic", fileName: "hehe", mimeType: "image/jpeg")
// formData.appendPartWithFileData(imageData, name: "pic", fileName: "xxoo", mimeType: "image/jpeg")
// }, success: { (_, result) -> Void in
// guard let dic = result as? [String: AnyObject] else {
// //设置出错信息
// let myError = NSError(domain: dataErrorDomain, code: -10000, userInfo: [NSLocalizedDescriptionKey : "数据不合法"])
// print(myError)
//
// finish(dic: nil, error: myError)
//
// return
// }
// finish(dic: dic, error: nil)
// }) { (_, error) -> Void in
// print(error)
// }
}
}
| 0d47cfde9890700b93ec8933f6bf4b99 | 34.68 | 155 | 0.488416 | false | false | false | false |
CeranPaul/SketchCurves | refs/heads/master | SketchGenTests/ArcTests.swift | apache-2.0 | 1 | //
// ArcTests.swift
// SketchCurves
//
// Created by Paul on 11/12/15.
// Copyright © 2018 Ceran Digital Media. All rights reserved. See LICENSE.md
//
import XCTest
class ArcTests: XCTestCase {
/// Tests the simple parts for one of the inits
func testFidelityThreePoints() {
let sun = Point3D(x: 3.5, y: 6.0, z: 0.0)
let earth = Point3D(x: 5.5, y: 6.0, z: 0.0)
let atlantis = Point3D(x: 3.5, y: 8.0, z: 0.0)
var orbit = try! Arc(center: sun, end1: earth, end2: atlantis, useSmallAngle: false)
XCTAssert(orbit.getCenter() == sun)
XCTAssert(orbit.getOneEnd() == earth)
XCTAssert(orbit.getOtherEnd() == atlantis)
XCTAssertFalse(orbit.isFull)
XCTAssertEqual(orbit.getSweepAngle(), 3.0 * Double.pi / -2.0, accuracy: 0.0001)
var target = 2.0
XCTAssertEqual(orbit.getRadius(), target, accuracy: 0.0001)
orbit = try! Arc(center: sun, end1: earth, end2: atlantis, useSmallAngle: true)
XCTAssertEqual(orbit.getSweepAngle(), Double.pi / 2.0, accuracy: 0.0001)
// Detect an ArcPointsError from duplicate points by bad referencing
do {
let ctr = Point3D(x: 2.0, y: 1.0, z: 5.0)
// let e1 = Point3D(x: 3.0, y: 1.0, z: 5.0)
let e2 = Point3D(x: 2.0, y: 2.0, z: 5.0)
// Bad referencing should cause an error to be thrown
let _ = try Arc(center: ctr, end1: e2, end2: ctr, useSmallAngle: false)
} catch is ArcPointsError {
XCTAssert(true)
} catch { // This code will never get run
XCTAssert(false)
}
// Detect non-equidistant points
do {
let ctr = Point3D(x: 2.0, y: 1.0, z: 5.0)
let e1 = Point3D(x: 3.0, y: 1.0, z: 5.0)
let e2 = Point3D(x: 2.0, y: 2.5, z: 5.0)
// Bad point separation should cause an error to be thrown
let _ = try Arc(center: ctr, end1: e1, end2: e2, useSmallAngle: false)
} catch is ArcPointsError {
XCTAssert(true)
} catch { // This code will never get run
XCTAssert(false)
}
// Detect collinear points
do {
let ctr = Point3D(x: 2.0, y: 1.0, z: 5.0)
let e1 = Point3D(x: 3.0, y: 1.0, z: 5.0)
let e2 = Point3D(x: 1.0, y: 1.0, z: 5.0)
// Points all on a line should cause an error to be thrown
let _ = try Arc(center: ctr, end1: e1, end2: e2, useSmallAngle: false)
} catch is ArcPointsError {
XCTAssert(true)
} catch { // This code will never get run
XCTAssert(false)
}
// Check that sweep angles get generated correctly
/// Convenient values
let sqrt22 = sqrt(2.0) / 2.0
let sqrt32 = sqrt(3.0) / 2.0
let earth44 = Point3D(x: 3.5 + 2.0 * sqrt32, y: 6.0 + 2.0 * 0.5, z: 0.0)
// High to high
let season = try! Arc(center: sun, end1: earth44, end2: atlantis, useSmallAngle: true)
target = 1.0 * Double.pi / 3.0
let theta = season.getSweepAngle()
XCTAssertEqual(theta, target, accuracy: 0.001)
// High to high complement
let season3 = try! Arc(center: sun, end1: earth44, end2: atlantis, useSmallAngle: false)
let target3 = -1.0 * (2.0 * Double.pi - target)
let theta3 = season3.getSweepAngle()
XCTAssertEqual(theta3, target3, accuracy: 0.001)
// Low to high
let earth2 = Point3D(x: 3.5 + 2.0 * sqrt32, y: 6.0 - 2.0 * 0.5, z: 0.0)
let season2 = try! Arc(center: sun, end1: earth2, end2: atlantis, useSmallAngle: true)
let target2 = 2.0 * Double.pi / 3.0
let theta2 = season2.getSweepAngle()
XCTAssertEqual(theta2, target2, accuracy: 0.001)
// Low to high complement
let season4 = try! Arc(center: sun, end1: earth2, end2: atlantis, useSmallAngle: false)
let target4 = -1.0 * (2.0 * Double.pi - target2)
let theta4 = season4.getSweepAngle()
XCTAssertEqual(theta4, target4, accuracy: 0.001)
// High to low
let earth3 = Point3D(x: 3.5 + 2.0 * sqrt32, y: 6.0 + 2.0 * 0.5, z: 0.0)
let atlantis5 = Point3D(x: 3.5 - 2.0 * sqrt22, y: 6.0 - 2.0 * sqrt22, z: 0.0)
let season5 = try! Arc(center: sun, end1: earth3, end2: atlantis5, useSmallAngle: false)
let target5 = -13.0 * Double.pi / 12.0
let theta5 = season5.getSweepAngle()
XCTAssertEqual(theta5, target5, accuracy: 0.001)
// High to low complement
let season6 = try! Arc(center: sun, end1: earth3, end2: atlantis5, useSmallAngle: true)
let target6 = 11.0 * Double.pi / 12.0
let theta6 = season6.getSweepAngle()
XCTAssertEqual(theta6, target6, accuracy: 0.001)
// Low to low
let season7 = try! Arc(center: sun, end1: earth2, end2: atlantis5, useSmallAngle: false)
let target7 = -17.0 * Double.pi / 12.0
let theta7 = season7.getSweepAngle()
XCTAssertEqual(theta7, target7, accuracy: 0.001)
let season8 = try! Arc(center: sun, end1: earth2, end2: atlantis5, useSmallAngle: true)
// Low to low complement
let target8 = 7.0 * Double.pi / 12.0
let theta8 = season8.getSweepAngle()
XCTAssertEqual(theta8, target8, accuracy: 0.001)
// Check generation of the axis
let c1 = Point3D(x: 0.9, y: -1.21, z: 3.5)
let s1 = Point3D(x: 0.9, y: -1.21 + sqrt32, z: 3.5 + 0.5)
let f1 = Point3D(x: 0.9, y: -1.21, z: 3.5 + 1.0)
let slice = try! Arc(center: c1, end1: s1, end2: f1, useSmallAngle: false)
let target9 = Vector3D(i: 1.0, j: 0.0, k: 0.0)
let trial = slice.getAxisDir()
XCTAssertEqual(trial, target9)
}
/// Test the second initializer
func testFidelityCASS() {
let sun = Point3D(x: 3.5, y: 6.0, z: 0.0)
let earth = Point3D(x: 5.5, y: 6.0, z: 0.0)
let solarSystemUp = Vector3D(i: 0.0, j: 0.0, k: 1.0)
let fourMonths = 2.0 * Double.pi / 3.0
var orbit = try! Arc(center: sun, axis: solarSystemUp, end1: earth, sweep: fourMonths)
var target = 2.0
XCTAssertEqual(orbit.getRadius(), target, accuracy: 0.0001)
XCTAssertFalse(orbit.isFull)
/// A handy value when checking points at angles
let sqrt32 = sqrt(3.0) / 2.0
target = 3.5 - 2.0 * 0.5
XCTAssertEqual(orbit.getOtherEnd().x, target, accuracy: Point3D.Epsilon)
target = 6.0 + 2.0 * sqrt32
XCTAssertEqual(orbit.getOtherEnd().y, target, accuracy: Point3D.Epsilon)
orbit = try! Arc(center: sun, axis: solarSystemUp, end1: earth, sweep: 2.0 * Double.pi)
XCTAssert(orbit.isFull)
do {
let solarSystemUp2 = Vector3D(i: 0.0, j: 0.0, k: 0.0)
orbit = try Arc(center: sun, axis: solarSystemUp2, end1: earth, sweep: 2.0 * Double.pi)
} catch is ZeroVectorError {
XCTAssert(true)
} catch {
XCTAssert(false, "Code should never have gotten here")
}
do {
let solarSystemUp2 = Vector3D(i: 0.0, j: 0.0, k: 0.5)
orbit = try Arc(center: sun, axis: solarSystemUp2, end1: earth, sweep: 2.0 * Double.pi)
} catch is NonUnitDirectionError {
XCTAssert(true)
} catch {
XCTAssert(false, "Code should never have gotten here")
}
do {
let earth2 = Point3D(x: 3.5, y: 6.0, z: 0.0)
orbit = try Arc(center: sun, axis: solarSystemUp, end1: earth2, sweep: 2.0 * Double.pi)
} catch is CoincidentPointsError {
XCTAssert(true)
} catch {
XCTAssert(false, "Code should never have gotten here")
}
do {
orbit = try Arc(center: sun, axis: solarSystemUp, end1: earth, sweep: 0.0)
} catch is ZeroSweepError {
XCTAssert(true)
} catch {
XCTAssert(false, "Code should never have gotten here")
}
do {
let earth2 = Point3D(x: 3.5, y: 6.0, z: 4.0)
orbit = try Arc(center: sun, axis: solarSystemUp, end1: earth2, sweep: 2.0 * Double.pi)
} catch is NonOrthogonalPointError {
XCTAssert(true)
} catch {
XCTAssert(false, "Code should never have gotten here")
}
}
func testPointAt() {
let thumb = Point3D(x: 3.5, y: 6.0, z: 0.0)
let knuckle = Point3D(x: 5.5, y: 6.0, z: 0.0)
let tip = Point3D(x: 3.5, y: 8.0, z: 0.0)
do {
let grip = try Arc(center: thumb, end1: knuckle, end2: tip, useSmallAngle: true)
var spot = try! grip.pointAt(t: 0.5)
XCTAssert(spot.z == 0.0)
XCTAssert(spot.y == 6.0 + 2.squareRoot()) // This is bizarre notation, probably from a language level comparison.
XCTAssert(spot.x == 3.5 + 2.squareRoot())
spot = try! grip.pointAt(t: 0.0)
XCTAssert(spot.z == 0.0)
XCTAssert(spot.y == 6.0)
XCTAssert(spot.x == 3.5 + 2.0)
} catch {
print("Screwed up while testing a circle 7")
}
// Another start-at-zero case with a different check method
let ctr = Point3D(x: 10.5, y: 6.0, z: -1.2)
/// On the horizon
let green = Point3D(x: 11.8, y: 6.0, z: -1.2)
/// Noon sun
let checker = Point3D(x: 10.5, y: 7.3, z: -1.2)
let shoulder = try! Arc(center: ctr, end1: green, end2: checker, useSmallAngle: true)
var upRight = Vector3D(i: 1.0, j: 1.0, k: 0.0)
upRight.normalize()
/// Unit slope
let ray = try! Line(spot: ctr, arrow: upRight)
var plop = try! shoulder.pointAt(t: 0.5)
let flag1 = Line.isCoincident(straightA: ray, pip: plop)
XCTAssert(flag1)
// Clockwise sweep
let sunSetting = try! Arc(center: ctr, end1: checker, end2: green, useSmallAngle: true)
var clock = Vector3D(i: 0.866, j: 0.5, k: 0.0)
clock.normalize()
let ray2 = try! Line(spot: ctr, arrow: clock)
plop = try! sunSetting.pointAt(t: 0.666667)
XCTAssert(Line.isCoincident(straightA: ray2, pip: plop))
// TODO: Add tests in a non-XY plane
let sunSetting2 = try! Arc(center: ctr, end1: checker, end2: green, useSmallAngle: false)
var clock2 = Vector3D(i: 0.0, j: -1.0, k: 0.0)
clock2.normalize()
var ray3 = try! Line(spot: ctr, arrow: clock2)
plop = try! sunSetting2.pointAt(t: 0.666667)
XCTAssert(Line.isCoincident(straightA: ray3, pip: plop))
let countdown = try! Arc(center: ctr, end1: checker, end2: green, useSmallAngle: false)
clock = Vector3D(i: -1.0, j: 0.0, k: 0.0)
ray3 = try! Line(spot: ctr, arrow: clock)
plop = try! countdown.pointAt(t: 0.333333)
XCTAssert(Line.isCoincident(straightA: ray3, pip: plop))
}
func testReverse() {
let ctr = Point3D(x: 10.5, y: 6.0, z: -1.2)
let green = Point3D(x: 11.8, y: 6.0, z: -1.2)
let checker = Point3D(x: 10.5, y: 7.3, z: -1.2)
/// One quarter of a full circle - in quadrant I
let shoulder = try! Arc(center: ctr, end1: green, end2: checker, useSmallAngle: true)
XCTAssertEqual(Double.pi / 2.0, shoulder.getSweepAngle())
var clock1 = Vector3D(i: 0.5, j: 0.866, k: 0.0)
clock1.normalize()
let ray1 = try! Line(spot: ctr, arrow: clock1)
var plop = try! shoulder.pointAt(t: 0.666667)
XCTAssert(Line.isCoincident(straightA: ray1, pip: plop))
shoulder.reverse()
var clock2 = Vector3D(i: 0.866, j: 0.5, k: 0.0)
clock2.normalize()
let ray2 = try! Line(spot: ctr, arrow: clock2)
plop = try! shoulder.pointAt(t: 0.666667)
XCTAssert(Line.isCoincident(straightA: ray2, pip: plop))
}
func testEquals() {
let sun = Point3D(x: 3.5, y: 6.0, z: 0.0)
let earth = Point3D(x: 5.5, y: 6.0, z: 0.0)
let atlantis = Point3D(x: 3.5, y: 8.0, z: 0.0)
let betelgeuse = Point3D(x: 3.5, y: 6.0, z: 0.0)
let planetX = Point3D(x: 5.5, y: 6.0, z: 0.0)
let planetY = Point3D(x: 3.5, y: 8.0, z: 0.0)
let solarSystem1 = try! Arc(center: sun, end1: earth, end2: atlantis, useSmallAngle: false)
let solarSystem2 = try! Arc(center: betelgeuse, end1: planetX, end2: planetY, useSmallAngle: false)
XCTAssert(solarSystem1 == solarSystem2)
// Add tests to compare results from the different initializers
}
func testSetIntent() {
let sun = Point3D(x: 3.5, y: 6.0, z: 0.0)
let earth = Point3D(x: 5.5, y: 6.0, z: 0.0)
let atlantis = Point3D(x: 3.5, y: 8.0, z: 0.0)
let solarSystem1 = try! Arc(center: sun, end1: earth, end2: atlantis, useSmallAngle: false)
XCTAssert(solarSystem1.usage == PenTypes.ordinary)
solarSystem1.setIntent(purpose: PenTypes.ideal)
XCTAssert(solarSystem1.usage == PenTypes.ideal)
}
func testSimpleExtent() {
let axis = Vector3D(i: 0.0, j: 0.0, k: 1.0)
let ctr = Point3D(x: 2.0, y: 1.0, z: 5.0)
let e1 = Point3D(x: 4.5, y: 1.0, z: 5.0)
var theta = Double.pi / 4.0 + 0.15
var shield = try! Arc(center: ctr, axis: axis, end1: e1, sweep: theta)
var brick = shield.simpleExtent()
XCTAssertEqual(brick.getOrigin().x, shield.rad * cos(theta))
XCTAssertEqual(brick.getOrigin().y, 0.0)
XCTAssertEqual(brick.getOrigin().z, -shield.rad / 10.0)
XCTAssertEqual(brick.getWidth(), shield.rad * (1.0 - cos(theta)), accuracy: Point3D.Epsilon / 3.0)
XCTAssertEqual(brick.getHeight(), shield.rad * sin(theta), accuracy: Point3D.Epsilon / 3.0)
XCTAssertEqual(brick.getDepth(), shield.rad / 5.0)
// Push the angle into quadrant II
theta = Double.pi / 2.0 + 0.15
shield = try! Arc(center: ctr, axis: axis, end1: e1, sweep: theta)
brick = shield.simpleExtent()
XCTAssertEqual(brick.getOrigin().x, shield.rad * cos(theta), accuracy: Point3D.Epsilon / 3.0)
XCTAssertEqual(brick.getWidth(), shield.rad * (1.0 - cos(theta)), accuracy: Point3D.Epsilon / 3.0)
XCTAssertEqual(brick.getHeight(), shield.rad, accuracy: Point3D.Epsilon / 3.0)
// Push the angle into quadrant III
theta = Double.pi + 0.15
shield = try! Arc(center: ctr, axis: axis, end1: e1, sweep: theta)
brick = shield.simpleExtent()
XCTAssertEqual(brick.getOrigin().x, -shield.rad, accuracy: Point3D.Epsilon / 3.0)
XCTAssertEqual(brick.getWidth(), 2.0 * shield.rad, accuracy: Point3D.Epsilon / 3.0)
XCTAssertEqual(brick.getHeight(), shield.rad - shield.rad * sin(theta), accuracy: Point3D.Epsilon / 3.0)
// Push the angle into quadrant IV
theta = Double.pi * 3.0 / 2.0 + 0.15
shield = try! Arc(center: ctr, axis: axis, end1: e1, sweep: theta)
brick = shield.simpleExtent()
XCTAssertEqual(brick.getOrigin().x, -shield.rad, accuracy: Point3D.Epsilon / 3.0)
XCTAssertEqual(brick.getWidth(), 2.0 * shield.rad, accuracy: Point3D.Epsilon / 3.0)
XCTAssertEqual(brick.getHeight(), 2.0 * shield.rad, accuracy: Point3D.Epsilon / 3.0)
// Negative angle - quadrant IV
theta = -Double.pi / 2.0 + 0.15
shield = try! Arc(center: ctr, axis: axis, end1: e1, sweep: theta)
brick = shield.simpleExtent()
XCTAssertEqual(brick.getOrigin().x, shield.rad * cos(theta), accuracy: Point3D.Epsilon / 3.0)
XCTAssertEqual(brick.getOrigin().y, shield.rad * sin(theta), accuracy: Point3D.Epsilon / 3.0)
XCTAssertEqual(brick.getWidth(), shield.rad * (1.0 - cos(theta)), accuracy: Point3D.Epsilon / 3.0)
XCTAssertEqual(brick.getHeight(), -1.0 * shield.rad * sin(theta), accuracy: Point3D.Epsilon / 3.0)
// Negative angle - quadrant III
theta = -Double.pi + 0.15
shield = try! Arc(center: ctr, axis: axis, end1: e1, sweep: theta)
brick = shield.simpleExtent()
XCTAssertEqual(brick.getOrigin().x, shield.rad * cos(theta), accuracy: Point3D.Epsilon / 3.0)
XCTAssertEqual(brick.getOrigin().y, -shield.rad, accuracy: Point3D.Epsilon / 3.0)
XCTAssertEqual(brick.getWidth(), shield.rad * (1.0 - cos(theta)), accuracy: Point3D.Epsilon / 3.0)
XCTAssertEqual(brick.getHeight(), shield.rad, accuracy: Point3D.Epsilon / 3.0)
// Negative angle - quadrant II
theta = -Double.pi * 3.0 / 2.0 + 0.15
shield = try! Arc(center: ctr, axis: axis, end1: e1, sweep: theta)
brick = shield.simpleExtent()
XCTAssertEqual(brick.getOrigin().x, -shield.rad, accuracy: Point3D.Epsilon / 3.0)
XCTAssertEqual(brick.getOrigin().y, -shield.rad, accuracy: Point3D.Epsilon / 3.0)
XCTAssertEqual(brick.getWidth(), 2.0 * shield.rad, accuracy: Point3D.Epsilon / 3.0)
XCTAssertEqual(brick.getHeight(), shield.rad * (1.0 + sin(theta)), accuracy: Point3D.Epsilon / 3.0)
// Negative angle - quadrant I
theta = -Double.pi * 2.0 + 0.15
shield = try! Arc(center: ctr, axis: axis, end1: e1, sweep: theta)
brick = shield.simpleExtent()
XCTAssertEqual(brick.getOrigin().x, -shield.rad, accuracy: Point3D.Epsilon / 3.0)
XCTAssertEqual(brick.getOrigin().y, -shield.rad, accuracy: Point3D.Epsilon / 3.0)
XCTAssertEqual(brick.getWidth(), 2.0 * shield.rad, accuracy: Point3D.Epsilon / 3.0)
XCTAssertEqual(brick.getHeight(), 2.0 * shield.rad, accuracy: Point3D.Epsilon / 3.0)
}
func testExtent() {
let axis = Vector3D(i: 0.0, j: 0.0, k: 1.0)
let ctr = Point3D(x: 2.0, y: 1.0, z: 5.0)
let e1 = Point3D(x: 4.5, y: 1.0, z: 5.0)
let shield = try! Arc(center: ctr, axis: axis, end1: e1, sweep: Double.pi)
let box = shield.getExtent()
XCTAssertEqual(box.getOrigin().x, -0.5, accuracy: Point3D.Epsilon / 3.0)
XCTAssertEqual(box.getOrigin().y, 1.0, accuracy: Point3D.Epsilon / 3.0)
XCTAssertEqual(box.getOrigin().z, 5.0 - shield.rad / 10.0, accuracy: Point3D.Epsilon / 3.0)
XCTAssertEqual(box.getWidth(), 5.0, accuracy: Point3D.Epsilon / 3.0)
XCTAssertEqual(box.getHeight(), 2.5, accuracy: Point3D.Epsilon / 3.0)
let sqrt22 = sqrt(2.0) / 2.0
// Spin around Z-axis Gee, is a transform the way to handle the spin case!
// let e2 = Point3D(x: 2.0 + 3.0 * sqrt22, y: 1.0 + 3.0 * sqrt22, z: 5.0)
// let shield3 = try! Arc(center: ctr, axis: axis, end1: e2, sweep: Double.pi)
// let box3 = shield3.getExtent()
// XCTAssertEqual(box3.getOrigin().x, -0.5, accuracy: Point3D.Epsilon / 3.0)
// XCTAssertEqual(box3.getOrigin().y, 1.0, accuracy: Point3D.Epsilon / 3.0)
// XCTAssertEqual(box3.getOrigin().z, 5.0 - shield.rad / 10.0, accuracy: Point3D.Epsilon / 3.0)
//
// XCTAssertEqual(box3.getWidth(), 5.0, accuracy: Point3D.Epsilon / 3.0)
// XCTAssertEqual(box3.getHeight(), 2.5, accuracy: Point3D.Epsilon / 3.0)
// Tilt around the X-axis
var axis2 = Vector3D(i: 0.0, j: 0.707, k: 0.707)
axis2.normalize()
let shield2 = try! Arc(center: ctr, axis: axis2, end1: e1, sweep: Double.pi)
let box2 = shield2.getExtent()
XCTAssertEqual(box2.getOrigin().x, -0.5, accuracy: Point3D.Epsilon / 3.0)
XCTAssertEqual(box2.getWidth(), 5.0, accuracy: Point3D.Epsilon / 3.0)
XCTAssertEqual(box2.getHeight(), shield2.rad * (1.0 + 0.2) * sqrt22, accuracy: Point3D.Epsilon / 3.0)
}
}
| bd600f2606179aba640d7098a089c9d9 | 34.859247 | 127 | 0.526289 | false | false | false | false |
fastred/IBAnalyzer | refs/heads/master | IBAnalyzerTests/SwiftParserTests.swift | mit | 1 | //
// SwiftParserTests.swift
// IBAnalyzer
//
// Created by Arkadiusz Holko on 26-12-16.
// Copyright © 2016 Arkadiusz Holko. All rights reserved.
//
import XCTest
import SourceKittenFramework
@testable import IBAnalyzer
// swiftlint:disable line_length
class SwiftParserTests: XCTestCase {
func testViewControllerWithoutOutletsAndActions() {
let source = "class TestViewController: UIViewController { var button: UIButton!; func didTapButton(_ sender: UIButton) {} }"
let expected = Class(outlets: [], actions: [], inherited: ["UIViewController"])
XCTAssertEqual(mappingFor(contents: source), ["TestViewController": expected])
}
func testViewControllerWithOneOutlet() {
let source = "class TestViewController: UIViewController { @IBOutlet weak var button: UIButton! }"
let button = Declaration(name: "button", line: 1, column: 0)
let expected = Class(outlets: [button], actions: [], inherited: ["UIViewController"])
XCTAssertEqual(mappingFor(contents: source), ["TestViewController": expected])
}
func testNestedViewControllerWithOneOutlet() {
let source = "class Outer { class TestViewController: UIViewController { @IBOutlet weak var button: UIButton! }}"
let expectedOuter = Class(outlets: [], actions: [], inherited: [])
let button = Declaration(name: "button", line: 1, column: 0)
let expectedInner = Class(outlets: [button], actions: [], inherited: ["UIViewController"])
XCTAssertEqual(mappingFor(contents: source), ["Outer": expectedOuter,
"TestViewController": expectedInner])
}
func testViewControllerWithOneAction() {
let source = "class TestViewController: UIViewController { @IBAction func didTapButton(_ sender: UIButton) {} }"
let didTapButton = Declaration(name: "didTapButton:", line: 1, column: 0)
let expected = Class(outlets: [], actions: [didTapButton], inherited: ["UIViewController"])
XCTAssertEqual(mappingFor(contents: source), ["TestViewController": expected])
}
func testMultipleInheritance() {
let source = "class TestViewController: UIViewController, SomeProtocol { }"
let expected = Class(outlets: [], actions: [], inherited: ["UIViewController", "SomeProtocol"])
XCTAssertEqual(mappingFor(contents: source), ["TestViewController": expected])
}
func testViewControllerWithActionInExtension() {
let source = "class TestViewController: UIViewController {}; extension TestViewController { @IBAction func didTapButton(_ sender: UIButton) {} }"
let didTapButton = Declaration(name: "didTapButton:", line: 1, column: 0)
let expected = Class(outlets: [], actions: [didTapButton], inherited: ["UIViewController"])
XCTAssertEqual(mappingFor(contents: source), ["TestViewController": expected])
}
private func mappingFor(contents: String) -> [String: Class] {
let parser = SwiftParser()
var result: [String: Class] = [:]
do {
try parser.mappingForContents(contents, result: &result)
} catch let error {
XCTFail(error.localizedDescription)
}
return result
}
}
| c94194dfe73fd78dc09a101031ecdcbf | 43.534247 | 153 | 0.673331 | false | true | false | false |
RocketChat/Rocket.Chat.iOS | refs/heads/develop | Rocket.Chat/Models/Subscription/SubscriptionUtils.swift | mit | 1 | //
// SubscriptionUtils.swift
// Rocket.Chat
//
// Created by Matheus Cardoso on 3/1/18.
// Copyright © 2018 Rocket.Chat. All rights reserved.
//
import RealmSwift
extension Subscription {
func isValid() -> Bool {
return !self.rid.isEmpty
}
func isJoined() -> Bool {
return auth != nil || type != .channel
}
func fetchRoomIdentifier(_ completion: @escaping MessageCompletionObject <Subscription>) {
switch type {
case .channel: fetchChannelIdentifier(completion)
case .directMessage: fetchDirectMessageIdentifier(completion)
default: break
}
}
private func fetchChannelIdentifier(_ completion: @escaping MessageCompletionObject <Subscription>) {
guard let identifier = self.identifier else { return }
SubscriptionManager.getRoom(byName: name, completion: { (response) in
guard !response.isError() else { return }
guard let rid = response.result["result"]["_id"].string else { return }
let result = response.result["result"]
Realm.execute({ realm in
if let obj = Subscription.find(withIdentifier: identifier) {
obj.rid = rid
obj.update(result, realm: realm)
realm.add(obj, update: true)
}
}, completion: {
if let subscription = Subscription.find(rid: rid) {
completion(subscription)
}
})
})
}
private func fetchDirectMessageIdentifier(_ completion: @escaping MessageCompletionObject <Subscription>) {
guard let identifier = self.identifier else { return }
let name = self.name
SubscriptionManager.createDirectMessage(name, completion: { (response) in
guard !response.isError() else { return }
guard let rid = response.result["result"]["rid"].string else { return }
Realm.execute({ realm in
// We need to check for the existence of one Subscription
// here because another real time response may have
// already included this object into the database
// before this block is executed.
if let existingObject = Subscription.find(rid: rid, realm: realm) {
if let obj = Subscription.find(withIdentifier: identifier) {
realm.add(existingObject, update: true)
realm.delete(obj)
}
} else {
if let obj = Subscription.find(withIdentifier: identifier) {
obj.rid = rid
realm.add(obj, update: true)
}
}
}, completion: {
DispatchQueue.main.async {
if let subscription = Subscription.find(name: name) {
completion(subscription)
}
}
})
})
}
func fetchMessages(_ limit: Int = 20, lastMessageDate: Date? = nil, threadIdentifier: String? = nil) -> [Message] {
var limitedMessages: [Message] = []
guard var messages = fetchMessagesQueryResults() else { return [] }
if let lastMessageDate = lastMessageDate {
messages = messages.filter("createdAt < %@", lastMessageDate)
}
if let threadIdentifier = threadIdentifier {
messages = messages.filter("identifier == %@ OR threadMessageId == %@", threadIdentifier, threadIdentifier)
}
let totalMessagesIndexes = messages.count - 1
for index in 0..<limit {
let reversedIndex = totalMessagesIndexes - index
guard totalMessagesIndexes >= reversedIndex, reversedIndex >= 0 else {
return limitedMessages
}
limitedMessages.append(messages[reversedIndex])
}
return limitedMessages
}
func fetchMessagesQueryResults() -> Results<Message>? {
guard var filteredMessages = self.messages?.filter("identifier != NULL AND createdAt != NULL") else {
return nil
}
if let hiddenTypes = AuthSettingsManager.settings?.hiddenTypes {
for hiddenType in hiddenTypes {
filteredMessages = filteredMessages.filter("internalType != %@", hiddenType.rawValue)
}
}
return filteredMessages.sorted(byKeyPath: "createdAt", ascending: true)
}
func fetchMessagesQueryResultsFor(threadIdentifier: String) -> Results<Message>? {
return fetchMessagesQueryResults()?.filter("threadMessageId == %@", threadIdentifier)
}
func updateFavorite(_ favorite: Bool) {
Realm.executeOnMainThread({ _ in
self.favorite = favorite
})
}
}
// MARK: Failed Messages
extension Subscription {
func setTemporaryMessagesFailed(user: User? = AuthManager.currentUser()) {
guard let user = user else {
return
}
Realm.executeOnMainThread { realm in
self.messages?.filter("temporary = true").filter({
$0.user == user
}).forEach {
$0.temporary = false
$0.failed = true
realm.add($0, update: true)
}
}
}
}
| 19829ae8ba3c9711bed8c5eca88f844b | 33.082278 | 119 | 0.569731 | false | false | false | false |
vinnyoodles/DualSlideMenu | refs/heads/master | Example/Pods/DualSlideMenu/Pod/Classes/MainViewController.swift | mit | 1 | //
// MainViewController.swift
// Pods
//
// Created by Vincent Le on 3/23/16.
//
//
import UIKit
protocol MainViewControllerDelegate {
func toggle(swipeDirection: String)
func closeBothMenu()
}
class MainViewController: UIViewController {
//The connection between main vc and the container vc
var delegate: MainViewControllerDelegate?
override func viewDidLoad() {
super.viewDidLoad()
//add swipe recognizers
let leftSwipe = UISwipeGestureRecognizer(target: self, action: Selector("handleSwipes:"))
let rightSwipe = UISwipeGestureRecognizer(target: self, action: Selector("handleSwipes:"))
leftSwipe.direction = .Left
rightSwipe.direction = .Right
view.addGestureRecognizer(leftSwipe)
view.addGestureRecognizer(rightSwipe)
}
func handleSwipes(sender:UISwipeGestureRecognizer) {
if (sender.direction == .Left) {
print("left swipe")
delegate?.toggle("left")
}
else if (sender.direction == .Right){
print("right swipe")
delegate?.toggle("right")
}
}
}
| 1a4563e6ad83581f997c1649112a1ea7 | 25.883721 | 98 | 0.638408 | false | false | false | false |
Wzxhaha/Grimace | refs/heads/master | Grimace/Classes/Extension.swift | apache-2.0 | 1 | //
// Extension.swift
// Pods
//
// Created by wzxjiang on 2017/7/24.
//
//
import CoreMedia
extension CMSampleBuffer {
public func imageInfo() -> (data: Data, size: CGSize)? {
guard let buffer = CMSampleBufferGetImageBuffer(self) else {
return nil
}
CVPixelBufferLockBaseAddress(buffer, CVPixelBufferLockFlags(rawValue: 0))
let lumaBuffer = CVPixelBufferGetBaseAddressOfPlane(buffer, 0)
let bytesPerRow = CVPixelBufferGetBytesPerRowOfPlane(buffer, 0)
let width = CVPixelBufferGetWidth(buffer)
let height = CVPixelBufferGetHeight(buffer)
let grayColorSpace = CGColorSpaceCreateDeviceGray()
let context =
CGContext(
data: lumaBuffer,
width: width,
height: height,
bitsPerComponent: 8,
bytesPerRow: bytesPerRow,
space: grayColorSpace,
bitmapInfo: 0
)
var cgImage = context?.makeImage()
CVPixelBufferUnlockBaseAddress(buffer, CVPixelBufferLockFlags(rawValue: 0))
guard let data = cgImage?.dataProvider?.data else { return nil }
cgImage = nil
return (data as Data, CGSize(width: width, height: height))
}
}
| 3d6e9137e5175240950a18aecb566ed4 | 26.333333 | 84 | 0.56528 | false | false | false | false |
tavultesoft/keymanweb | refs/heads/master | ios/keyman/Keyman/Keyman/Classes/KMWebBrowser/WebBrowserViewController.swift | apache-2.0 | 1 | //
// WebBrowserViewController.swift
// Keyman
//
// Created by Gabriel Wong on 2017-09-05.
// Copyright © 2017 SIL International. All rights reserved.
//
import KeymanEngine
import UIKit
class WebBrowserViewController: UIViewController, UIWebViewDelegate, UIAlertViewDelegate {
@IBOutlet var webView: UIWebView!
@IBOutlet var navBar: UINavigationBar!
@IBOutlet var toolBar: UIToolbar!
@IBOutlet var navBarTopConstraint: NSLayoutConstraint!
private var addressField: UITextField!
private var rightView: UIView!
private var refreshButton: UIButton!
private var stopButton: UIButton!
@IBOutlet var backButton: UIBarButtonItem!
@IBOutlet var forwardButton: UIBarButtonItem!
@IBOutlet var bookmarksButton: UIBarButtonItem!
@IBOutlet var globeButton: UIBarButtonItem!
@IBOutlet var closeButton: UIBarButtonItem!
var navbarBackground: KMNavigationBarBackgroundView!
var fontFamily = UIFont.systemFont(ofSize: UIFont.systemFontSize).fontName
private var newFontFamily = ""
private let webBrowserLastURLKey = "KMWebBrowserLastURL"
private var keyboardChangedObserver: NotificationObserver?
private var keyboardPickerDismissedObserver: NotificationObserver?
convenience init() {
self.init(nibName: "WebBrowserViewController", bundle: nil)
}
override func viewDidLoad() {
super.viewDidLoad()
keyboardChangedObserver = NotificationCenter.default.addObserver(
forName: Notifications.keyboardChanged,
observer: self,
function: WebBrowserViewController.keyboardChanged)
keyboardPickerDismissedObserver = NotificationCenter.default.addObserver(
forName: Notifications.keyboardPickerDismissed,
observer: self,
function: WebBrowserViewController.keyboardPickerDismissed)
webView.delegate = self
webView.scalesPageToFit = true
if #available(iOS 13.0, *) {
// Dark mode settings must be applied through this new property,
// its class, and others like it.
navBar.standardAppearance.configureWithOpaqueBackground()
} else {
// Fallback on earlier versions
}
// Setup NavigationBar
navbarBackground = KMNavigationBarBackgroundView()
navbarBackground.hideLogo()
navbarBackground.addToNavbar(navBar)
navbarBackground.setOrientation(UIApplication.shared.statusBarOrientation)
// Setup address field
let addressFrame = CGRect(x: 10, y: 4.0, width: navBar.frame.size.width - 20, height: 28)
addressField = UITextField(frame: addressFrame)
addressField.clearButtonMode = .whileEditing
addressField.rightViewMode = .unlessEditing
addressField.autoresizingMask = .flexibleWidth
addressField.borderStyle = .roundedRect
addressField.autocapitalizationType = .none
addressField.autocorrectionType = .no
addressField.font = UIFont.systemFont(ofSize: 17)
addressField.placeholder = "http://"
addressField.text = ""
addressField.keyboardType = UIKeyboardType.URL
addressField.addTarget(self, action: #selector(self.loadAddress), for: .editingDidEndOnExit)
navBar.addSubview(addressField)
rightView = UIView(frame: CGRect(x: 0, y: 0, width: 40, height: 28))
addressField.rightView = rightView
let refreshSize = CGSize(width: 18, height: 22)
let refreshIcon = #imageLiteral(resourceName: "UIButtonBarRefresh.png").resize(to: refreshSize)
.withRenderingMode(.alwaysOriginal)
refreshButton = UIButton(type: UIButton.ButtonType.system)
refreshButton.setImage(refreshIcon, for: .normal)
refreshButton.frame = rightView.frame
refreshButton.addTarget(self, action: #selector(self.refresh), for: .touchUpInside)
refreshButton.isHidden = true
rightView.addSubview(refreshButton)
let stopSize = CGSize(width: 17, height: 17)
let stopIcon = #imageLiteral(resourceName: "UIButtonBarStop.png").resize(to: stopSize)
.withRenderingMode(.alwaysOriginal)
stopButton = UIButton(type: UIButton.ButtonType.system)
stopButton.setImage(stopIcon, for: .normal)
stopButton.frame = rightView.frame
stopButton.addTarget(self, action: #selector(self.stop), for: .touchUpInside)
stopButton.isHidden = true
rightView.addSubview(stopButton)
updateButtons()
let userData = UserDefaults.standard
let lastUrlStr = userData.object(forKey: webBrowserLastURLKey) as? String ?? "https://www.google.com/"
if let url = URL(string: lastUrlStr) {
let request = URLRequest(url: url)
webView.loadRequest(request)
}
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
if #available(iOS 13.0, *) {
// 13.0 auto-adjusts the top to avoid the status bar.
} else {
navBarTopConstraint.constant = AppDelegate.statusBarHeight()
}
}
override func willRotate(to toInterfaceOrientation: UIInterfaceOrientation, duration: TimeInterval) {
if let navbarBackground = navbarBackground {
navbarBackground.setOrientation(toInterfaceOrientation)
}
}
override func didRotate(from fromInterfaceOrientation: UIInterfaceOrientation) {
navBarTopConstraint.constant = AppDelegate.statusBarHeight()
}
@objc func loadAddress(_ sender: Any, event: UIEvent) {
if let urlString = addressField?.text {
loadUrlString(urlString)
}
}
func loadUrlString(_ urlString: String, allowSearchRedirect: Bool = true) {
guard var url = URL(string: urlString) else {
if allowSearchRedirect {
loadSearchString(urlString)
}
return
}
if url.scheme == nil {
url = URL(string: "http://\(urlString)") ?? url
}
let request = URLRequest(url: url)
webView.loadRequest(request)
}
func loadSearchString(_ searchString: String) {
if let query = searchString.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) {
loadUrlString("google.com/search?q=\(query)", allowSearchRedirect: false)
}
}
func updateAddress(_ request: URLRequest) {
let url: URL? = request.mainDocumentURL
addressField.text = url?.absoluteString
let userData = UserDefaults.standard
userData.set(url?.absoluteString, forKey: webBrowserLastURLKey)
userData.synchronize()
}
@objc func refresh(_ sender: Any) {
webView.reload()
}
@objc func stop(_ sender: Any?) {
webView.stopLoading()
}
@IBAction func back(_ sender: Any) {
webView.goBack()
}
@IBAction func forward(_ sender: Any) {
webView.goForward()
}
@IBAction func bookmarks(_ sender: Any) {
let bookmarksVC = BookmarksViewController()
bookmarksVC.webBrowser = self
present(bookmarksVC, animated: true, completion: nil)
}
@IBAction func globe(_ sender: Any) {
Manager.shared.showKeyboardPicker(in: self, shouldAddKeyboard: false)
}
@objc func close(_ sender: Any?) {
dismiss(animated: true, completion: nil)
}
func webView(_ webView: UIWebView,
shouldStartLoadWith request: URLRequest,
navigationType: UIWebView.NavigationType) -> Bool {
if request.url?.lastPathComponent.hasSuffix(".kmp") ?? false {
// Can't have the browser auto-download with no way to select a different page.
// Can't just ignore it, either, as the .kmp may result from a redirect from
// the previous URL. (Like if using the keyman.com keyboard search!)
let userData = UserDefaults.standard
userData.set(nil as String?, forKey: webBrowserLastURLKey)
userData.synchronize()
// The user is trying to download a .kmp, but the standard
// UIWebView can't handle it properly.
ResourceDownloadManager.shared.downloadRawKMP(from: request.url!) { file, error in
// do something!
if let error = error {
let alertTitle = NSLocalizedString("alert-error-title", bundle: Bundle(for: Manager.self), comment: "")
let alert = ResourceFileManager.shared.buildSimpleAlert(title: alertTitle,
message: error.localizedDescription)
self.present(alert, animated: true, completion: nil)
return
}
// Re-use the standard 'open random file' code as when launching the
// app from a file. This will also auto-dismiss the browser, returning
// to the app's main screen.
if let file = file {
let appDelegate = UIApplication.shared.delegate as! AppDelegate
_ = appDelegate.application(UIApplication.shared, open: file)
}
}
return false
}
updateAddress(request)
return true
}
func webViewDidStartLoad(_ webView: UIWebView) {
UIApplication.shared.isNetworkActivityIndicatorVisible = true
updateButtons()
}
func webViewDidFinishLoad(_ webView: UIWebView) {
UIApplication.shared.isNetworkActivityIndicatorVisible = false
appendCSSFontFamily()
updateButtons()
}
func webView(_ webView: UIWebView, didFailLoadWithError error: Error) {
UIApplication.shared.isNetworkActivityIndicatorVisible = false
updateButtons()
var signalError: Bool = true
// An error will likely result if the user attempts to download a KMP,
// despite the fact that we tell it not to attempt a load.
let nsError = error as NSError
if let url = nsError.userInfo["NSErrorFailingURLKey"] as? NSURL {
signalError = !(url.path?.hasSuffix(".kmp") ?? false)
}
if signalError {
let alertController = UIAlertController(title: NSLocalizedString("error-opening-page", comment: ""),
message: error.localizedDescription,
preferredStyle: UIAlertController.Style.alert)
alertController.addAction(UIAlertAction(title: NSLocalizedString("command-ok",
bundle: Bundle(for: Manager.self),
comment: ""),
style: UIAlertAction.Style.default,
handler: nil))
self.present(alertController, animated: true, completion: nil)
}
}
private func updateButtons() {
refreshButton.isHidden = webView.isLoading
stopButton.isHidden = !webView.isLoading
backButton.isEnabled = webView.canGoBack
forwardButton.isEnabled = webView.canGoForward
}
private func appendCSSFontFamily() {
let jsStr: String = "var style = document.createElement('style');" +
"style.type = 'text/css';" +
"style.innerHTML = '*{font-family:\"\(fontFamily)\" !important;}';" +
"document.getElementsByTagName('head')[0].appendChild(style);"
webView?.stringByEvaluatingJavaScript(from: jsStr)
}
private func keyboardChanged(_ kb: InstallableKeyboard) {
if let fontName = Manager.shared.fontNameForKeyboard(withFullID: kb.fullID) {
newFontFamily = fontName
} else {
newFontFamily = UIFont.systemFont(ofSize: UIFont.systemFontSize).fontName
}
}
private func keyboardPickerDismissed() {
if newFontFamily != fontFamily {
fontFamily = newFontFamily
webView?.reload()
}
}
}
| 6b683e282c18e4b8341e97c26296f0dd | 35.242718 | 113 | 0.690419 | false | false | false | false |
stripysock/SwiftGen | refs/heads/master | GenumKit/Parsers/StoryboardParser.swift | mit | 1 | //
// GenumKit
// Copyright (c) 2015 Olivier Halligon
// MIT Licence
//
import Foundation
public final class StoryboardParser {
struct Scene {
let storyboardID: String
let tag: String
let customClass: String?
}
struct Segue {
let segueID: String
let customClass: String?
}
struct Cell {
let reuseID: String
let customClass: String?
}
var storyboardsScenes = [String: Set<Scene>]()
var storyboardsSegues = [String: Set<Segue>]()
var storyboardsCells = [String: Set<Cell>]()
public init() {}
public func addStoryboardAtPath(path: String) {
let parser = NSXMLParser(contentsOfURL: NSURL.fileURLWithPath(path))
class ParserDelegate : NSObject, NSXMLParserDelegate {
var scenes = Set<Scene>()
var segues = Set<Segue>()
var cells = Set<Cell>()
var inScene = false
var readyForFirstObject = false
var readyForPrototypes = false
var readyForConnections = false
@objc func parser(parser: NSXMLParser, didStartElement elementName: String,
namespaceURI: String?, qualifiedName qName: String?,
attributes attributeDict: [String : String])
{
switch elementName {
case "scene":
inScene = true
case "objects" where inScene:
readyForFirstObject = true
case let tag where readyForFirstObject:
if let storyboardID = attributeDict["storyboardIdentifier"] {
let customClass = attributeDict["customClass"]
scenes.insert(Scene(storyboardID: storyboardID, tag: tag, customClass: customClass))
}
readyForFirstObject = false
case "prototypes":
readyForPrototypes = true
case "tableViewCell" where readyForPrototypes:
if let reuseID = attributeDict["reuseIdentifier"] {
let customClass = attributeDict["customClass"]
cells.insert(Cell(reuseID: reuseID, customClass: customClass))
}
case "connections":
readyForConnections = true
case "segue" where readyForConnections:
if let segueID = attributeDict["identifier"] {
let customClass = attributeDict["customClass"]
segues.insert(Segue(segueID: segueID, customClass: customClass))
}
case "collectionViewCell":
if let reuseID = attributeDict["reuseIdentifier"] {
let customClass = attributeDict["reuseIdentifier"]
cells.insert(Cell(reuseID: reuseID, customClass: customClass))
}
default:
break
}
}
@objc func parser(parser: NSXMLParser, didEndElement elementName: String,
namespaceURI: String?, qualifiedName qName: String?)
{
switch elementName {
case "scene":
inScene = false
case "objects" where inScene:
readyForFirstObject = false
case "prototypes":
readyForPrototypes = false
case "connections":
readyForConnections = false
default:
break
}
}
}
let delegate = ParserDelegate()
parser?.delegate = delegate
parser?.parse()
let storyboardName = ((path as NSString).lastPathComponent as NSString).stringByDeletingPathExtension
storyboardsScenes[storyboardName] = delegate.scenes
storyboardsSegues[storyboardName] = delegate.segues
storyboardsCells[storyboardName] = delegate.cells
}
public func parseDirectory(path: String) {
if let dirEnum = NSFileManager.defaultManager().enumeratorAtPath(path) {
while let subPath = dirEnum.nextObject() as? NSString {
if subPath.pathExtension == "storyboard" {
self.addStoryboardAtPath((path as NSString).stringByAppendingPathComponent(subPath as String))
}
}
}
}
}
extension StoryboardParser.Scene: Equatable { }
func ==(lhs: StoryboardParser.Scene, rhs: StoryboardParser.Scene) -> Bool {
return lhs.storyboardID == rhs.storyboardID && lhs.tag == rhs.tag && lhs.customClass == rhs.customClass
}
extension StoryboardParser.Scene: Hashable {
var hashValue: Int {
return "\(storyboardID);\(tag);\(customClass)".hashValue
}
}
extension StoryboardParser.Cell: Equatable { }
func ==(lhs: StoryboardParser.Cell, rhs: StoryboardParser.Cell) -> Bool {
return lhs.reuseID == rhs.reuseID && lhs.customClass == rhs.customClass
}
extension StoryboardParser.Cell: Hashable {
var hashValue: Int {
return "\(reuseID);\(customClass)".hashValue
}
}
extension StoryboardParser.Segue: Equatable { }
func ==(lhs: StoryboardParser.Segue, rhs: StoryboardParser.Segue) -> Bool {
return lhs.segueID == rhs.segueID && lhs.customClass == rhs.customClass
}
extension StoryboardParser.Segue: Hashable {
var hashValue: Int {
return "\(segueID);\(customClass)".hashValue
}
}
| c6acf2f73841db39aef7d0e62fedd903 | 30.896104 | 105 | 0.649226 | false | false | false | false |
MarvinNazari/ICSPullToRefresh.Swift | refs/heads/master | ICSPullToRefresh/NVActivityIndicatorAnimationTriangleSkewSpin.swift | mit | 1 | //
// NVActivityIndicatorAnimationTriangleSkewSpin.swift
// NVActivityIndicatorViewDemo
//
// Created by Nguyen Vinh on 7/24/15.
// Copyright (c) 2015 Nguyen Vinh. All rights reserved.
//
import UIKit
class NVActivityIndicatorAnimationTriangleSkewSpin: NVActivityIndicatorAnimationDelegate {
func setUpAnimationInLayer(layer: CALayer, size: CGSize, color: UIColor) {
let x = (layer.bounds.size.width - size.width) / 2
let y = (layer.bounds.size.height - size.height) / 2
let duration: CFTimeInterval = 3
let timingFunction = CAMediaTimingFunction(controlPoints: 0.09, 0.57, 0.49, 0.9)
// Animation
let animation = CAKeyframeAnimation(keyPath: "transform")
animation.keyTimes = [0, 0.25, 0.5, 0.75, 1]
animation.timingFunctions = [timingFunction, timingFunction, timingFunction, timingFunction]
animation.values = [
NSValue(CATransform3D: CATransform3DConcat(createRotateXTransform(angle: 0), createRotateYTransform(angle: 0))),
NSValue(CATransform3D: CATransform3DConcat(createRotateXTransform(angle: CGFloat(M_PI)), createRotateYTransform(angle: 0))),
NSValue(CATransform3D: CATransform3DConcat(createRotateXTransform(angle: CGFloat(M_PI)), createRotateYTransform(angle: CGFloat(M_PI)))),
NSValue(CATransform3D: CATransform3DConcat(createRotateXTransform(angle: 0), createRotateYTransform(angle: CGFloat(M_PI)))),
NSValue(CATransform3D: CATransform3DConcat(createRotateXTransform(angle: 0), createRotateYTransform(angle: 0)))]
animation.duration = duration
animation.repeatCount = HUGE
animation.removedOnCompletion = false
// Draw triangle
let triangle = NVActivityIndicatorShape.Triangle.createLayerWith(size: size, color: color)
triangle.frame = CGRect(x: x, y: y, width: size.width, height: size.height)
triangle.addAnimation(animation, forKey: "animation")
layer.addSublayer(triangle)
}
func createRotateXTransform(angle angle: CGFloat) -> CATransform3D {
var transform = CATransform3DMakeRotation(angle, 1, 0, 0)
transform.m34 = CGFloat(-1) / 100
return transform
}
func createRotateYTransform(angle angle: CGFloat) -> CATransform3D {
var transform = CATransform3DMakeRotation(angle, 0, 1, 0)
transform.m34 = CGFloat(-1) / 100
return transform
}
}
| 6a1030d3dc6594ff21ac187f13a3324a | 43.175439 | 148 | 0.680699 | false | false | false | false |
codefellows/sea-b23-iOS | refs/heads/master | PhotoFilters/GalleryViewController.swift | mit | 1 | //
// GalleryViewController.swift
// PhotoFilters
//
// Created by Bradley Johnson on 10/13/14.
// Copyright (c) 2014 Code Fellows. All rights reserved.
//
import UIKit
protocol GalleryDelegate : class {
func didTapOnPicture(image : UIImage)
}
class GalleryViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate {
@IBOutlet weak var collectionView: UICollectionView!
weak var delegate: GalleryDelegate?
// var myParentViewController : ViewController?
// var myProfileParentViewController : ProfileViewController
var images = [UIImage]()
override func viewDidLoad() {
super.viewDidLoad()
self.collectionView.dataSource = self
self.collectionView.delegate = self
var image1 = UIImage(named: "photo2.jpg")
var image2 = UIImage(named: "photo3.jpg")
var image3 = UIImage(named: "photo4.jpg")
var image4 = UIImage(named: "photo5.jpg")
self.images.append(image1)
self.images.append(image2)
self.images.append(image3)
self.images.append(image4)
// Do any additional setup after loading the view.
}
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return self.images.count
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("GALLERY_CELL", forIndexPath: indexPath) as GalleryCell
//cell.backgroundColor = UIColor.purpleColor()
cell.imageView.image = self.images[indexPath.row]
return cell
}
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
// println("indexpath: \(indexPath)")
self.delegate?.didTapOnPicture(self.images[indexPath.row])
//self.myParentViewController?.didTapOnPicture(self.images[indexPath.row])
self.dismissViewControllerAnimated(true, completion: nil)
}
}
| fe1264d235f5bd1f81b1e2fb3d4c4ec3 | 32.625 | 130 | 0.69145 | false | false | false | false |
CapstoneTeamA/Mobile-Test-Runner-for-Jama | refs/heads/master | Mobile Test Runner for Jama/Mobile Test Runner for Jama/ProjectModel.swift | mit | 1 | //
// ProjectModel.swift
// Mobile Test Runner for Jama
//
// Created by PSU2 on 6/28/17.
// Copyright © 2017 Jaca. All rights reserved.
//
import Foundation
class ProjectModel {
var name = ""
var projectKey = ""
var id = -1
func extractProject(fromData: [String : AnyObject]) {
var fields: [String : AnyObject] = [:]
guard fromData["fields"] != nil else {
return
}
fields = fromData["fields"] as! Dictionary
id = fromData["id"] as! Int
name = fields["name"] as! String
guard fields["projectKey"] != nil else{
return
}
projectKey = fields["projectKey"] as! String
}
}
| f7066700f3f86da7db47f0e594775e47 | 21.5625 | 57 | 0.538781 | false | false | false | false |
blkbrds/intern09_final_project_tung_bien | refs/heads/master | MyApp/View/Controls/CustomViews/ConfirmOrderView/ConfirmOrderView.swift | mit | 1 | //
// Demo.swift
// MyApp
//
// Created by asiantech on 8/1/17.
// Copyright © 2017 Asian Tech Co., Ltd. All rights reserved.
//
import UIKit
protocol ConfirmOrderViewDelegate: class {
func confirmOrderViewDelegate()
}
final class ConfirmOrderView: UIView {
// MARK: - Properties
@IBOutlet weak var remainingBalanceLabel: UILabel!
@IBOutlet weak var orderTotalLabel: UILabel!
@IBOutlet weak var currentBalanceLabel: UILabel!
@IBOutlet weak var cancelButton: UIButton!
@IBOutlet weak var popUpView: UIView!
private let duration = 0.3
var totalOrder: Double = 0 {
didSet {
orderTotalLabel.text = "\(totalOrder.formattedWithSeparator()) \(App.String.UnitCurrency)"
}
}
var balance: Double = 0 {
didSet {
currentBalanceLabel.text = "\(balance.formattedWithSeparator()) \(App.String.UnitCurrency)"
}
}
var remainingBalance: Double = 0 {
didSet {
remainingBalanceLabel.text = "\(remainingBalance.formattedWithSeparator()) \(App.String.UnitCurrency)"
}
}
weak var delegate: ConfirmOrderViewDelegate?
// MARK: - Public
func show() {
popUpView.layer.cornerRadius = 5
cancelButton.layer.borderWidth = 1
cancelButton.layer.borderColor = App.Color.greenTheme.cgColor
alpha = 0
guard let root = AppDelegate.shared.window else {
return
}
frame = root.bounds
root.addSubview(self)
UIView.animate(withDuration: duration, animations: {
self.alpha = 1
})
}
func hide() {
UIView.animate(withDuration: duration, animations: {
self.alpha = 0
}) { (_) in
self.removeFromSuperview()
}
}
// MARK: - Action
@IBAction func okButtonTouchUpInside(_ sender: UIButton) {
delegate?.confirmOrderViewDelegate()
hide()
}
@IBAction func cancelButtonTouchUpInside(_ sender: UIButton) {
hide()
}
}
| 2080dce5fbe5a9c4102facdd2b2ecf45 | 25.789474 | 115 | 0.617387 | false | false | false | false |
mathewsanders/Mustard | refs/heads/master | Playgrounds/Source/Custom tokenizers.playground/Sources/LetterCountTokenizer.swift | mit | 1 | //
// LetterCountTokenizer.swift
//
//
// Created by Mat on 1/6/17.
//
//
import Swift
import Mustard
open class LetterCountTokenizer: DefaultTokenizerType {
let targetSize: Int
private var currentSize: Int = 0
required public init() {
self.targetSize = 0
}
public init(_ size: Int) {
self.targetSize = size
}
public func tokenCanTake(_ scalar: UnicodeScalar) -> Bool {
if CharacterSet.letters.contains(scalar) {
currentSize += 1
return currentSize <= targetSize
}
return false
}
public func completeTokenIsInvalid(whenNextScalarIs scalar: UnicodeScalar?) -> Bool {
guard let char = scalar else { return false }
return !CharacterSet.whitespaces.contains(char)
}
public func tokenIsComplete() -> Bool {
return targetSize == currentSize
}
public func prepareForReuse() {
currentSize = 0
}
open func advanceIfCompleteTokenIsInvalid() -> Bool {
return false
}
}
| a62aac9c8bced66ecdc42b828d7ad8d6 | 20.877551 | 89 | 0.603545 | false | false | false | false |
OneBusAway/onebusaway-iphone | refs/heads/develop | Carthage/Checkouts/PromiseKit/Sources/Promise.swift | apache-2.0 | 7 | import class Dispatch.DispatchQueue
import class Foundation.NSError
import func Foundation.NSLog
/**
A *promise* represents the future value of a (usually) asynchronous task.
To obtain the value of a promise we call `then`.
Promises are chainable: `then` returns a promise, you can call `then` on
that promise, which returns a promise, you can call `then` on that
promise, et cetera.
Promises start in a pending state and *resolve* with a value to become
*fulfilled* or an `Error` to become rejected.
- SeeAlso: [PromiseKit `then` Guide](http://promisekit.org/docs/)
*/
open class Promise<T> {
let state: State<T>
/**
Create a new, pending promise.
func fetchAvatar(user: String) -> Promise<UIImage> {
return Promise { fulfill, reject in
MyWebHelper.GET("\(user)/avatar") { data, err in
guard let data = data else { return reject(err) }
guard let img = UIImage(data: data) else { return reject(MyError.InvalidImage) }
guard let img.size.width > 0 else { return reject(MyError.ImageTooSmall) }
fulfill(img)
}
}
}
- Parameter resolvers: The provided closure is called immediately on the active thread; commence your asynchronous task, calling either fulfill or reject when it completes.
- Parameter fulfill: Fulfills this promise with the provided value.
- Parameter reject: Rejects this promise with the provided error.
- Returns: A new promise.
- Note: If you are wrapping a delegate-based system, we recommend
to use instead: `Promise.pending()`
- SeeAlso: http://promisekit.org/docs/sealing-promises/
- SeeAlso: http://promisekit.org/docs/cookbook/wrapping-delegation/
- SeeAlso: pending()
*/
required public init(resolvers: (_ fulfill: @escaping (T) -> Void, _ reject: @escaping (Error) -> Void) throws -> Void) {
var resolve: ((Resolution<T>) -> Void)!
do {
state = UnsealedState(resolver: &resolve)
try resolvers({ resolve(.fulfilled($0)) }, { error in
#if !PMKDisableWarnings
if self.isPending {
resolve(Resolution(error))
} else {
NSLog("PromiseKit: warning: reject called on already rejected Promise: \(error)")
}
#else
resolve(Resolution(error))
#endif
})
} catch {
resolve(Resolution(error))
}
}
/**
Create an already fulfilled promise.
To create a resolved `Void` promise, do: `Promise(value: ())`
*/
required public init(value: T) {
state = SealedState(resolution: .fulfilled(value))
}
/**
Create an already rejected promise.
*/
required public init(error: Error) {
state = SealedState(resolution: Resolution(error))
}
/**
Careful with this, it is imperative that sealant can only be called once
or you will end up with spurious unhandled-errors due to possible double
rejections and thus immediately deallocated ErrorConsumptionTokens.
*/
init(sealant: (@escaping (Resolution<T>) -> Void) -> Void) {
var resolve: ((Resolution<T>) -> Void)!
state = UnsealedState(resolver: &resolve)
sealant(resolve)
}
/**
A `typealias` for the return values of `pending()`. Simplifies declaration of properties that reference the values' containing tuple when this is necessary. For example, when working with multiple `pendingPromise(value: ())`s within the same scope, or when the promise initialization must occur outside of the caller's initialization.
class Foo: BarDelegate {
var task: Promise<Int>.PendingTuple?
}
- SeeAlso: pending()
*/
public typealias PendingTuple = (promise: Promise, fulfill: (T) -> Void, reject: (Error) -> Void)
/**
Making promises that wrap asynchronous delegation systems or other larger asynchronous systems without a simple completion handler is easier with pending.
class Foo: BarDelegate {
let (promise, fulfill, reject) = Promise<Int>.pending()
func barDidFinishWithResult(result: Int) {
fulfill(result)
}
func barDidError(error: NSError) {
reject(error)
}
}
- Returns: A tuple consisting of:
1) A promise
2) A function that fulfills that promise
3) A function that rejects that promise
*/
public final class func pending() -> PendingTuple {
var fulfill: ((T) -> Void)!
var reject: ((Error) -> Void)!
let promise = self.init { fulfill = $0; reject = $1 }
return (promise, fulfill, reject)
}
/**
The provided closure is executed when this promise is resolved.
- Parameter on: The queue to which the provided closure dispatches.
- Parameter body: The closure that is executed when this Promise is fulfilled.
- Returns: A new promise that is resolved with the value returned from the provided closure. For example:
URLSession.GET(url).then { data -> Int in
//…
return data.length
}.then { length in
//…
}
*/
@discardableResult
public func then<U>(on q: DispatchQueue = .default, execute body: @escaping (T) throws -> U) -> Promise<U> {
return Promise<U> { resolve in
state.then(on: q, else: resolve) { value in
resolve(.fulfilled(try body(value)))
}
}
}
/**
The provided closure executes when this promise resolves.
This variant of `then` allows chaining promises, the promise returned by the provided closure is resolved before the promise returned by this closure resolves.
- Parameter on: The queue to which the provided closure dispatches.
- Parameter execute: The closure that executes when this promise fulfills.
- Returns: A new promise that resolves when the promise returned from the provided closure resolves. For example:
URLSession.GET(url1).then { data in
return CLLocationManager.promise()
}.then { location in
//…
}
*/
@discardableResult
public func then<U>(on q: DispatchQueue = .default, execute body: @escaping (T) throws -> Promise<U>) -> Promise<U> {
var resolve: ((Resolution<U>) -> Void)!
let rv = Promise<U>{ resolve = $0 }
state.then(on: q, else: resolve) { value in
let promise = try body(value)
guard promise !== rv else { throw PMKError.returnedSelf }
promise.state.pipe(resolve)
}
return rv
}
/**
The provided closure executes when this promise resolves.
This variant of `then` allows returning a tuple of promises within provided closure. All of the returned
promises needs be fulfilled for this promise to be marked as resolved.
- Note: At maximum 5 promises may be returned in a tuple
- Note: If *any* of the tuple-provided promises reject, the returned promise is immediately rejected with that error.
- Warning: In the event of rejection the other promises will continue to resolve and, as per any other promise, will either fulfill or reject.
- Parameter on: The queue to which the provided closure dispatches.
- Parameter execute: The closure that executes when this promise fulfills.
- Returns: A new promise that resolves when all promises returned from the provided closure resolve. For example:
loginPromise.then { _ -> (Promise<Data>, Promise<UIImage>)
return (URLSession.GET(userUrl), URLSession.dataTask(with: avatarUrl).asImage())
}.then { userData, avatarImage in
//…
}
*/
@discardableResult
public func then<U, V>(on q: DispatchQueue = .default, execute body: @escaping (T) throws -> (Promise<U>, Promise<V>)) -> Promise<(U, V)> {
return then(on: q, execute: body) { when(fulfilled: $0.0, $0.1) }
}
/// This variant of `then` allows returning a tuple of promises within provided closure.
@discardableResult
public func then<U, V, X>(on q: DispatchQueue = .default, execute body: @escaping (T) throws -> (Promise<U>, Promise<V>, Promise<X>)) -> Promise<(U, V, X)> {
return then(on: q, execute: body) { when(fulfilled: $0.0, $0.1, $0.2) }
}
/// This variant of `then` allows returning a tuple of promises within provided closure.
@discardableResult
public func then<U, V, X, Y>(on q: DispatchQueue = .default, execute body: @escaping (T) throws -> (Promise<U>, Promise<V>, Promise<X>, Promise<Y>)) -> Promise<(U, V, X, Y)> {
return then(on: q, execute: body) { when(fulfilled: $0.0, $0.1, $0.2, $0.3) }
}
/// This variant of `then` allows returning a tuple of promises within provided closure.
@discardableResult
public func then<U, V, X, Y, Z>(on q: DispatchQueue = .default, execute body: @escaping (T) throws -> (Promise<U>, Promise<V>, Promise<X>, Promise<Y>, Promise<Z>)) -> Promise<(U, V, X, Y, Z)> {
return then(on: q, execute: body) { when(fulfilled: $0.0, $0.1, $0.2, $0.3, $0.4) }
}
/// utility function to serve `then` implementations with `body` returning tuple of promises
@discardableResult
private func then<U, V>(on q: DispatchQueue, execute body: @escaping (T) throws -> V, when: @escaping (V) -> Promise<U>) -> Promise<U> {
return Promise<U> { resolve in
state.then(on: q, else: resolve) { value in
let promise = try body(value)
// since when(promise) switches to `zalgo`, we have to pipe back to `q`
when(promise).state.pipe(on: q, to: resolve)
}
}
}
/**
The provided closure executes when this promise rejects.
Rejecting a promise cascades: rejecting all subsequent promises (unless
recover is invoked) thus you will typically place your catch at the end
of a chain. Often utility promises will not have a catch, instead
delegating the error handling to the caller.
- Parameter on: The queue to which the provided closure dispatches.
- Parameter policy: The default policy does not execute your handler for cancellation errors.
- Parameter execute: The handler to execute if this promise is rejected.
- Returns: `self`
- SeeAlso: [Cancellation](http://promisekit.org/docs/)
- Important: The promise that is returned is `self`. `catch` cannot affect the chain, in PromiseKit 3 no promise was returned to strongly imply this, however for PromiseKit 4 we started returning a promise so that you can `always` after a catch or return from a function that has an error handler.
*/
@discardableResult
public func `catch`(on q: DispatchQueue = .default, policy: CatchPolicy = .allErrorsExceptCancellation, execute body: @escaping (Error) -> Void) -> Promise {
state.catch(on: q, policy: policy, else: { _ in }, execute: body)
return self
}
/**
The provided closure executes when this promise rejects.
Unlike `catch`, `recover` continues the chain provided the closure does not throw. Use `recover` in circumstances where recovering the chain from certain errors is a possibility. For example:
CLLocationManager.promise().recover { error in
guard error == CLError.unknownLocation else { throw error }
return CLLocation.Chicago
}
- Parameter on: The queue to which the provided closure dispatches.
- Parameter policy: The default policy does not execute your handler for cancellation errors.
- Parameter execute: The handler to execute if this promise is rejected.
- SeeAlso: [Cancellation](http://promisekit.org/docs/)
*/
@discardableResult
public func recover(on q: DispatchQueue = .default, policy: CatchPolicy = .allErrorsExceptCancellation, execute body: @escaping (Error) throws -> Promise) -> Promise {
var resolve: ((Resolution<T>) -> Void)!
let rv = Promise{ resolve = $0 }
state.catch(on: q, policy: policy, else: resolve) { error in
let promise = try body(error)
guard promise !== rv else { throw PMKError.returnedSelf }
promise.state.pipe(resolve)
}
return rv
}
/**
The provided closure executes when this promise rejects.
Unlike `catch`, `recover` continues the chain provided the closure does not throw. Use `recover` in circumstances where recovering the chain from certain errors is a possibility. For example:
CLLocationManager.promise().recover { error in
guard error == CLError.unknownLocation else { throw error }
return CLLocation.Chicago
}
- Parameter on: The queue to which the provided closure dispatches.
- Parameter policy: The default policy does not execute your handler for cancellation errors.
- Parameter execute: The handler to execute if this promise is rejected.
- SeeAlso: [Cancellation](http://promisekit.org/docs/)
*/
@discardableResult
public func recover(on q: DispatchQueue = .default, policy: CatchPolicy = .allErrorsExceptCancellation, execute body: @escaping (Error) throws -> T) -> Promise {
return Promise { resolve in
state.catch(on: q, policy: policy, else: resolve) { error in
resolve(.fulfilled(try body(error)))
}
}
}
/**
The provided closure executes when this promise resolves.
firstly {
UIApplication.shared.networkActivityIndicatorVisible = true
}.then {
//…
}.always {
UIApplication.shared.networkActivityIndicatorVisible = false
}.catch {
//…
}
- Parameter on: The queue to which the provided closure dispatches.
- Parameter execute: The closure that executes when this promise resolves.
- Returns: A new promise, resolved with this promise’s resolution.
*/
@discardableResult
public func always(on q: DispatchQueue = .default, execute body: @escaping () -> Void) -> Promise {
state.always(on: q) { resolution in
body()
}
return self
}
/**
Allows you to “tap” into a promise chain and inspect its result.
The function you provide cannot mutate the chain.
URLSession.GET(/*…*/).tap { result in
print(result)
}
- Parameter on: The queue to which the provided closure dispatches.
- Parameter execute: The closure that executes when this promise resolves.
- Returns: A new promise, resolved with this promise’s resolution.
*/
@discardableResult
public func tap(on q: DispatchQueue = .default, execute body: @escaping (Result<T>) -> Void) -> Promise {
state.always(on: q) { resolution in
body(Result(resolution))
}
return self
}
/**
Void promises are less prone to generics-of-doom scenarios.
- SeeAlso: when.swift contains enlightening examples of using `Promise<Void>` to simplify your code.
*/
public func asVoid() -> Promise<Void> {
return then(on: zalgo) { _ in return }
}
//MARK: deprecations
@available(*, unavailable, renamed: "always()")
public func finally(on: DispatchQueue = DispatchQueue.main, execute body: () -> Void) -> Promise { fatalError() }
@available(*, unavailable, renamed: "always()")
public func ensure(on: DispatchQueue = DispatchQueue.main, execute body: () -> Void) -> Promise { fatalError() }
@available(*, unavailable, renamed: "pending()")
public class func `defer`() -> PendingTuple { fatalError() }
@available(*, unavailable, renamed: "pending()")
public class func `pendingPromise`() -> PendingTuple { fatalError() }
@available(*, unavailable, message: "deprecated: use then(on: .global())")
public func thenInBackground<U>(execute body: (T) throws -> U) -> Promise<U> { fatalError() }
@available(*, unavailable, renamed: "catch")
public func onError(policy: CatchPolicy = .allErrors, execute body: (Error) -> Void) { fatalError() }
@available(*, unavailable, renamed: "catch")
public func errorOnQueue(_ on: DispatchQueue, policy: CatchPolicy = .allErrors, execute body: (Error) -> Void) { fatalError() }
@available(*, unavailable, renamed: "catch")
public func error(policy: CatchPolicy, execute body: (Error) -> Void) { fatalError() }
@available(*, unavailable, renamed: "catch")
public func report(policy: CatchPolicy = .allErrors, execute body: (Error) -> Void) { fatalError() }
@available(*, unavailable, renamed: "init(value:)")
public init(_ value: T) { fatalError() }
//MARK: disallow `Promise<Error>`
@available(*, unavailable, message: "cannot instantiate Promise<Error>")
public init<T: Error>(resolvers: (_ fulfill: (T) -> Void, _ reject: (Error) -> Void) throws -> Void) { fatalError() }
@available(*, unavailable, message: "cannot instantiate Promise<Error>")
public class func pending<T: Error>() -> (promise: Promise, fulfill: (T) -> Void, reject: (Error) -> Void) { fatalError() }
//MARK: disallow returning `Error`
@available (*, unavailable, message: "instead of returning the error; throw")
public func then<U: Error>(on: DispatchQueue = .default, execute body: (T) throws -> U) -> Promise<U> { fatalError() }
@available (*, unavailable, message: "instead of returning the error; throw")
public func recover<T: Error>(on: DispatchQueue = .default, execute body: (Error) throws -> T) -> Promise { fatalError() }
//MARK: disallow returning `Promise?`
@available(*, unavailable, message: "unwrap the promise")
public func then<U>(on: DispatchQueue = .default, execute body: (T) throws -> Promise<U>?) -> Promise<U> { fatalError() }
@available(*, unavailable, message: "unwrap the promise")
public func recover(on: DispatchQueue = .default, execute body: (Error) throws -> Promise?) -> Promise { fatalError() }
}
extension Promise: CustomStringConvertible {
public var description: String {
return "Promise: \(state)"
}
}
/**
Judicious use of `firstly` *may* make chains more readable.
Compare:
URLSession.GET(url1).then {
URLSession.GET(url2)
}.then {
URLSession.GET(url3)
}
With:
firstly {
URLSession.GET(url1)
}.then {
URLSession.GET(url2)
}.then {
URLSession.GET(url3)
}
*/
public func firstly<T>(execute body: () throws -> Promise<T>) -> Promise<T> {
return firstly(execute: body) { $0 }
}
/**
Judicious use of `firstly` *may* make chains more readable.
Firstly allows to return tuple of promises
Compare:
when(fulfilled: URLSession.GET(url1), URLSession.GET(url2)).then {
URLSession.GET(url3)
}.then {
URLSession.GET(url4)
}
With:
firstly {
(URLSession.GET(url1), URLSession.GET(url2))
}.then { _, _ in
URLSession.GET(url2)
}.then {
URLSession.GET(url3)
}
- Note: At maximum 5 promises may be returned in a tuple
- Note: If *any* of the tuple-provided promises reject, the returned promise is immediately rejected with that error.
*/
public func firstly<T, U>(execute body: () throws -> (Promise<T>, Promise<U>)) -> Promise<(T, U)> {
return firstly(execute: body) { when(fulfilled: $0.0, $0.1) }
}
/// Firstly allows to return tuple of promises
public func firstly<T, U, V>(execute body: () throws -> (Promise<T>, Promise<U>, Promise<V>)) -> Promise<(T, U, V)> {
return firstly(execute: body) { when(fulfilled: $0.0, $0.1, $0.2) }
}
/// Firstly allows to return tuple of promises
public func firstly<T, U, V, W>(execute body: () throws -> (Promise<T>, Promise<U>, Promise<V>, Promise<W>)) -> Promise<(T, U, V, W)> {
return firstly(execute: body) { when(fulfilled: $0.0, $0.1, $0.2, $0.3) }
}
/// Firstly allows to return tuple of promises
public func firstly<T, U, V, W, X>(execute body: () throws -> (Promise<T>, Promise<U>, Promise<V>, Promise<W>, Promise<X>)) -> Promise<(T, U, V, W, X)> {
return firstly(execute: body) { when(fulfilled: $0.0, $0.1, $0.2, $0.3, $0.4) }
}
/// utility function to serve `firstly` implementations with `body` returning tuple of promises
fileprivate func firstly<U, V>(execute body: () throws -> V, when: (V) -> Promise<U>) -> Promise<U> {
do {
return when(try body())
} catch {
return Promise(error: error)
}
}
@available(*, unavailable, message: "instead of returning the error; throw")
public func firstly<T: Error>(execute body: () throws -> T) -> Promise<T> { fatalError() }
@available(*, unavailable, message: "use DispatchQueue.promise")
public func firstly<T>(on: DispatchQueue, execute body: () throws -> Promise<T>) -> Promise<T> { fatalError() }
/**
- SeeAlso: `DispatchQueue.promise(group:qos:flags:execute:)`
*/
@available(*, deprecated: 4.0, renamed: "DispatchQueue.promise")
public func dispatch_promise<T>(_ on: DispatchQueue, _ body: @escaping () throws -> T) -> Promise<T> {
return Promise(value: ()).then(on: on, execute: body)
}
/**
The underlying resolved state of a promise.
- Remark: Same as `Resolution<T>` but without the associated `ErrorConsumptionToken`.
*/
public enum Result<T> {
/// Fulfillment
case fulfilled(T)
/// Rejection
case rejected(Error)
init(_ resolution: Resolution<T>) {
switch resolution {
case .fulfilled(let value):
self = .fulfilled(value)
case .rejected(let error, _):
self = .rejected(error)
}
}
/**
- Returns: `true` if the result is `fulfilled` or `false` if it is `rejected`.
*/
public var boolValue: Bool {
switch self {
case .fulfilled:
return true
case .rejected:
return false
}
}
}
/**
An object produced by `Promise.joint()`, along with a promise to which it is bound.
Joining with a promise via `Promise.join(_:)` will pipe the resolution of that promise to
the joint's bound promise.
- SeeAlso: `Promise.joint()`
- SeeAlso: `Promise.join(_:)`
*/
public class PMKJoint<T> {
fileprivate var resolve: ((Resolution<T>) -> Void)!
}
extension Promise {
/**
Provides a safe way to instantiate a `Promise` and resolve it later via its joint and another
promise.
class Engine {
static func make() -> Promise<Engine> {
let (enginePromise, joint) = Promise<Engine>.joint()
let cylinder: Cylinder = Cylinder(explodeAction: {
// We *could* use an IUO, but there are no guarantees about when
// this callback will be called. Having an actual promise is safe.
enginePromise.then { engine in
engine.checkOilPressure()
}
})
firstly {
Ignition.default.start()
}.then { plugs in
Engine(cylinders: [cylinder], sparkPlugs: plugs)
}.join(joint)
return enginePromise
}
}
- Returns: A new promise and its joint.
- SeeAlso: `Promise.join(_:)`
*/
public final class func joint() -> (Promise<T>, PMKJoint<T>) {
let pipe = PMKJoint<T>()
let promise = Promise(sealant: { pipe.resolve = $0 })
return (promise, pipe)
}
/**
Pipes the value of this promise to the promise created with the joint.
- Parameter joint: The joint on which to join.
- SeeAlso: `Promise.joint()`
*/
public func join(_ joint: PMKJoint<T>) {
state.pipe(joint.resolve)
}
}
extension Promise where T: Collection {
/**
Transforms a `Promise` where `T` is a `Collection` into a `Promise<[U]>`
URLSession.shared.dataTask(url: /*…*/).asArray().map { result in
return download(result)
}.then { images in
// images is `[UIImage]`
}
- Parameter on: The queue to which the provided closure dispatches.
- Parameter transform: The closure that executes when this promise resolves.
- Returns: A new promise, resolved with this promise’s resolution.
*/
public func map<U>(on: DispatchQueue = .default, transform: @escaping (T.Iterator.Element) throws -> Promise<U>) -> Promise<[U]> {
return Promise<[U]> { resolve in
return state.then(on: zalgo, else: resolve) { tt in
when(fulfilled: try tt.map(transform)).state.pipe(resolve)
}
}
}
}
#if swift(>=3.1)
public extension Promise where T == Void {
convenience init() {
self.init(value: ())
}
}
#endif
| fc94d7bc0e9bc218609b198eb2891e1d | 37.993808 | 339 | 0.625248 | false | false | false | false |
loudnate/Loop | refs/heads/master | Loop/View Controllers/TextFieldTableViewController.swift | apache-2.0 | 1 | //
// TextFieldTableViewController.swift
// Loop
//
// Created by Nate Racklyeft on 7/31/16.
// Copyright © 2016 Nathan Racklyeft. All rights reserved.
//
import LoopKitUI
import HealthKit
/// Convenience static constructors used to contain common configuration
extension TextFieldTableViewController {
typealias T = TextFieldTableViewController
private static let valueNumberFormatter: NumberFormatter = {
let formatter = NumberFormatter()
formatter.numberStyle = .decimal
formatter.minimumFractionDigits = 0
formatter.maximumFractionDigits = 2
return formatter
}()
}
| c5bc8003e6c166eed7d1cac8fa6db972 | 23.423077 | 72 | 0.722835 | false | false | false | false |
DasHutch/minecraft-castle-challenge | refs/heads/develop | app/_src/CastleChallengeDataManager.swift | gpl-2.0 | 1 | //
// CastleChallengeDataManager.swift
// MC Castle Challenge
//
// Created by Gregory Hutchinson on 4/9/16.
// Copyright © 2016 Gregory Hutchinson. All rights reserved.
//
import Foundation
/**
CastleChallengeDataManager Struct
*/
class CastleChallengeDataManager {
lazy var _rules = [Rule]()
struct Errors {
enum FileSystem {
case missing(file: String?)
var domain: String {
return "com.minecraft.castle.challenge.errors.filesystem"
}
var code: Int {
switch self {
case missing(_):
return 1000
}
}
var detail: String {
switch self {
case missing(let file):
return "file is missing: \(file)"
}
}
var error: NSError {
return NSError(domain: domain, code: code, userInfo: [NSLocalizedDescriptionKey: detail])
}
}
enum Parsing {
case missingKey(key: String?)
var domain: String {
return "com.minecraft.castle.challenge.errors.parsing"
}
var code: Int {
switch self {
case missingKey(_):
return 1000
}
}
var detail: String {
switch self {
case missingKey(let key):
return "missing key in dict: \(key)"
}
}
var error: NSError {
return NSError(domain: domain, code: code, userInfo: [NSLocalizedDescriptionKey: detail])
}
}
}
func dataForAge(age: String) throws -> NSMutableDictionary {
let path = FileManager.defaultManager.challengeProgressPLIST()
let plistDict = NSMutableDictionary(contentsOfFile: path)
guard plistDict != nil else {
log.severe("Stage / Data from Saved PLIST is nil, unable to retrieve data.")
throw Errors.FileSystem.missing(file: path).error
}
guard let ages = plistDict!["ages"] as? NSMutableDictionary else {
log.severe("Stage / Data from saved PLIST is missing `ages` dictionary. Possibly, a corrupt plist file?!")
throw Errors.Parsing.missingKey(key: "ages").error
}
let ageLowerCase = age.lowercaseString
guard let age = ages[ageLowerCase] as? NSMutableDictionary else {
throw Errors.Parsing.missingKey(key: ageLowerCase).error
}
log.verbose("Config'd Data for Age: \(age) from PLIST")
return age
}
func dataForRules() throws -> NSArray {
let path = FileManager.defaultManager.challengeProgressPLIST()
let plistDict = NSMutableDictionary(contentsOfFile: path)
guard plistDict != nil else {
log.severe("Stage / Data from Saved PLIST is nil, unable to retrieve data.")
throw Errors.FileSystem.missing(file: path).error
}
guard let rules = plistDict!["rules"] as? NSArray else {
log.severe("Stage / Data from saved PLIST is missing `rules` dictionary. Possibly, a corrupt plist file?!")
throw Errors.Parsing.missingKey(key: "rules").error
}
return rules
}
func rules() -> [Rule] {
if _rules.count >= 0 {
return _rules
}
do {
let rulesData = try dataForRules()
var rules = [Rule]()
for rule in rulesData {
if let ruleString = rule as? String {
rules.append(Rule(description: ruleString))
}else {
log.warning("Rule is not a string, unable to add it to our Rules array: \(rule)")
}
}
return rules
}catch let error as NSError {
log.error("Error: \(error)")
return [Rule]()
}
}
func ruleForIndexPath(indexPath: NSIndexPath) -> Rule {
if let theRule = rules().atIndex(indexPath.row) {
return theRule
}else {
return Rule(description: "")
}
}
}
| 18e0b9bd2b96a9352cac8d0c0a45ff9f | 29.532374 | 119 | 0.534402 | false | false | false | false |
RuiAAPeres/DVR | refs/heads/master | DVR/Cassette.swift | mit | 4 | import Foundation
struct Cassette {
let name: String
let interactions: [Interaction]
init(name: String, interactions: [Interaction]) {
self.name = name
self.interactions = interactions
}
func interactionForRequest(request: NSURLRequest) -> Interaction? {
for interaction in interactions {
let r = interaction.request
// Note: We don't check headers right now
if r.HTTPMethod == request.HTTPMethod && r.URL == request.URL && r.HTTPBody == request.HTTPBody {
return interaction
}
}
return nil
}
}
extension Cassette {
var dictionary: [String: AnyObject] {
return [
"name": name,
"interactions": interactions.map { $0.dictionary }
]
}
init?(dictionary: [String: AnyObject]) {
guard let name = dictionary["name"] as? String else { return nil }
self.name = name
if let array = dictionary["interactions"] as? [[String: AnyObject]] {
interactions = array.flatMap { Interaction(dictionary: $0) }
} else {
interactions = []
}
}
}
| b368e3e8d91a7a9caa7df2b3eb2daae1 | 25.177778 | 109 | 0.56961 | false | false | false | false |
simonbs/Emcee | refs/heads/master | LastFMKit/Models/Artist.swift | mit | 1 | //
// Artist.swift
// Emcee
//
// Created by Simon Støvring on 31/03/15.
// Copyright (c) 2015 SimonBS. All rights reserved.
//
import Foundation
import SwiftyJSON
public class Artist {
public let name: String
public let playcount: Int
public let url: NSURL
public let images: [Asset]
init(json: JSON) {
name = json["name"].stringValue
playcount = json["playcount"].intValue
url = json["url"].URL!
var mutableAssets = [Asset]()
for imageJson in json["image"].arrayValue {
mutableAssets.append(Asset(json: imageJson))
}
images = mutableAssets
}
public func smallestImage() -> Asset? {
return images.sort { $0.rank < $1.rank }.first
}
public func largestImage() -> Asset? {
return images.sort { $0.rank > $1.rank }.first
}
}
| 39fd9d6bb66871a94f6f429734d91b59 | 21.275 | 56 | 0.578002 | false | false | false | false |
zhangliangzhi/iosStudyBySwift | refs/heads/master | TableTest/TableTest/ViewController.swift | mit | 1 | //
// ViewController.swift
// TableTest
//
// Created by ZhangLiangZhi on 2016/12/5.
// Copyright © 2016年 xigk. All rights reserved.
//
import UIKit
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
@IBOutlet weak var tableView: UITableView!
var avengers = ["Thor", "Hulk", "Iron Man", "Capt. America", "Black Widow"]
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
// tableView.isEditing = true
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return avengers.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = UITableViewCell()
cell.textLabel?.text = avengers[indexPath.row]
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
performSegue(withIdentifier: "oneSegue", sender: avengers[indexPath.row])
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let guest = segue.destination as! SecondViewController
guest.micKey = sender as! String
}
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
avengers.remove(at: indexPath.row)
tableView.deleteRows(at: [indexPath], with: .fade)
}
else if editingStyle == .insert {
avengers.append("ok add")
tableView.insertRows(at: [indexPath], with: .fade)
}
}
func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCellEditingStyle {
// 第一行不显示删除
if indexPath.row == 0 && avengers.count == 1{
return .insert
}else{
return .delete
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| fb486a6e6654092077f22a53129b9425 | 28.890411 | 127 | 0.634739 | false | false | false | false |
Vostro162/VaporTelegram | refs/heads/master | Sources/App/InlineQueryResultVideo.swift | mit | 1 | //
// InlineQueryResultVideo.swift
// VaporTelegram
//
// Created by Marius Hartig on 05.06.17.
//
//
import Foundation
struct InlineQueryResultVideo: InlineQuery {
let id: String
let type: String
let url: URL
let mimeType: String
let thumbURL: URL
let title: String
let replyMarkup: ReplyMarkup?
let inputMessageContent: InputMessageContent?
let description: String?
let width: Int?
let height: Int?
let duration: Int?
let caption: String?
public init(
id: String,
type: String,
url: URL,
mimeType: String,
thumbURL: URL,
title: String,
replyMarkup: ReplyMarkup? = nil,
inputMessageContent: InputMessageContent? = nil,
description: String? = nil,
width: Int? = nil,
height: Int? = nil,
duration: Int? = nil,
caption: String? = nil
) {
self.id = id
self.type = type
self.url = url
self.mimeType = mimeType
self.thumbURL = thumbURL
self.title = title
self.replyMarkup = replyMarkup
self.inputMessageContent = inputMessageContent
self.description = description
self.width = width
self.height = height
self.duration = duration
self.caption = caption
}
}
| 19e339e6f25f451c9e9ddfe61fd8d450 | 22.561404 | 56 | 0.592703 | false | false | false | false |
JohnCoates/Aerial | refs/heads/master | Aerial/Source/Views/PrefPanel/InfoDateView.swift | mit | 1 | //
// InfoDateView.swift
// Aerial
//
// Created by Guillaume Louel on 23/03/2020.
// Copyright © 2020 Guillaume Louel. All rights reserved.
//
import Cocoa
class InfoDateView: NSView {
@IBOutlet var dateFormatPopup: NSPopUpButton!
@IBOutlet var withYearCheckbox: NSButton!
@IBOutlet var customDateFormatField: NSTextField!
// Init(ish)
func setStates() {
dateFormatPopup.selectItem(at: PrefsInfo.date.format.rawValue)
withYearCheckbox.state = PrefsInfo.date.withYear ? .on : .off
withYearCheckbox.isHidden = (PrefsInfo.date.format == .custom)
customDateFormatField.stringValue = PrefsInfo.customDateFormat
customDateFormatField.isHidden = !(PrefsInfo.date.format == .custom)
}
@IBAction func dateFormatPopupChange(_ sender: NSPopUpButton) {
PrefsInfo.date.format = InfoDate(rawValue: sender.indexOfSelectedItem)!
withYearCheckbox.isHidden = (PrefsInfo.date.format == .custom)
customDateFormatField.isHidden = !(PrefsInfo.date.format == .custom)
}
@IBAction func withYearCheckboxChange(_ sender: NSButton) {
let onState = sender.state == .on
PrefsInfo.date.withYear = onState
}
@IBAction func customDateFormatFieldChange(_ sender: NSTextField) {
PrefsInfo.customDateFormat = sender.stringValue
}
}
| c742c9b73f96e6252734e024ac1dec38 | 30.348837 | 79 | 0.700297 | false | false | false | false |
maximbilan/SwiftThicknessPicker | refs/heads/master | SwiftThicknessPicker/ViewController.swift | mit | 1 | //
// ViewController.swift
// SwiftThicknessPicker
//
// Created by Maxim Bilan on 5/12/15.
// Copyright (c) 2015 Maxim Bilan. All rights reserved.
//
import UIKit
class ViewController: UIViewController, SwiftThicknessPickerDelegate {
@IBOutlet weak var horizontalThicknessPicker: SwiftThicknessPicker!
@IBOutlet weak var verticalThicknessPicker: SwiftThicknessPicker!
@IBOutlet weak var testLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
horizontalThicknessPicker.delegate = self
horizontalThicknessPicker.direction = SwiftThicknessPicker.PickerDirection.horizontal
horizontalThicknessPicker.minValue = 1
horizontalThicknessPicker.maxValue = 20
horizontalThicknessPicker.currentValue = 17
verticalThicknessPicker.delegate = self
verticalThicknessPicker.direction = SwiftThicknessPicker.PickerDirection.vertical
}
// MARK: - SwiftThicknessPickerDelegate
func valueChanged(_ value: Int) {
testLabel.text = "\(value)"
}
// MARK: - Actions
@IBAction func testButtonAction(_ sender: UIButton) {
horizontalThicknessPicker.currentValue = 11
verticalThicknessPicker.currentValue = 20
}
}
| 059d2d47a2ee848046f589df78a23948 | 25.295455 | 87 | 0.782195 | false | true | false | false |
wordpress-mobile/WordPress-iOS | refs/heads/trunk | WordPress/Classes/ViewRelated/Stats/Shared Views/Stats Detail/StatsReferrersChartViewModel.swift | gpl-2.0 | 1 | import Foundation
struct StatsReferrersChartViewModel {
let referrers: StatsTopReferrersTimeIntervalData
func makeReferrersChartView() -> UIView {
// The referrers chart currently shows 3 segments. If available, it will show:
// - WordPress.com Reader
// - Search
// - Other
// Unfortunately due to the results returned by the API this just has to be checked
// based on the title of the group, so it's really only possible for English-speaking users.
// When we can't find a WordPress.com Reader or Search Engines group, we'll just use the top
// two groups with the highest referrers count.
var topReferrers: [StatsReferrer] = []
var allReferrers = referrers.referrers
// First, find the WordPress.com and Search groups if we can
if let wpIndex = allReferrers.firstIndex(where: { $0.title.contains(Constants.wpComReferrerGroupTitle) }) {
topReferrers.append(allReferrers[wpIndex])
allReferrers.remove(at: wpIndex)
}
if let searchIndex = allReferrers.firstIndex(where: { $0.title.contains(Constants.searchEnginesReferrerGroupTitle) }) {
topReferrers.append(allReferrers[searchIndex])
allReferrers.remove(at: searchIndex)
}
// Then add groups from the top of the list to make up our target group count
while topReferrers.count < (Constants.referrersMaxGroupCount-1) && allReferrers.count > 0 {
topReferrers.append(allReferrers.removeFirst())
}
// Create segments for each referrer
var segments = topReferrers.enumerated().map({ index, item in
return DonutChartView.Segment(
title: Constants.referrersTitlesMap[item.title] ?? item.title,
value: CGFloat(item.viewsCount),
color: Constants.referrersSegmentColors[index]
)
})
// Create a segment for all remaining referrers – "Other"
let otherCount = allReferrers.map({ $0.viewsCount }).reduce(0, +) + referrers.otherReferrerViewsCount
let otherSegment = DonutChartView.Segment(
title: Constants.otherReferrerGroupTitle,
value: CGFloat(otherCount),
color: Constants.referrersSegmentColors.last!
)
segments.append(otherSegment)
let chartView = DonutChartView()
chartView.configure(title: Constants.chartTitle, totalCount: CGFloat(referrers.totalReferrerViewsCount), segments: segments)
chartView.translatesAutoresizingMaskIntoConstraints = false
chartView.heightAnchor.constraint(equalToConstant: Constants.chartHeight).isActive = true
return chartView
}
private enum Constants {
// Referrers
// These first two titles are not localized as they're used for string matching against the API response.
static let wpComReferrerGroupTitle = "WordPress.com Reader"
static let searchEnginesReferrerGroupTitle = "Search Engines"
static let otherReferrerGroupTitle = NSLocalizedString("Other", comment: "Title of Stats section that shows referrer traffic from other sources.")
static let chartTitle = NSLocalizedString("Views", comment: "Title for chart showing site views from various referrer sources.")
static let referrersMaxGroupCount = 3
static let referrersSegmentColors: [UIColor] = [
.muriel(name: .blue, .shade80),
.muriel(name: .blue, .shade50),
.muriel(name: .blue, .shade5)
]
static let referrersTitlesMap = [
"WordPress.com Reader": "WordPress",
"Search Engines": NSLocalizedString("Search", comment: "Title of Stats section that shows search engine referrer traffic.")
]
static let chartHeight: CGFloat = 231.0
}
}
| baf1c3ad88206defbc2bcbb658a8be20 | 46.207317 | 154 | 0.670369 | false | false | false | false |
jianwoo/ios-charts | refs/heads/master | Charts/Classes/Data/LineRadarChartDataSet.swift | apache-2.0 | 2 | //
// LineRadarChartDataSet.swift
// Charts
//
// Created by Daniel Cohen Gindi on 26/2/15.
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/ios-charts
//
import Foundation
public class LineRadarChartDataSet: BarLineScatterCandleChartDataSet
{
public var fillColor = UIColor(red: 140.0/255.0, green: 234.0/255.0, blue: 255.0/255.0, alpha: 1.0)
public var fillAlpha = CGFloat(0.33)
private var _lineWidth = CGFloat(1.0)
public var drawFilledEnabled = false
/// line width of the chart (min = 0.2f, max = 10f)
/// :default: 1
public var lineWidth: CGFloat
{
get
{
return _lineWidth;
}
set
{
_lineWidth = newValue;
if (_lineWidth < 0.2)
{
_lineWidth = 0.5;
}
if (_lineWidth > 10.0)
{
_lineWidth = 10.0;
}
}
}
public var isDrawFilledEnabled: Bool
{
return drawFilledEnabled;
}
// MARK: NSCopying
public override func copyWithZone(zone: NSZone) -> AnyObject
{
var copy = super.copyWithZone(zone) as! LineRadarChartDataSet;
copy.fillColor = fillColor;
copy._lineWidth = _lineWidth;
copy.drawFilledEnabled = drawFilledEnabled;
return copy;
}
}
| b484e62e1428ad5249d5cfb9dd0ffe5b | 23.533333 | 103 | 0.572011 | false | false | false | false |
alirsamar/BiOS | refs/heads/master | Alien Adventure/AlienAdventure1.swift | mit | 3 | //
// AlienAdventure1.swift
// Alien Adventure
//
// Created by Jarrod Parkes on 10/5/15.
// Copyright © 2015 Udacity. All rights reserved.
//
// MARK: - RequestTester (Alien Adventure 1 Tests)
extension UDRequestTester {
// MARK: ReverseLongString
func testReverseLongestName() -> Bool {
// check 1
if delegate.handleReverseLongestName([UDItem]()) != "" {
print("ReverseLongestName FAILED: If the inventory is empty, then the method should return \"\".")
return false
}
// check 2
if delegate.handleReverseLongestName(allItems()) != "akoozaBresaL" {
print("ReverseLongestName FAILED: The reverse longest string was not returned.")
return false
}
// check 3
if delegate.handleReverseLongestName(delegate.inventory) != "nonnaCresaL" {
print("ReverseLongestName FAILED: The reverse longest string was not returned.")
return false
}
return true
}
// MARK: MatchMoonRocks
func testMatchMoonRocks() -> Bool {
// check 1
let itemsFromCheck1 = delegate.handleMatchMoonRocks([UDItem]())
if itemsFromCheck1.count != 0 {
print("MatchMoonRocks FAILED: If the inventory is empty, then no MoonRocks should be returned.")
return false
}
// check 2
let itemsFromCheck2 = delegate.handleMatchMoonRocks(allItems())
var moonRocksCount2 = 0
for item in itemsFromCheck2 {
if item == UDItemIndex.items["MoonRock"]! {
moonRocksCount2 += 1
}
}
if moonRocksCount2 != 1 {
print("MatchMoonRocks FAILED: An incorrect number of MoonRocks was returned.")
return false
}
// check 3
let itemsFromCheck3 = delegate.handleMatchMoonRocks(delegate.inventory)
var moonRocksCount3 = 0
for item in itemsFromCheck3 {
if item == UDItemIndex.items["MoonRock"]! {
moonRocksCount3 += 1
}
}
if moonRocksCount3 != 2 || itemsFromCheck3.count != 2 {
print("MatchMoonRocks FAILED: An incorrect number of MoonRocks was returned.")
return false
}
return true
}
// MARK: InscriptionEternalStar
func testInscriptionEternalStar() -> Bool {
// check 1
if delegate.handleInscriptionEternalStar([UDItem]()) != nil {
print("InscriptionEternalStar FAILED: If the inventory is empty, then nil should be returned.")
return false
}
// check 2
let item = delegate.handleInscriptionEternalStar(delegate.inventory)
if item != UDItemIndex.items["GlowSphere"]! {
print("InscriptionEternalStar FAILED: The correct item was not returned.")
return false
}
return true
}
// MARK: LeastValuableItem
func testLeastValuableItem() -> Bool {
// check 1
if delegate.handleLeastValuableItem([UDItem]()) != nil {
print("LeastValuableItem FAILED: If the inventory is empty, then nil should be returned.")
return false
}
// check 2
let result2 = delegate.handleLeastValuableItem(allItems())
if result2 != UDItemIndex.items["Dust"]! {
print("LeastValuableItem FAILED: The least valuable item was not returned.")
return false
}
// check 3
let result3 = delegate.handleLeastValuableItem(delegate.inventory)
if result3 != UDItemIndex.items["MoonRubble"]! {
print("LeastValuableItem FAILED: The least valuable item was not returned.")
return false
}
return true
}
// MARK: ShuffleStrings
func testShuffleStrings() -> Bool {
// check 1
if !delegate.handleShuffleStrings(s1: "ab", s2: "cd", shuffle: "acbd") {
print("ShuffleStrings FAILED: The shuffle for the input (\"ab\", \"cd\", \"acbd\") is valid, but false was returned.")
return false
}
// check 2
if delegate.handleShuffleStrings(s1: "ab", s2: "cd", shuffle: "badc") {
print("ShuffleStrings FAILED: The shuffle for the input (\"ab\", \"cd\", \"badc\") is invalid, but true was returned.")
return false
}
// check 3
if !delegate.handleShuffleStrings(s1: "", s2: "", shuffle: "") {
print("ShuffleStrings FAILED: The shuffle for the input (\"\", \"\", \"\") is valid, but false was returned.")
return false
}
// check 4
if delegate.handleShuffleStrings(s1: "", s2: "", shuffle: "sdf") {
print("ShuffleStrings FAILED: The shuffle for the input (\"\", \"\", \"sdf\") is invalid, but true was returned.")
return false
}
// check 5
if delegate.handleShuffleStrings(s1: "ab", s2: "cd", shuffle: "abef") {
print("ShuffleStrings FAILED: The shuffle for the input (\"ab\", \"cd\", \"abef\") is invalid, but true was returned.")
return false
}
// check 6
if delegate.handleShuffleStrings(s1: "ab", s2: "cd", shuffle: "abdc") {
print("ShuffleStrings FAILED: The shuffle for the input (\"ab\", \"cd\", \"abdc\") is invalid, but true was returned.")
return false
}
return true
}
}
// MARK: - RequestTester (Alien Adventure 1 Process Requests)
extension UDRequestTester {
// MARK: ReverseLongString
func processReverseLongestName(failed: Bool) -> String {
if !failed {
let reverseLongestName = delegate.handleReverseLongestName(delegate.inventory)
return "Hero: \"How about \(reverseLongestName)?\""
} else {
return "Hero: \"Uhh... Udacity?\""
}
}
// MARK: MatchMoonRocks
func processMatchMoonRocks(failed: Bool) -> String {
if(!failed) {
let moonRocks = delegate.handleMatchMoonRocks(delegate.inventory)
delegate.inventory = delegate.inventory.filter({$0.name != "MoonRock"})
return "Hero: [Hands over \(moonRocks.count) MoonRocks]"
} else {
return "Hero: [Hands over some items (they might be MoonRocks...)]"
}
}
// MARK: InscriptionEternalStar
func processInscriptionEternalStar(failed: Bool) -> String {
var processingString = "Hero: [Hands over "
if let eternalStarItem = delegate.handleInscriptionEternalStar(delegate.inventory) {
processingString += "the \(eternalStarItem.name)]"
if(!failed) {
delegate.inventory = delegate.inventory.filter({$0.inscription == nil || $0 != eternalStarItem})
}
} else {
processingString += "NOTHING!]"
}
return processingString
}
// MARK: LeastValuableItem
func processLeastValuableItem(failed: Bool) -> String {
var processingString = "Hero: [Hands over "
if let leastValuableItem = delegate.handleLeastValuableItem(delegate.inventory) {
processingString += "the \(leastValuableItem.name)]"
if(!failed) {
for (idx, item) in delegate.inventory.enumerate() {
if item == leastValuableItem {
delegate.inventory.removeAtIndex(idx)
break
}
}
}
} else {
processingString += "NOTHING!]"
}
return processingString
}
// MARK: ShuffleStrings
func processShuffleStrings(failed: Bool) -> String {
// check 1
if !delegate.handleShuffleStrings(s1: "ab", s2: "cd", shuffle: "acbd") {
return "Hero: \"So is (\"ab\", \"cd\", \"acbd\") a valid shuffle? Umm... no?\""
}
// check 2
if delegate.handleShuffleStrings(s1: "ab", s2: "cd", shuffle: "badc") {
return "Hero: \"So is (\"ab\", \"cd\", \"badc\") a valid shuffle? Umm... yes?\""
}
// check 3
if !delegate.handleShuffleStrings(s1: "", s2: "", shuffle: "") {
return "Hero: \"So is (\"\", \"\", \"\") a valid shuffle? Umm... no?\""
}
// check 4
if delegate.handleShuffleStrings(s1: "", s2: "", shuffle: "sdf") {
return "Hero: \"So is (\"\", \"\", \"sdf\") a valid shuffle? Umm... yes?\""
}
// check 5
if delegate.handleShuffleStrings(s1: "ab", s2: "cd", shuffle: "abef") {
return "Hero: \"So is (\"ab\", \"cd\", \"abef\") a valid shuffle? Umm... yes?\""
}
// check 6
if delegate.handleShuffleStrings(s1: "ab", s2: "cd", shuffle: "abdc") {
return "Hero: \"So is (\"ab\", \"cd\", \"abdc\") a valid shuffle? Umm... yes?\""
}
return "Hero: \"So is (\"ab\", \"cd\", \"badc\") a valid shuffle? No it isn't!\""
}
} | 1bf01208545a634824f168e525084e0b | 33.277372 | 131 | 0.541582 | false | false | false | false |
ScoutHarris/WordPress-iOS | refs/heads/develop | WordPress/Classes/ViewRelated/NUX/LoginProloguePageViewController.swift | gpl-2.0 | 2 | import UIKit
class LoginProloguePageViewController: UIPageViewController {
var pages: [UIViewController] = []
fileprivate var pageControl: UIPageControl?
fileprivate var bgAnimation: UIViewPropertyAnimator?
fileprivate struct Constants {
static let pagerPadding: CGFloat = 9.0
static let pagerHeight: CGFloat = 0.13
}
override func viewDidLoad() {
super.viewDidLoad()
dataSource = self
delegate = self
pages.append(LoginProloguePromoViewController(as: .post))
pages.append(LoginProloguePromoViewController(as: .stats))
pages.append(LoginProloguePromoViewController(as: .reader))
pages.append(LoginProloguePromoViewController(as: .notifications))
pages.append(LoginProloguePromoViewController(as: .jetpack))
setViewControllers([pages[0]], direction: .forward, animated: false)
view.backgroundColor = backgroundColor(for: 0)
addPageControl()
}
func addPageControl() {
let newControl = UIPageControl()
newControl.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(newControl)
newControl.topAnchor.constraint(equalTo: view.topAnchor, constant: Constants.pagerPadding).isActive = true
newControl.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true
newControl.rightAnchor.constraint(equalTo: view.rightAnchor).isActive = true
newControl.heightAnchor.constraint(equalTo: view.heightAnchor, multiplier: Constants.pagerHeight).isActive = true
newControl.numberOfPages = pages.count
newControl.addTarget(self, action: #selector(handlePageControlValueChanged(sender:)), for: UIControlEvents.valueChanged)
pageControl = newControl
}
func handlePageControlValueChanged(sender: UIPageControl) {
guard let currentPage = viewControllers?.first,
let currentIndex = pages.index(of: currentPage) else {
return
}
let direction: UIPageViewControllerNavigationDirection = sender.currentPage > currentIndex ? .forward : .reverse
setViewControllers([pages[sender.currentPage]], direction: direction, animated: true)
WPAppAnalytics.track(.loginProloguePaged)
}
fileprivate func animateBackground(for index: Int, duration: TimeInterval = 0.5) {
bgAnimation?.stopAnimation(true)
bgAnimation = UIViewPropertyAnimator(duration: 0.5, curve: .easeOut) { [weak self] in
self?.view.backgroundColor = self?.backgroundColor(for: index)
}
bgAnimation?.startAnimation()
}
fileprivate func backgroundColor(for index: Int) -> UIColor {
switch index % 2 {
case 0:
return WPStyleGuide.lightBlue()
case 1:
fallthrough
default:
return WPStyleGuide.wordPressBlue()
}
}
}
extension LoginProloguePageViewController: UIPageViewControllerDataSource {
func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? {
guard let index = pages.index(of: viewController) else {
return nil
}
if index > 0 {
return pages[index - 1]
}
return nil
}
func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? {
guard let index = pages.index(of: viewController) else {
return nil
}
if index < pages.count - 1 {
return pages[index + 1]
}
return nil
}
}
extension LoginProloguePageViewController: UIPageViewControllerDelegate {
func pageViewController(_ pageViewController: UIPageViewController, didFinishAnimating finished: Bool, previousViewControllers: [UIViewController], transitionCompleted completed: Bool) {
let toVC = previousViewControllers[0]
guard let index = pages.index(of: toVC) else {
return
}
if !completed {
pageControl?.currentPage = index
animateBackground(for: index, duration: 0.2)
} else {
WPAppAnalytics.track(.loginProloguePaged)
}
}
func pageViewController(_ pageViewController: UIPageViewController, willTransitionTo pendingViewControllers: [UIViewController]) {
let toVC = pendingViewControllers[0]
guard let index = pages.index(of: toVC) else {
return
}
animateBackground(for: index)
pageControl?.currentPage = index
}
}
| 30b125d89d44f99d7f2460b9afc87acd | 36.991803 | 190 | 0.681122 | false | false | false | false |
Kawoou/KWDrawerController | refs/heads/master | DrawerController/Animator/DrawerBounceEaseAnimator.swift | mit | 1 | /*
The MIT License (MIT)
Copyright (c) 2017 Kawoou (Jungwon An)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
import UIKit
open class DrawerBounceEaseAnimator: DrawerTickAnimator {
// MARK: - Enum
public enum EaseType {
case easeIn
case easeOut
case easeInOut
internal func algorithm(value: Double) -> Double {
switch self {
case .easeIn:
let outEase: EaseType = .easeOut
return 1 - outEase.algorithm(value: 1 - value)
case .easeOut:
if value < 4 / 11.0 {
return (121 * value * value) / 16.0
} else if value < 8 / 11.0 {
return (363 / 40.0 * value * value) - (99 / 10.0 * value) + 17 / 5.0
} else if value < 9 / 10.0 {
return (4356 / 361.0 * value * value) - (35442 / 1805.0 * value) + 16061 / 1805.0
} else {
return (54 / 5.0 * value * value) - (513 / 25.0 * value) + 268 / 25.0
}
case .easeInOut:
let inEase: EaseType = .easeIn
let outEase: EaseType = .easeOut
if value < 0.5 {
return 0.5 * inEase.algorithm(value: value * 2)
} else {
return 0.5 * outEase.algorithm(value: value * 2 - 1) + 0.5
}
}
}
}
// MARK: - Property
open var easeType: EaseType
// MARK: - Public
open override func tick(delta: TimeInterval, duration: TimeInterval, animations: @escaping (Float)->()) {
animations(Float(easeType.algorithm(value: delta / duration)))
}
// MARK: - Lifecycle
public init(easeType: EaseType = .easeInOut) {
self.easeType = easeType
super.init()
}
}
| d707cad17a67477203d18bf4eb923c3f | 32.988372 | 109 | 0.584331 | false | false | false | false |
devgabrielcoman/woodhouse | refs/heads/master | Pod/Classes/Transformers/Transform+Zomato+OpenMenu.swift | gpl-3.0 | 1 | //
// Transform+Zomato+OpenMenu.swift
// Pods
//
// Created by Gabriel Coman on 17/04/2016.
//
//
import UIKit
import KeyPathTransformer
import Dollar
func mapZomatoToOMenu(locu: [String:AnyObject]) -> [String:AnyObject] {
let woodhouse_id = String.createUUID(32)
let t = Transform<AnyObject>(locu)
// [OK] metadata
t["uuid"] = String.createOmfUUID()
t["accuracy"] = 1
t["created_date"] = NSDate.omfNowDate()
t["open_menu.version"] = "1.6"
// [OK] restaurant info
// details subset
t["restaurant_info.restaurant_name"] = t["restaurant.name"]
t["restaurant_info.brief_description"] = ""
t["restaurant_info.business_type"] = "independent"
// location subset
t["restaurant_info.address_1"] = t["restaurant.location.address"]
t["restaurant_info.city_town"] = t["restaurant.location.city"]
t["restaurant_info.country"] = t["restaurant.location.country_id"]
t["restaurant_info.postal_code"] = t["restaurant.location.zipcode"]
t["restaurant_info.latitude"] = t["restaurant.location.latitude"]
t["restaurant_info.longitude"] = t["restaurant.location.longitude"]
// contact subset
t["restaurant_info.phone"] = t["restaurant.phone_numbers"]
t["restaurant_info.website_url"] = t["restaurant.url"]
t["restaurant_info.omf_file_url"] = "http://sa-test-moat.herokuapp.com/static/sample.xml"
// [OK] Environment
// cuisine_type_primary subset
t["restaurant_info.environment.cuisine_type_primary"] = t["restaurant.cuisines"]
// seating_locations subset
t["restaurant_info.environment.seating_locations"] = ["indoor"]
// accepted_currencies subset
var accepted_currencies: [String] = []
if let symbol = t["restaurant.currency"] as? String {
accepted_currencies.append(symbol)
}
if accepted_currencies.count == 0 {
accepted_currencies.append("USD")
}
t["restaurant_info.environment.accepted_currencies"] = accepted_currencies
// operating days subset
t["operating_days"] = []
return t.result()
} | dd58ad964173750f5cff11c1afaabe36 | 31.828125 | 93 | 0.655714 | false | false | false | false |
JQJoe/RxDemo | refs/heads/develop | Carthage/Checkouts/RxSwift/Tests/RxCocoaTests/UIButton+RxTests.swift | apache-2.0 | 7 | //
// UIButton+RxTests.swift
// Tests
//
// Created by Krunoslav Zaher on 6/24/16.
// Copyright © 2016 Krunoslav Zaher. All rights reserved.
//
import Foundation
import RxTest
import RxCocoa
import UIKit
import RxSwift
import XCTest
class RxButtonTests: RxTest {
func testTitleNormal() {
let button = UIButton(frame: CGRect(x: 0, y: 0, width: 1, height: 1))
XCTAssertFalse(button.title(for: []) == "normal")
_ = Observable.just("normal").subscribe(button.rx.title(for: []))
XCTAssertTrue(button.title(for: []) == "normal")
}
func testTitleSelected() {
let button = UIButton(frame: CGRect(x: 0, y: 0, width: 1, height: 1))
XCTAssertFalse(button.title(for: .selected) == "normal")
_ = Observable.just("normal").subscribe(button.rx.title(for: .selected))
XCTAssertTrue(button.title(for: .selected) == "normal")
}
func testTitleDefault() {
let button = UIButton(frame: CGRect(x: 0, y: 0, width: 1, height: 1))
XCTAssertFalse(button.title(for: []) == "normal")
_ = Observable.just("normal").subscribe(button.rx.title())
XCTAssertTrue(button.title(for: []) == "normal")
}
}
| 9977b7316d2a29a38d028c586660faef | 28.975 | 80 | 0.627189 | false | true | false | false |
Dreezydraig/actor-platform | refs/heads/master | actor-apps/app-ios/ActorApp/Controllers/Conversation/Cells/BubbleBackgroundProcessor.swift | mit | 14 | //
// Copyright (c) 2014-2015 Actor LLC. <https://actor.im>
//
import Foundation
//class BubbleBackgroundProcessor: NSObject, ARBackgroundProcessor {
//
// let layoutCache: LayoutCache = LayoutCache()
//
// func processInBackgroundWithId(item: AnyObject!) {
// var message = item as! ACMessage
//
// Actor.getUserWithUid(message.senderId)
//
// var cached = layoutCache.pick(message.rid)
// if (cached != nil) {
// return
// }
//
// println("process \(message.rid)")
// var layout = MessagesLayouting.buildLayout(message, layoutCache: layoutCache)
// self.layoutCache.cache(message.rid, layout: layout)
// }
//}
class ListProcessor: NSObject, ARListProcessor {
let layoutCache: LayoutCache = LayoutCache()
let isGroup: Bool
init(isGroup: Bool) {
self.isGroup = isGroup
}
func buildLayout(message: ACMessage) {
Actor.getUserWithUid(message.senderId)
var cached = layoutCache.pick(message.rid)
if (cached != nil) {
return
}
var layout = MessagesLayouting.buildLayout(message, layoutCache: layoutCache)
self.layoutCache.cache(message.rid, layout: layout)
}
func processWithItems(items: JavaUtilList!, withPrevious previous: AnyObject!) -> AnyObject! {
var objs = [ACMessage]()
var indexes = [jlong: Int]()
for i in 0..<items.size() {
var msg = items.getWithInt(i) as! ACMessage
indexes.updateValue(Int(i), forKey: msg.rid)
objs.append(msg)
}
var settings = [CellSetting]()
for i in 0..<objs.count {
settings.append(buildCellSetting(i, items: objs))
}
var layouts = [CellLayout]()
for i in 0..<objs.count {
layouts.append(MessagesLayouting.buildLayout(objs[i], layoutCache: layoutCache))
}
var forceUpdates = [Bool]()
var updates = [Bool]()
if let prevList = previous as? PreprocessedList {
for i in 0..<objs.count {
var obj = objs[i]
var oldIndex = prevList.indexMap[obj.rid]
if oldIndex != nil {
var oldSetting = prevList.cellSettings[oldIndex!]
var setting = settings[i]
if setting.clenchTop != oldSetting.clenchTop || setting.clenchBottom != oldSetting.clenchBottom || setting.showDate != oldSetting.showDate {
if setting.showDate != oldSetting.showDate {
forceUpdates.append(true)
updates.append(false)
} else {
forceUpdates.append(false)
updates.append(true)
}
} else {
forceUpdates.append(false)
updates.append(false)
}
} else {
forceUpdates.append(false)
updates.append(false)
}
}
} else {
for i in 0..<objs.count {
forceUpdates.append(false)
updates.append(false)
}
}
var heights = [CGFloat]()
for i in 0..<objs.count {
heights.append(buildHeight(i, items: objs, settings: settings))
}
var res = PreprocessedList()
res.items = objs
res.cellSettings = settings
res.layouts = layouts
res.layoutCache = layoutCache
res.heights = heights
res.indexMap = indexes
res.forceUpdated = forceUpdates
res.updated = updates
return res
}
func buildCellSetting(index: Int, items: [ACMessage]) -> CellSetting {
var current = items[index]
var next: ACMessage! = index > 0 ? items[index - 1] : nil
var prev: ACMessage! = index + 1 < items.count ? items[index + 1] : nil
var isShowDate = true
var isShowDateNext = true
var clenchTop = false
var clenchBottom = false
if (prev != nil) {
isShowDate = !areSameDate(current, prev: prev)
if !isShowDate {
clenchTop = useCompact(current, next: prev)
}
}
if (next != nil) {
if areSameDate(next, prev: current) {
clenchBottom = useCompact(current, next: next)
}
}
return CellSetting(showDate: isShowDate, clenchTop: clenchTop, clenchBottom: clenchBottom)
}
func areSameDate(source:ACMessage, prev: ACMessage) -> Bool {
let calendar = NSCalendar.currentCalendar()
var currentDate = NSDate(timeIntervalSince1970: Double(source.date)/1000.0)
var currentDateComp = calendar.components(.CalendarUnitDay | .CalendarUnitYear | .CalendarUnitMonth, fromDate: currentDate)
var nextDate = NSDate(timeIntervalSince1970: Double(prev.date)/1000.0)
var nextDateComp = calendar.components(.CalendarUnitDay | .CalendarUnitYear | .CalendarUnitMonth, fromDate: nextDate)
return (currentDateComp.year == nextDateComp.year && currentDateComp.month == nextDateComp.month && currentDateComp.day == nextDateComp.day)
}
func useCompact(source: ACMessage, next: ACMessage) -> Bool {
if (source.content is ACServiceContent) {
if (next.content is ACServiceContent) {
return true
}
} else {
if (next.content is ACServiceContent) {
return false
}
if (source.senderId == next.senderId) {
return true
}
}
return false
}
func buildHeight(index: Int, items: [ACMessage], settings: [CellSetting]) -> CGFloat {
var message = items[index]
var setting = settings[index]
return MessagesLayouting.measureHeight(message, group: isGroup, setting: setting, layoutCache: layoutCache)
}
}
@objc class PreprocessedList {
var items: [ACMessage]!
var cellSettings: [CellSetting]!
var layouts: [CellLayout]!
var layoutCache: LayoutCache!
var heights: [CGFloat]!
var forceUpdated: [Bool]!
var updated: [Bool]!
var indexMap: [jlong: Int]!
} | 8abaebf38ec0ee732bbbdc5c187ef6ff | 33.415789 | 160 | 0.551086 | false | false | false | false |
scottrhoyt/Noonian | refs/heads/master | Sources/NoonianKit/Utilities/String+NoonianKit.swift | mit | 1 | //
// String+NoonianKit.swift
// Noonian
//
// Created by Scott Hoyt on 11/4/16.
// Copyright © 2016 Scott Hoyt. All rights reserved.
//
import Foundation
public extension String {
func pathByAdding(component: String) -> String {
var path = self
var component = component
if !path.isEmpty && path.characters.last == "/" { path.remove(at: path.index(before: path.endIndex)) }
if !component.isEmpty && component.characters.first == "/" { component.remove(at: component.startIndex) }
return path + "/" + component
}
var isAbsolutePath: Bool {
return characters.first == "/"
}
public func absolutePathRepresentation(rootDirectory: String = FileManager.default.currentDirectoryPath) -> String {
if isAbsolutePath {
return self as String
}
return rootDirectory.pathByAdding(component: self)
}
}
| 9e02327ea5b762a19c30c4c82b8d8684 | 26.515152 | 120 | 0.643172 | false | false | false | false |
odemolliens/blockchain-ios-sdk | refs/heads/master | SDK_SWIFT/ODBlockChainWallet/ODBlockChainWallet/Domain/ODPaymentResults.swift | apache-2.0 | 1 | //
//Copyright 2014 Olivier Demolliens - @odemolliens
//
//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
/**
{ "message" : "Response Message" , "tx_hash": "Transaction Hash", "notice" : "Additional Message" }
{ "message" : "Sent 0.1 BTC to 1A8JiWcwvpY7tAopUkSnGuEYHmzGYfZPiq" , "tx_hash" : "f322d01ad784e5deeb25464a5781c3b20971c1863679ca506e702e3e33c18e9c" , "notice" : "Some funds are pending confirmation and cannot be spent yet (Value 0.001 BTC)" }
*/
class ODPaymentResults : NSObject
{
var message : NSString;
var txHash : NSString;
var notice : NSString;
// MARK: Constructor
override init()
{
message = "";
txHash = "";
notice = "";
}
// MARK: Static Methods
class func instantiateWithDictionnary(dic:NSDictionary) -> ODPaymentResults
{
var paymentResult : ODPaymentResults = ODPaymentResults();
paymentResult.message = dic.valueForKey("message") as NSString!;
paymentResult.txHash = dic.valueForKey("tx_hash") as NSString!;
paymentResult.notice = dic.valueForKey("notice") as NSString!;
return paymentResult;
}
class func parseErrorResponseFromAPI(response:NSString) -> ODBCErrorAPI
{
// TODO : undev
if(response.isEqualToString(kBCCommonNull) || response.isEqualToString(kBCCommonCloudFare)){
return ODBCErrorAPI.ApiUnavailable;
}else{
return ODBCErrorAPI.Unknow;
}
}
// MARK: Methods
} | 5db2db41ca9468ebaa504f1e33c49210 | 29.863636 | 242 | 0.675835 | false | false | false | false |
SASAbus/SASAbus-ios | refs/heads/master | SASAbus/Data/Networking/RestClient.swift | gpl-3.0 | 1 | import Foundation
import Alamofire
import RxSwift
import RxCocoa
import SwiftyJSON
class RestClient {
// - MARK: Internal network requests
static func getInternal(_ endpoint: String, parameters: Parameters? = nil) -> Alamofire.DataRequest {
return request(endpoint, method: .get, parameters: parameters)
}
static func postInternal(_ endpoint: String, parameters: Parameters? = nil) -> Alamofire.DataRequest {
return request(endpoint, method: .post, parameters: parameters)
}
static func putInternal(_ endpoint: String, parameters: Parameters? = nil) -> Alamofire.DataRequest {
return request(endpoint, method: .put, parameters: parameters)
}
static func deleteInternal(_ endpoint: String, parameters: Parameters? = nil) -> Alamofire.DataRequest {
return request(endpoint, method: .delete, parameters: parameters)
}
static func request(_ endpoint: String, method: HTTPMethod, parameters: Parameters? = nil) -> Alamofire.DataRequest {
var host = Endpoint.apiUrl
if endpoint.starts(with: "realtime") {
host = Endpoint.realtimeApiUrl
}
let url = host + endpoint
let headers = getHeaders(url)
Log.debug("\(method.rawValue.uppercased()): \(url)")
return Alamofire.request(url, method: method, parameters: parameters, headers: headers)
}
// - MARK: Headers
static func getHeaders(_ url: URLConvertible) -> [String : String] {
let versionCode = Bundle.main.versionCode
let versionName = Bundle.main.versionName
var headers = [
"User-Agent": "SasaBus iOS",
"X-Device": DeviceUtils.getModel(),
"X-Language": Locales.get(),
"X-Version-Code": versionCode,
"X-Version-Name": versionName,
"X-Android-Id": DeviceUtils.getIdentifier()
]
if requiresAuthHeader(try! url.asURL().pathComponents) {
let token = AuthHelper.getTokenIfValid()
if let token = token {
headers["Authorization"] = "Bearer \(token)"
} else {
Log.error("Token is invalid")
}
}
return headers
}
static func requiresAuthHeader(_ segments: [String]) -> Bool {
if segments.count <= 3 {
return false
}
let path = segments[2]
let segment = segments[3]
if path == "eco" || path == "sync" {
return true
}
if path == "auth" {
if segment == "password" || segment == "logout" || segment == "delete" {
return true
}
}
return false
}
}
extension RestClient {
static func get<T:JSONable>(_ url: String, index: String) -> Observable<T?> {
return Observable<T?>.create { observer -> Disposable in
let requestReference = getInternal(url)
.responseJSON(completionHandler: { response in
if response.result.isSuccess {
let json = JSON(response.result.value)
if json[index].exists() {
let items = json[index].arrayValue
if !items.isEmpty {
let casted = items[0].to(type: T.self) as? T
observer.on(.next(casted))
} else {
let casted = json[index].to(type: T.self) as? T
observer.on(.next(casted))
}
} else {
observer.onError(Errors.json(message: "Index '\(index)' does not exist in JSON for url '\(url)'"))
}
observer.onCompleted()
} else {
observer.onError(response.result.error!)
}
})
return Disposables.create {
requestReference.cancel()
}
}
}
static func get<T:JSONable>(_ url: String, index: String) -> Observable<[T]> {
return Observable<[T]>.create { observer -> Disposable in
let requestReference = getInternal(url)
.responseJSON(completionHandler: { response in
if response.result.isSuccess {
let json = JSON(response.result.value)
var items: [T] = []
if let item = json[index].to(type: T.self) {
items = item as! [T]
}
observer.onNext(items)
observer.onCompleted()
} else {
observer.onError(response.result.error!)
}
})
return Disposables.create {
requestReference.cancel()
}
}
}
static func getJson(_ url: String) -> Observable<JSON> {
return Observable<JSON>.create { observer -> Disposable in
let requestReference = getInternal(url)
.responseJSON(completionHandler: { response in
if response.result.isSuccess {
observer.onNext(JSON(response.result.value))
observer.onCompleted()
} else {
observer.onError(response.result.error!)
}
})
return Disposables.create {
requestReference.cancel()
}
}
}
}
extension RestClient {
static func post(_ url: String, parameters: Parameters? = nil) -> Observable<JSON> {
return Observable<JSON>.create { observer -> Disposable in
let requestReference = postInternal(url, parameters: parameters)
.responseJSON(completionHandler: { response in
if response.result.isSuccess {
let json = JSON(response.result.value)
observer.onNext(json)
observer.onCompleted()
} else {
observer.onError(response.result.error!)
}
})
return Disposables.create {
requestReference.cancel()
}
}
}
static func post(_ url: String, parameters: Parameters? = nil) -> Observable<Void?> {
return Observable<Void?>.create { observer -> Disposable in
let requestReference = postInternal(url, parameters: parameters)
.response(completionHandler: { response in
if response.error == nil {
observer.onNext(nil)
observer.onCompleted()
} else {
observer.onError(response.error!)
}
})
return Disposables.create {
requestReference.cancel()
}
}
}
}
extension RestClient {
static func delete(_ url: String, parameters: Parameters? = nil) -> Observable<Void?> {
return Observable<Void?>.create { observer -> Disposable in
let requestReference = deleteInternal(url, parameters: parameters)
.response(completionHandler: { response in
if response.error == nil {
observer.onNext(nil)
observer.onCompleted()
} else {
observer.onError(response.error!)
}
})
return Disposables.create {
requestReference.cancel()
}
}
}
}
extension RestClient {
static func put<T:JSONable>(_ url: String, index: String) -> Observable<T?> {
return Observable<T?>.create { observer -> Disposable in
let requestReference = putInternal(url)
.responseJSON(completionHandler: { response in
if response.result.isSuccess {
let json = JSON(response.result.value)
if json[index].exists() {
let items = json[index].arrayValue
if !items.isEmpty {
let casted = items[0].to(type: T.self) as? T
observer.on(.next(casted))
} else {
let casted = json[index].to(type: T.self) as? T
observer.on(.next(casted))
}
} else {
observer.on(.next(nil))
}
observer.onCompleted()
} else {
observer.onError(response.result.error!)
}
})
return Disposables.create {
requestReference.cancel()
}
}
}
static func putNoResponse(_ url: String) -> Observable<Any?> {
return Observable<Any?>.create { observer -> Disposable in
let requestReference = putInternal(url).response { response in
if response.error == nil {
observer.onNext(nil)
observer.onCompleted()
} else {
observer.onError(response.error!)
}
}
return Disposables.create {
requestReference.cancel()
}
}
}
static func putBody(_ url: String, json body: String) -> Observable<JSON> {
return Observable<JSON>.create { observer -> Disposable in
let fullUrl = "\(Endpoint.apiUrl)\(url)"
var request = URLRequest(url: URL(string: fullUrl)!)
request.httpMethod = HTTPMethod.put.rawValue
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
let data = body.data(using: .utf8)
request.httpBody = data
Log.debug("POST: \(fullUrl)")
let headers = getHeaders(fullUrl)
request.allHTTPHeaderFields = headers
let requestReference = Alamofire.request(request).responseJSON { response in
if response.result.isSuccess {
let json = JSON(response.result.value)
observer.onNext(json)
observer.onCompleted()
} else {
observer.onError(response.result.error!)
}
}
return Disposables.create {
requestReference.cancel()
}
}
}
}
| a7e23544ce5aa360fc6e562a802b089b | 34.529968 | 130 | 0.478647 | false | false | false | false |
PerfectlySoft/Perfect-Authentication | refs/heads/master | Sources/OAuth2/OAuth2.swift | apache-2.0 | 1 | //
// OAuth2.swift
// Based on Turnstile's oAuth2
//
// Created by Edward Jiang on 8/7/16.
//
// Modified by Jonathan Guthrie 18 Jan 2017
// Intended to work more independantly of Turnstile
import Foundation
import PerfectHTTP
/**
OAuth 2 represents the base API Client for an OAuth 2 server that implements the
authorization code grant type. This is the typical redirect based login flow.
Since OAuth doesn't define token validation, implementing it is up to a subclass.
*/
open class OAuth2 {
/// The Client ID for the OAuth 2 Server
public let clientID: String
/// The Client Secret for the OAuth 2 Server
public let clientSecret: String
/// The Authorization Endpoint of the OAuth 2 Server
public let authorizationURL: String
/// The Token Endpoint of the OAuth 2 Server
public let tokenURL: String
/// Creates the OAuth 2 client
public init(clientID: String, clientSecret: String, authorizationURL: String, tokenURL: String) {
self.clientID = clientID
self.clientSecret = clientSecret
self.authorizationURL = authorizationURL
self.tokenURL = tokenURL
}
/// Gets the login link for the OAuth 2 server. Redirect the end user to this URL
///
/// - parameter redirectURL: The URL for the server to redirect the user back to after login.
/// You will need to configure this in the admin console for the OAuth provider's site.
/// - parameter state: A randomly generated string to prevent CSRF attacks.
/// Verify this when validating the Authorization Code
/// - parameter scopes: A list of OAuth scopes you'd like the user to grant
open func getLoginLink(redirectURL: String, state: String, scopes: [String] = []) -> String {
var url = "\(authorizationURL)?response_type=code"
url += "&client_id=\(clientID.stringByEncodingURL)"
url += "&redirect_uri=\(redirectURL.stringByEncodingURL)"
url += "&state=\(state.stringByEncodingURL)"
url += "&scope=\((scopes.joined(separator: " ")).stringByEncodingURL)"
return url
}
/// Exchanges an authorization code for an access token
/// - throws: InvalidAuthorizationCodeError() if the Authorization Code could not be validated
/// - throws: APIConnectionError() if we cannot connect to the OAuth server
/// - throws: InvalidAPIResponse() if the server does not respond in a way we expect
open func exchange(authorizationCode: AuthorizationCode) throws -> OAuth2Token {
let postBody = ["grant_type": "authorization_code",
"client_id": clientID,
"client_secret": clientSecret,
"redirect_uri": authorizationCode.redirectURL,
"code": authorizationCode.code]
// let (_, data, _, _) = makeRequest(.post, tokenURL, body: urlencode(dict: postBody), encoding: "form")
let data = makeRequest(.post, tokenURL, body: urlencode(dict: postBody), encoding: "form")
guard let token = OAuth2Token(json: data) else {
if let error = OAuth2Error(json: data) {
throw error
} else {
throw InvalidAPIResponse()
}
}
return token
}
/// Parses a URL and exchanges the OAuth 2 access token and exchanges it for an access token
/// - throws: InvalidAuthorizationCodeError() if the Authorization Code could not be validated
/// - throws: APIConnectionError() if we cannot connect to the OAuth server
/// - throws: InvalidAPIResponse() if the server does not respond in a way we expect
/// - throws: OAuth2Error() if the oauth server calls back with an error
open func exchange(request: HTTPRequest, state: String, redirectURL: String) throws -> OAuth2Token {
//request.param(name: "state") == state
guard let code = request.param(name: "code")
else {
print("Where's the code?")
throw InvalidAPIResponse()
}
return try exchange(authorizationCode: AuthorizationCode(code: code, redirectURL: redirectURL))
}
// TODO: add refresh token support
}
extension URLComponents {
var queryDictionary: [String: String] {
var result = [String: String]()
guard let components = query?.components(separatedBy: "&") else {
return result
}
components.forEach { component in
let queryPair = component.components(separatedBy: "=")
if queryPair.count == 2 {
result[queryPair[0]] = queryPair[1]
} else {
result[queryPair[0]] = ""
}
}
return result
}
}
extension URLComponents {
mutating func setQueryItems(dict: [String: String]) {
query = dict.map { (key, value) in
return key + "=" + value
}.joined(separator: "&")
}
}
| afd210aa2f9419d0a999973661dfc3fd | 38.222222 | 105 | 0.637798 | false | false | false | false |
JGiola/swift | refs/heads/main | test/Interop/Cxx/foreign-reference/move-only.swift | apache-2.0 | 5 | // RUN: %target-run-simple-swift(-I %S/Inputs/ -Xfrontend -enable-experimental-cxx-interop -Xfrontend -validate-tbd-against-ir=none -Xfrontend -disable-llvm-verify)
//
// REQUIRES: executable_test
import StdlibUnittest
import MoveOnly
@inline(never)
func blackHole(_ t: (BadCopyCtor, BadCopyCtor)) { }
var MoveOnlyTestSuite = TestSuite("Move only types that are marked as foreign references")
MoveOnlyTestSuite.test("MoveOnly") {
var x = MoveOnly.create()
expectEqual(x.test(), 42)
expectEqual(x.testMutable(), 42)
x = MoveOnly.create()
expectEqual(x.test(), 42)
}
MoveOnlyTestSuite.test("NoCopyMove") {
var x = NoCopyMove.create()
expectEqual(x.test(), 42)
expectEqual(x.testMutable(), 42)
x = NoCopyMove.create()
expectEqual(x.test(), 42)
}
MoveOnlyTestSuite.test("PrivateCopyCtor") {
var x = PrivateCopyCtor.create()
expectEqual(x.test(), 42)
expectEqual(x.testMutable(), 42)
x = PrivateCopyCtor.create()
expectEqual(x.test(), 42)
}
MoveOnlyTestSuite.test("BadCopyCtor") {
var x = BadCopyCtor.create()
expectEqual(x.test(), 42)
expectEqual(x.testMutable(), 42)
x = BadCopyCtor.create()
expectEqual(x.test(), 42)
let t = (x, x) // Copy this around just to make sure we don't call the copy ctor.
blackHole(t)
}
runAllTests()
| 4984dfeab834d806c3905bc45672893f | 23.673077 | 164 | 0.707716 | false | true | false | false |
ps2/rileylink_ios | refs/heads/dev | NightscoutUploadKit/Models/LoopSettings.swift | mit | 1 | //
// LoopSettings.swift
// NightscoutUploadKit
//
// Created by Pete Schwamb on 4/21/20.
// Copyright © 2020 Pete Schwamb. All rights reserved.
//
import Foundation
public struct LoopSettings {
typealias RawValue = [String: Any]
public let dosingEnabled: Bool
public let overridePresets: [TemporaryScheduleOverride]
public let scheduleOverride: TemporaryScheduleOverride?
public let minimumBGGuard: Double?
public let preMealTargetRange: ClosedRange<Double>?
public let maximumBasalRatePerHour: Double?
public let maximumBolus: Double?
public let deviceToken: String?
public let bundleIdentifier: String?
public let dosingStrategy: String?
public init(dosingEnabled: Bool, overridePresets: [TemporaryScheduleOverride], scheduleOverride: TemporaryScheduleOverride?, minimumBGGuard: Double?, preMealTargetRange: ClosedRange<Double>?, maximumBasalRatePerHour: Double?, maximumBolus: Double?,
deviceToken: String?, bundleIdentifier: String?, dosingStrategy: String?) {
self.dosingEnabled = dosingEnabled
self.overridePresets = overridePresets
self.scheduleOverride = scheduleOverride
self.minimumBGGuard = minimumBGGuard
self.preMealTargetRange = preMealTargetRange
self.maximumBasalRatePerHour = maximumBasalRatePerHour
self.maximumBolus = maximumBolus
self.deviceToken = deviceToken
self.bundleIdentifier = bundleIdentifier
self.dosingStrategy = dosingStrategy
}
public var dictionaryRepresentation: [String: Any] {
var rval: [String: Any] = [
"dosingEnabled": dosingEnabled,
"overridePresets": overridePresets.map { $0.dictionaryRepresentation },
]
rval["minimumBGGuard"] = minimumBGGuard
rval["scheduleOverride"] = scheduleOverride?.dictionaryRepresentation
if let preMealTargetRange = preMealTargetRange {
rval["preMealTargetRange"] = [preMealTargetRange.lowerBound, preMealTargetRange.upperBound]
}
rval["maximumBasalRatePerHour"] = maximumBasalRatePerHour
rval["maximumBolus"] = maximumBolus
rval["deviceToken"] = deviceToken
rval["dosingStrategy"] = dosingStrategy
if let bundleIdentifier = bundleIdentifier {
rval["bundleIdentifier"] = bundleIdentifier
}
return rval
}
init?(rawValue: RawValue) {
guard
let dosingEnabled = rawValue["dosingEnabled"] as? Bool,
let overridePresetsRaw = rawValue["overridePresets"] as? [TemporaryScheduleOverride.RawValue]
else {
return nil
}
self.dosingEnabled = dosingEnabled
self.overridePresets = overridePresetsRaw.compactMap { TemporaryScheduleOverride(rawValue: $0) }
if let scheduleOverrideRaw = rawValue["scheduleOverride"] as? TemporaryScheduleOverride.RawValue {
scheduleOverride = TemporaryScheduleOverride(rawValue: scheduleOverrideRaw)
} else {
scheduleOverride = nil
}
minimumBGGuard = rawValue["minimumBGGuard"] as? Double
if let preMealTargetRangeRaw = rawValue["preMealTargetRange"] as? [Double], preMealTargetRangeRaw.count == 2 {
preMealTargetRange = ClosedRange(uncheckedBounds: (lower: preMealTargetRangeRaw[0], upper: preMealTargetRangeRaw[1]))
} else {
preMealTargetRange = nil
}
maximumBasalRatePerHour = rawValue["maximumBasalRatePerHour"] as? Double
maximumBolus = rawValue["maximumBolus"] as? Double
deviceToken = rawValue["deviceToken"] as? String
bundleIdentifier = rawValue["bundleIdentifier"] as? String
dosingStrategy = rawValue["dosingStrategy"] as? String
}
}
| e50e968b8e65e13fe60359839fc9edb3 | 38.915789 | 252 | 0.694884 | false | false | false | false |
123kyky/SteamReader | refs/heads/develop | 02-SnapKit/vendor-swift02/Pods/SnapKit/Source/Debugging.swift | apache-2.0 | 98 | //
// SnapKit
//
// Copyright (c) 2011-2015 SnapKit Team - https://github.com/SnapKit
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#if os(iOS) || os(tvOS)
import UIKit
#else
import AppKit
#endif
/**
Used to allow adding a snp_label to a View for debugging purposes
*/
public extension View {
public var snp_label: String? {
get {
return objc_getAssociatedObject(self, &labelKey) as? String
}
set {
objc_setAssociatedObject(self, &labelKey, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_COPY_NONATOMIC)
}
}
}
/**
Used to allow adding a snp_label to a LayoutConstraint for debugging purposes
*/
public extension LayoutConstraint {
public var snp_label: String? {
get {
return objc_getAssociatedObject(self, &labelKey) as? String
}
set {
objc_setAssociatedObject(self, &labelKey, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_COPY_NONATOMIC)
}
}
override public var description: String {
var description = "<"
description += descriptionForObject(self)
description += " \(descriptionForObject(self.firstItem))"
if self.firstAttribute != .NotAnAttribute {
description += ".\(self.firstAttribute.snp_description)"
}
description += " \(self.relation.snp_description)"
if let secondItem: AnyObject = self.secondItem {
description += " \(descriptionForObject(secondItem))"
}
if self.secondAttribute != .NotAnAttribute {
description += ".\(self.secondAttribute.snp_description)"
}
if self.multiplier != 1.0 {
description += " * \(self.multiplier)"
}
if self.secondAttribute == .NotAnAttribute {
description += " \(self.constant)"
} else {
if self.constant > 0.0 {
description += " + \(self.constant)"
} else if self.constant < 0.0 {
description += " - \(CGFloat.abs(self.constant))"
}
}
if self.priority != 1000.0 {
description += " ^\(self.priority)"
}
description += ">"
return description
}
internal var snp_makerFile: String? {
return self.snp_constraint?.makerFile
}
internal var snp_makerLine: UInt? {
return self.snp_constraint?.makerLine
}
}
private var labelKey = ""
private func descriptionForObject(object: AnyObject) -> String {
let pointerDescription = NSString(format: "%p", ObjectIdentifier(object).uintValue)
var desc = ""
desc += object.dynamicType.description()
if let object = object as? View {
desc += ":\(object.snp_label ?? pointerDescription)"
} else if let object = object as? LayoutConstraint {
desc += ":\(object.snp_label ?? pointerDescription)"
} else {
desc += ":\(pointerDescription)"
}
if let object = object as? LayoutConstraint, let file = object.snp_makerFile, let line = object.snp_makerLine {
desc += "@\(file)#\(line)"
}
desc += ""
return desc
}
private extension NSLayoutRelation {
private var snp_description: String {
switch self {
case .Equal: return "=="
case .GreaterThanOrEqual: return ">="
case .LessThanOrEqual: return "<="
}
}
}
private extension NSLayoutAttribute {
private var snp_description: String {
#if os(iOS) || os(tvOS)
switch self {
case .NotAnAttribute: return "notAnAttribute"
case .Top: return "top"
case .Left: return "left"
case .Bottom: return "bottom"
case .Right: return "right"
case .Leading: return "leading"
case .Trailing: return "trailing"
case .Width: return "width"
case .Height: return "height"
case .CenterX: return "centerX"
case .CenterY: return "centerY"
case .Baseline: return "baseline"
case .FirstBaseline: return "firstBaseline"
case .TopMargin: return "topMargin"
case .LeftMargin: return "leftMargin"
case .BottomMargin: return "bottomMargin"
case .RightMargin: return "rightMargin"
case .LeadingMargin: return "leadingMargin"
case .TrailingMargin: return "trailingMargin"
case .CenterXWithinMargins: return "centerXWithinMargins"
case .CenterYWithinMargins: return "centerYWithinMargins"
}
#else
switch self {
case .NotAnAttribute: return "notAnAttribute"
case .Top: return "top"
case .Left: return "left"
case .Bottom: return "bottom"
case .Right: return "right"
case .Leading: return "leading"
case .Trailing: return "trailing"
case .Width: return "width"
case .Height: return "height"
case .CenterX: return "centerX"
case .CenterY: return "centerY"
case .Baseline: return "baseline"
default: return "default"
}
#endif
}
}
| 855156dfce02b8e1531af1efc076413a | 33.071429 | 119 | 0.573226 | false | false | false | false |
vojto/NiceKit | refs/heads/master | NiceKit/NKLabel.Mac.swift | mit | 1 | //
// NKLabel.Mac.swift
// FocusList
//
// Created by Vojtech Rinik on 12/02/16.
// Copyright © 2016 Vojtech Rinik. All rights reserved.
//
import Foundation
open class NKLabel: NKTextField {
open var userInteractionEnabled = true
public override init(frame frameRect: NSRect) {
super.init(frame: frameRect)
self.drawsBackground = false
self.isEditable = false
self.isSelectable = false
self.isBezeled = false
self.lineBreakMode = .byWordWrapping
self.setContentCompressionResistancePriority(NSLayoutConstraint.Priority(rawValue: 250), for: .horizontal)
}
required public init?(coder: NSCoder) {
super.init(coder: coder)
}
public convenience init(text: String) {
self.init(frame: CGRect.zero)
self.text = text
}
}
| e253ee7d967ea8d938af7882a97fdaf6 | 23.5 | 114 | 0.663866 | false | false | false | false |
gaoleegin/SwiftLanguage | refs/heads/master | GuidedTour-2.playground/Pages/Generics.xcplaygroundpage/Contents.swift | apache-2.0 | 1 | //: ## Generics
//:
//: Write a name inside angle brackets to make a generic function or type.
//:
func repeatItem<Item>(item: Item, numberOfTimes: Int) -> [Item] {
var result = [Item]()
for _ in 0..<numberOfTimes {
result.append(item)
}
return result
}
repeatItem("knock", numberOfTimes:4)
///范型
func repateItem1<Item>(item:Item,numbersOfItems:Int) ->[Item] {
var result = [Item]()
for _ in 0..<numbersOfItems{
result.append(item)
}
return result
}
//: You can make generic forms of functions and methods, as well as classes, enumerations, and structures.
//:
// Reimplement the Swift standard library's optional type
enum OptionalValue<Wrapped> {
case None
case Some(Wrapped)
}
var possibleInteger: OptionalValue<Int> = .None
possibleInteger = .Some(100)
//: Use `where` after the type name to specify a list of requirements—for example, to require the type to implement a protocol, to require two types to be the same, or to require a class to have a particular superclass.
//:
func anyCommonElements <T: SequenceType, U: SequenceType where T.Generator.Element: Equatable, T.Generator.Element == U.Generator.Element> (lhs: T, _ rhs: U) -> Bool {
for lhsItem in lhs {
for rhsItem in rhs {
if lhsItem == rhsItem {
return true
}
}
}
return false
}
anyCommonElements([1, 2, 3], [3])
//: > **Experiment**:
//: > Modify the `anyCommonElements(_:_:)` function to make a function that returns an array of the elements that any two sequences have in common.
//:
//: Writing `<T: Equatable>` is the same as writing `<T where T: Equatable>`.
//:
//: [Previous](@previous)
| 475507bcdd6e3c50068842a28a2e9974 | 29.890909 | 219 | 0.658034 | false | false | false | false |
aschwaighofer/swift | refs/heads/master | test/Frontend/dependencies-fine.swift | apache-2.0 | 2 | // REQUIRES: shell
// Also uses awk:
// XFAIL OS=windows
// RUN: %empty-directory(%t)
// RUN: %target-swift-frontend -emit-dependencies-path - -resolve-imports "%S/../Inputs/empty file.swift" | %FileCheck -check-prefix=CHECK-BASIC %s
// RUN: %target-swift-frontend -emit-reference-dependencies-path - -typecheck -primary-file "%S/../Inputs/empty file.swift" > %t.swiftdeps
// RUN: %S/../Inputs/process_fine_grained_swiftdeps.sh <%t.swiftdeps >%t-processed.swiftdeps
// RUN: %FileCheck -check-prefix=CHECK-BASIC-YAML %s <%t-processed.swiftdeps
// RUN: %target-swift-frontend -emit-dependencies-path %t.d -emit-reference-dependencies-path %t.swiftdeps -typecheck -primary-file "%S/../Inputs/empty file.swift"
// RUN: %FileCheck -check-prefix=CHECK-BASIC %s < %t.d
// RUN: %S/../Inputs/process_fine_grained_swiftdeps.sh <%t.swiftdeps >%t-processed.swiftdeps
// RUN: %FileCheck -check-prefix=CHECK-BASIC-YAML %s < %t-processed.swiftdeps
// CHECK-BASIC-LABEL: - :
// CHECK-BASIC: Inputs/empty\ file.swift
// CHECK-BASIC: Swift.swiftmodule
// CHECK-BASIC-NOT: {{ }}:{{ }}
// CHECK-BASIC-YAML-NOT: externalDepend {{.*}}empty
// CHECK-BASIC-YAML: externalDepend {{.*}} '{{.*}}Swift.swiftmodule{{(/.+[.]swiftmodule)?}}'
// RUN: %target-swift-frontend -emit-dependencies-path %t.d -emit-reference-dependencies-path %t.swiftdeps -typecheck "%S/../Inputs/empty file.swift" 2>&1 | %FileCheck -check-prefix=NO-PRIMARY-FILE %s
// NO-PRIMARY-FILE: warning: ignoring -emit-reference-dependencies (requires -primary-file)
// RUN: %target-swift-frontend -emit-dependencies-path - -emit-module "%S/../Inputs/empty file.swift" -o "%t/empty file.swiftmodule" -emit-module-doc-path "%t/empty file.swiftdoc" -emit-objc-header-path "%t/empty file.h" -emit-module-interface-path "%t/empty file.swiftinterface" | %FileCheck -check-prefix=CHECK-MULTIPLE-OUTPUTS %s
// CHECK-MULTIPLE-OUTPUTS-LABEL: empty\ file.swiftmodule :
// CHECK-MULTIPLE-OUTPUTS: Inputs/empty\ file.swift
// CHECK-MULTIPLE-OUTPUTS: Swift.swiftmodule
// CHECK-MULTIPLE-OUTPUTS-LABEL: empty\ file.swiftdoc :
// CHECK-MULTIPLE-OUTPUTS: Inputs/empty\ file.swift
// CHECK-MULTIPLE-OUTPUTS: Swift.swiftmodule
// CHECK-MULTIPLE-OUTPUTS-LABEL: empty\ file.swiftinterface :
// CHECK-MULTIPLE-OUTPUTS: Inputs/empty\ file.swift
// CHECK-MULTIPLE-OUTPUTS: Swift.swiftmodule
// CHECK-MULTIPLE-OUTPUTS-LABEL: empty\ file.h :
// CHECK-MULTIPLE-OUTPUTS: Inputs/empty\ file.swift
// CHECK-MULTIPLE-OUTPUTS: Swift.swiftmodule
// CHECK-MULTIPLE-OUTPUTS-NOT: {{ }}:{{ }}
// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -enable-objc-interop -disable-objc-attr-requires-foundation-module -import-objc-header %S/Inputs/dependencies/extra-header.h -emit-dependencies-path - -resolve-imports %s | %FileCheck -check-prefix=CHECK-IMPORT %s
// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -enable-objc-interop -disable-objc-attr-requires-foundation-module -import-objc-header %S/Inputs/dependencies/extra-header.h -track-system-dependencies -emit-dependencies-path - -resolve-imports %s | %FileCheck -check-prefix=CHECK-IMPORT-TRACK-SYSTEM %s
// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -enable-objc-interop -disable-objc-attr-requires-foundation-module -import-objc-header %S/Inputs/dependencies/extra-header.h -emit-reference-dependencies-path %t.swiftdeps -typecheck -primary-file %s
// RUN: %S/../Inputs/process_fine_grained_swiftdeps.sh <%t.swiftdeps >%t-processed.swiftdeps
// RUN: %FileCheck -check-prefix=CHECK-IMPORT-YAML %s <%t-processed.swiftdeps
// CHECK-IMPORT-LABEL: - :
// CHECK-IMPORT: dependencies-fine.swift
// CHECK-IMPORT-DAG: Swift.swiftmodule
// CHECK-IMPORT-DAG: Inputs/dependencies/$$$$$$$$$$.h
// CHECK-IMPORT-DAG: Inputs/dependencies{{/|\\}}UserClangModule.h
// CHECK-IMPORT-DAG: Inputs/dependencies/extra-header.h
// CHECK-IMPORT-DAG: Inputs/dependencies{{/|\\}}module.modulemap
// CHECK-IMPORT-DAG: ObjectiveC.swift
// CHECK-IMPORT-DAG: Foundation.swift
// CHECK-IMPORT-DAG: CoreGraphics.swift
// CHECK-IMPORT-NOT: {{[^\\]}}:
// CHECK-IMPORT-TRACK-SYSTEM-LABEL: - :
// CHECK-IMPORT-TRACK-SYSTEM: dependencies-fine.swift
// CHECK-IMPORT-TRACK-SYSTEM-DAG: Swift.swiftmodule
// CHECK-IMPORT-TRACK-SYSTEM-DAG: SwiftOnoneSupport.swiftmodule
// CHECK-IMPORT-TRACK-SYSTEM-DAG: CoreFoundation.swift
// CHECK-IMPORT-TRACK-SYSTEM-DAG: CoreGraphics.swift
// CHECK-IMPORT-TRACK-SYSTEM-DAG: Foundation.swift
// CHECK-IMPORT-TRACK-SYSTEM-DAG: ObjectiveC.swift
// CHECK-IMPORT-TRACK-SYSTEM-DAG: Inputs/dependencies/$$$$$$$$$$.h
// CHECK-IMPORT-TRACK-SYSTEM-DAG: Inputs/dependencies{{/|\\}}UserClangModule.h
// CHECK-IMPORT-TRACK-SYSTEM-DAG: Inputs/dependencies/extra-header.h
// CHECK-IMPORT-TRACK-SYSTEM-DAG: Inputs/dependencies{{/|\\}}module.modulemap
// CHECK-IMPORT-TRACK-SYSTEM-DAG: swift{{/|\\}}shims{{/|\\}}module.modulemap
// CHECK-IMPORT-TRACK-SYSTEM-DAG: usr{{/|\\}}include{{/|\\}}CoreFoundation.h
// CHECK-IMPORT-TRACK-SYSTEM-DAG: usr{{/|\\}}include{{/|\\}}CoreGraphics.apinotes
// CHECK-IMPORT-TRACK-SYSTEM-DAG: usr{{/|\\}}include{{/|\\}}CoreGraphics.h
// CHECK-IMPORT-TRACK-SYSTEM-DAG: usr{{/|\\}}include{{/|\\}}Foundation.h
// CHECK-IMPORT-TRACK-SYSTEM-DAG: usr{{/|\\}}include{{/|\\}}objc{{/|\\}}NSObject.h
// CHECK-IMPORT-TRACK-SYSTEM-DAG: usr{{/|\\}}include{{/|\\}}objc{{/|\\}}ObjectiveC.apinotes
// CHECK-IMPORT-TRACK-SYSTEM-DAG: usr{{/|\\}}include{{/|\\}}objc{{/|\\}}module.map
// CHECK-IMPORT-TRACK-SYSTEM-DAG: usr{{/|\\}}include{{/|\\}}objc{{/|\\}}objc.h
// CHECK-IMPORT-TRACK-SYSTEM-NOT: {{[^\\]}}:
// CHECK-IMPORT-YAML-NOT: externalDepend {{.*}}dependencies-fine.swift
// CHECK-IMPORT-YAML-DAG: externalDepend {{.*}} '{{.*}}{{/|\\}}Swift.swiftmodule{{(/.+[.]swiftmodule)?}}'
// CHECK-IMPORT-YAML-DAG: externalDepend {{.*}} '{{.*}}Inputs/dependencies/$$$$$.h'
// CHECK-IMPORT-YAML-DAG: externalDepend {{.*}} '{{.*}}Inputs/dependencies{{/|\\\\}}UserClangModule.h'
// CHECK-IMPORT-YAML-DAG: externalDepend {{.*}} '{{.*}}Inputs/dependencies/extra-header.h'
// CHECK-IMPORT-YAML-DAG: externalDepend {{.*}} '{{.*}}Inputs/dependencies{{/|\\\\}}module.modulemap'
// CHECK-IMPORT-YAML-DAG: externalDepend {{.*}} '{{.*}}{{/|\\\\}}ObjectiveC.swift'
// CHECK-IMPORT-YAML-DAG: externalDepend {{.*}} '{{.*}}{{/|\\\\}}Foundation.swift'
// CHECK-IMPORT-YAML-DAG: externalDepend {{.*}} '{{.*}}{{/|\\\\}}CoreGraphics.swift'
// CHECK-ERROR-YAML: # Dependencies are unknown because a compilation error occurred.
// RUN: not %target-swift-frontend(mock-sdk: %clang-importer-sdk) -DERROR -import-objc-header %S/Inputs/dependencies/extra-header.h -emit-dependencies-path - -typecheck %s | %FileCheck -check-prefix=CHECK-IMPORT %s
// RUN: not %target-swift-frontend(mock-sdk: %clang-importer-sdk) -DERROR -import-objc-header %S/Inputs/dependencies/extra-header.h -typecheck -primary-file %s - %FileCheck -check-prefix=CHECK-ERROR-YAML %s
import Foundation
import UserClangModule
class Test: NSObject {}
_ = A()
_ = USER_VERSION
_ = EXTRA_VERSION
_ = MONEY
#if ERROR
_ = someRandomUndefinedName
#endif
| 9e728b1a9ef2938e098974eb2b07ab4c | 58.803419 | 332 | 0.71302 | false | false | false | false |
davideast/NewPod | refs/heads/master | Example/Tests/Tests.swift | mit | 1 | // https://github.com/Quick/Quick
import Quick
import Nimble
import NewPod
class TableOfContentsSpec: QuickSpec {
override func spec() {
describe("these will fail") {
it("can do maths") {
expect(1) == 2
}
it("can read") {
expect("number") == "string"
}
it("will eventually fail") {
expect("time").toEventually( equal("done") )
}
context("these will pass") {
it("can do maths") {
expect(23) == 23
}
it("can read") {
expect("🐮") == "🐮"
}
it("will eventually pass") {
var time = "passing"
dispatch_async(dispatch_get_main_queue()) {
time = "done"
}
waitUntil { done in
NSThread.sleepForTimeInterval(0.5)
expect(time) == "done"
done()
}
}
}
}
}
}
| 9942562ba3f2afa6eb09b698ed3ddf09 | 22.34 | 63 | 0.361611 | false | false | false | false |
xBrux/Pensieve | refs/heads/master | Source/Core/Blob.swift | mit | 1 | //
// SQLite.swift
// https://github.com/stephencelis/SQLite.swift
// Copyright © 2014-2015 Stephen Celis.
//
// 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*/ struct Blob {
/*public*/ let bytes: [UInt8]
/*public*/ init(bytes: [UInt8]) {
self.bytes = bytes
}
/*public*/ init(bytes: UnsafePointer<Void>, length: Int) {
self.init(bytes: [UInt8](UnsafeBufferPointer(
start: UnsafePointer(bytes), count: length
)))
}
/*public*/ func toHex() -> String {
return bytes.map {
($0 < 16 ? "0" : "") + String($0, radix: 16, uppercase: false)
}.joinWithSeparator("")
}
}
extension Blob : CustomStringConvertible {
/*public*/ var description: String {
return "x'\(toHex())'"
}
}
extension Blob : Equatable {
}
/*public*/ func ==(lhs: Blob, rhs: Blob) -> Bool {
return lhs.bytes == rhs.bytes
}
| 0a2b732a8aa9bf2f38caf350ca5ab2d4 | 30.803279 | 80 | 0.67732 | false | false | false | false |
Drusy/auvergne-webcams-ios | refs/heads/master | Carthage/Checkouts/realm-cocoa/RealmSwift/Tests/ObjectSchemaInitializationTests.swift | apache-2.0 | 2 | ////////////////////////////////////////////////////////////////////////////
//
// Copyright 2015 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 XCTest
import RealmSwift
import Realm.Dynamic
import Foundation
class ObjectSchemaInitializationTests: TestCase {
func testAllValidTypes() {
let object = SwiftObject()
let objectSchema = object.objectSchema
let noSuchCol = objectSchema["noSuchCol"]
XCTAssertNil(noSuchCol)
let boolCol = objectSchema["boolCol"]
XCTAssertNotNil(boolCol)
XCTAssertEqual(boolCol!.name, "boolCol")
XCTAssertEqual(boolCol!.type, PropertyType.bool)
XCTAssertFalse(boolCol!.isIndexed)
XCTAssertFalse(boolCol!.isOptional)
XCTAssertNil(boolCol!.objectClassName)
let intCol = objectSchema["intCol"]
XCTAssertNotNil(intCol)
XCTAssertEqual(intCol!.name, "intCol")
XCTAssertEqual(intCol!.type, PropertyType.int)
XCTAssertFalse(intCol!.isIndexed)
XCTAssertFalse(intCol!.isOptional)
XCTAssertNil(intCol!.objectClassName)
let floatCol = objectSchema["floatCol"]
XCTAssertNotNil(floatCol)
XCTAssertEqual(floatCol!.name, "floatCol")
XCTAssertEqual(floatCol!.type, PropertyType.float)
XCTAssertFalse(floatCol!.isIndexed)
XCTAssertFalse(floatCol!.isOptional)
XCTAssertNil(floatCol!.objectClassName)
let doubleCol = objectSchema["doubleCol"]
XCTAssertNotNil(doubleCol)
XCTAssertEqual(doubleCol!.name, "doubleCol")
XCTAssertEqual(doubleCol!.type, PropertyType.double)
XCTAssertFalse(doubleCol!.isIndexed)
XCTAssertFalse(doubleCol!.isOptional)
XCTAssertNil(doubleCol!.objectClassName)
let stringCol = objectSchema["stringCol"]
XCTAssertNotNil(stringCol)
XCTAssertEqual(stringCol!.name, "stringCol")
XCTAssertEqual(stringCol!.type, PropertyType.string)
XCTAssertFalse(stringCol!.isIndexed)
XCTAssertFalse(stringCol!.isOptional)
XCTAssertNil(stringCol!.objectClassName)
let binaryCol = objectSchema["binaryCol"]
XCTAssertNotNil(binaryCol)
XCTAssertEqual(binaryCol!.name, "binaryCol")
XCTAssertEqual(binaryCol!.type, PropertyType.data)
XCTAssertFalse(binaryCol!.isIndexed)
XCTAssertFalse(binaryCol!.isOptional)
XCTAssertNil(binaryCol!.objectClassName)
let dateCol = objectSchema["dateCol"]
XCTAssertNotNil(dateCol)
XCTAssertEqual(dateCol!.name, "dateCol")
XCTAssertEqual(dateCol!.type, PropertyType.date)
XCTAssertFalse(dateCol!.isIndexed)
XCTAssertFalse(dateCol!.isOptional)
XCTAssertNil(dateCol!.objectClassName)
let objectCol = objectSchema["objectCol"]
XCTAssertNotNil(objectCol)
XCTAssertEqual(objectCol!.name, "objectCol")
XCTAssertEqual(objectCol!.type, PropertyType.object)
XCTAssertFalse(objectCol!.isIndexed)
XCTAssertTrue(objectCol!.isOptional)
XCTAssertEqual(objectCol!.objectClassName!, "SwiftBoolObject")
let arrayCol = objectSchema["arrayCol"]
XCTAssertNotNil(arrayCol)
XCTAssertEqual(arrayCol!.name, "arrayCol")
XCTAssertEqual(arrayCol!.type, PropertyType.object)
XCTAssertTrue(arrayCol!.isArray)
XCTAssertFalse(arrayCol!.isIndexed)
XCTAssertFalse(arrayCol!.isOptional)
XCTAssertEqual(objectCol!.objectClassName!, "SwiftBoolObject")
let dynamicArrayCol = SwiftCompanyObject().objectSchema["employees"]
XCTAssertNotNil(dynamicArrayCol)
XCTAssertEqual(dynamicArrayCol!.name, "employees")
XCTAssertEqual(dynamicArrayCol!.type, PropertyType.object)
XCTAssertTrue(dynamicArrayCol!.isArray)
XCTAssertFalse(dynamicArrayCol!.isIndexed)
XCTAssertFalse(arrayCol!.isOptional)
XCTAssertEqual(dynamicArrayCol!.objectClassName!, "SwiftEmployeeObject")
}
func testInvalidObjects() {
// Should be able to get a schema for a non-RLMObjectBase subclass
let schema = RLMObjectSchema(forObjectClass: SwiftFakeObjectSubclass.self)
XCTAssertEqual(schema.properties.count, 1)
assertThrows(RLMObjectSchema(forObjectClass: SwiftObjectWithAnyObject.self),
"Should throw when not ignoring a property of a type we can't persist")
assertThrows(RLMObjectSchema(forObjectClass: SwiftObjectWithStringArray.self),
"Should throw when not ignoring a property of a type we can't persist")
assertThrows(RLMObjectSchema(forObjectClass: SwiftObjectWithOptionalStringArray.self),
"Should throw when not ignoring a property of a type we can't persist")
assertThrows(RLMObjectSchema(forObjectClass: SwiftObjectWithBadPropertyName.self),
"Should throw when not ignoring a property with a name we don't support")
assertThrows(RLMObjectSchema(forObjectClass: SwiftObjectWithManagedLazyProperty.self),
"Should throw when not ignoring a lazy property")
assertThrows(RLMObjectSchema(forObjectClass: SwiftObjectWithDynamicManagedLazyProperty.self),
"Should throw when not ignoring a lazy property")
// Shouldn't throw when not ignoring a property of a type we can't persist if it's not dynamic
_ = RLMObjectSchema(forObjectClass: SwiftObjectWithEnum.self)
// Shouldn't throw when not ignoring a property of a type we can't persist if it's not dynamic
_ = RLMObjectSchema(forObjectClass: SwiftObjectWithStruct.self)
assertThrows(RLMObjectSchema(forObjectClass: SwiftObjectWithDatePrimaryKey.self),
"Should throw when setting a non int/string primary key")
assertThrows(RLMObjectSchema(forObjectClass: SwiftObjectWithNSURL.self),
"Should throw when not ignoring a property of a type we can't persist")
assertThrows(RLMObjectSchema(forObjectClass: SwiftObjectWithNonOptionalLinkProperty.self),
"Should throw when not marking a link property as optional")
assertThrows(RLMObjectSchema(forObjectClass: SwiftObjectWithNSNumber.self),
reason: "Can't persist NSNumber without default value: use a Swift-native number type " +
"or provide a default value.",
"Should throw when using not providing default value for NSNumber property on Swift model")
assertThrows(RLMObjectSchema(forObjectClass: SwiftObjectWithOptionalNSNumber.self),
reason: "Can't persist NSNumber without default value: use a Swift-native number type " +
"or provide a default value.",
"Should throw when using not providing default value for NSNumber property on Swift model")
}
func testPrimaryKey() {
XCTAssertNil(SwiftObject().objectSchema.primaryKeyProperty,
"Object should default to having no primary key property")
XCTAssertEqual(SwiftPrimaryStringObject().objectSchema.primaryKeyProperty!.name, "stringCol")
}
func testIgnoredProperties() {
let schema = SwiftIgnoredPropertiesObject().objectSchema
XCTAssertNil(schema["runtimeProperty"], "The object schema shouldn't contain ignored properties")
XCTAssertNil(schema["runtimeDefaultProperty"], "The object schema shouldn't contain ignored properties")
XCTAssertNil(schema["readOnlyProperty"], "The object schema shouldn't contain read-only properties")
}
func testIndexedProperties() {
XCTAssertTrue(SwiftIndexedPropertiesObject().objectSchema["stringCol"]!.isIndexed)
XCTAssertTrue(SwiftIndexedPropertiesObject().objectSchema["intCol"]!.isIndexed)
XCTAssertTrue(SwiftIndexedPropertiesObject().objectSchema["int8Col"]!.isIndexed)
XCTAssertTrue(SwiftIndexedPropertiesObject().objectSchema["int16Col"]!.isIndexed)
XCTAssertTrue(SwiftIndexedPropertiesObject().objectSchema["int32Col"]!.isIndexed)
XCTAssertTrue(SwiftIndexedPropertiesObject().objectSchema["int64Col"]!.isIndexed)
XCTAssertTrue(SwiftIndexedPropertiesObject().objectSchema["boolCol"]!.isIndexed)
XCTAssertTrue(SwiftIndexedPropertiesObject().objectSchema["dateCol"]!.isIndexed)
XCTAssertFalse(SwiftIndexedPropertiesObject().objectSchema["floatCol"]!.isIndexed)
XCTAssertFalse(SwiftIndexedPropertiesObject().objectSchema["doubleCol"]!.isIndexed)
XCTAssertFalse(SwiftIndexedPropertiesObject().objectSchema["dataCol"]!.isIndexed)
let unindexibleSchema = RLMObjectSchema(forObjectClass: SwiftObjectWithUnindexibleProperties.self)
for propName in SwiftObjectWithUnindexibleProperties.indexedProperties() {
XCTAssertFalse(unindexibleSchema[propName]!.indexed,
"Shouldn't mark unindexible property '\(propName)' as indexed")
}
}
func testOptionalProperties() {
let schema = RLMObjectSchema(forObjectClass: SwiftOptionalObject.self)
for prop in schema.properties {
XCTAssertTrue(prop.optional)
}
let types = Set(schema.properties.map { $0.type })
XCTAssertEqual(types, Set([.string, .string, .data, .date, .object, .int, .float, .double, .bool]))
}
func testImplicitlyUnwrappedOptionalsAreParsedAsOptionals() {
let schema = SwiftImplicitlyUnwrappedOptionalObject().objectSchema
XCTAssertTrue(schema["optObjectCol"]!.isOptional)
XCTAssertTrue(schema["optNSStringCol"]!.isOptional)
XCTAssertTrue(schema["optStringCol"]!.isOptional)
XCTAssertTrue(schema["optBinaryCol"]!.isOptional)
XCTAssertTrue(schema["optDateCol"]!.isOptional)
}
func testNonRealmOptionalTypesDeclaredAsRealmOptional() {
assertThrows(RLMObjectSchema(forObjectClass: SwiftObjectWithNonRealmOptionalType.self))
}
func testNotExplicitlyIgnoredComputedProperties() {
let schema = SwiftComputedPropertyNotIgnoredObject().objectSchema
// The two computed properties should not appear on the schema.
XCTAssertEqual(schema.properties.count, 1)
XCTAssertNotNil(schema["_urlBacking"])
}
}
class SwiftFakeObject: NSObject {
@objc class func objectUtilClass(_ isSwift: Bool) -> AnyClass { return ObjectUtil.self }
@objc class func primaryKey() -> String? { return nil }
@objc class func ignoredProperties() -> [String] { return [] }
@objc class func indexedProperties() -> [String] { return [] }
@objc class func _realmObjectName() -> String? { return nil }
@objc class func _realmColumnNames() -> [String: String]? { return nil }
}
class SwiftObjectWithNSURL: SwiftFakeObject {
@objc dynamic var url = NSURL(string: "http://realm.io")!
}
class SwiftObjectWithAnyObject: SwiftFakeObject {
@objc dynamic var anyObject: AnyObject = NSObject()
}
class SwiftObjectWithStringArray: SwiftFakeObject {
@objc dynamic var stringArray = [String]()
}
class SwiftObjectWithOptionalStringArray: SwiftFakeObject {
@objc dynamic var stringArray: [String]?
}
enum SwiftEnum {
case case1
case case2
}
class SwiftObjectWithEnum: SwiftFakeObject {
var swiftEnum = SwiftEnum.case1
}
class SwiftObjectWithStruct: SwiftFakeObject {
var swiftStruct = SortDescriptor(keyPath: "prop")
}
class SwiftObjectWithDatePrimaryKey: SwiftFakeObject {
@objc dynamic var date = Date()
override class func primaryKey() -> String? {
return "date"
}
}
class SwiftObjectWithNSNumber: SwiftFakeObject {
@objc dynamic var number = NSNumber()
}
class SwiftObjectWithOptionalNSNumber: SwiftFakeObject {
@objc dynamic var number: NSNumber? = NSNumber()
}
class SwiftFakeObjectSubclass: SwiftFakeObject {
@objc dynamic var dateCol = Date()
}
class SwiftObjectWithUnindexibleProperties: SwiftFakeObject {
@objc dynamic var boolCol = false
@objc dynamic var intCol = 123
@objc dynamic var floatCol = 1.23 as Float
@objc dynamic var doubleCol = 12.3
@objc dynamic var binaryCol = "a".data(using: String.Encoding.utf8)!
@objc dynamic var dateCol = Date(timeIntervalSince1970: 1)
@objc dynamic var objectCol: SwiftBoolObject? = SwiftBoolObject()
let arrayCol = List<SwiftBoolObject>()
dynamic override class func indexedProperties() -> [String] {
return ["boolCol", "intCol", "floatCol", "doubleCol", "binaryCol", "dateCol", "objectCol", "arrayCol"]
}
}
// swiftlint:disable:next type_name
class SwiftObjectWithNonNullableOptionalProperties: SwiftFakeObject {
@objc dynamic var optDateCol: Date?
}
class SwiftObjectWithNonOptionalLinkProperty: SwiftFakeObject {
@objc dynamic var objectCol = SwiftBoolObject()
}
extension Set: RealmOptionalType { }
class SwiftObjectWithNonRealmOptionalType: SwiftFakeObject {
let set = RealmOptional<Set<Int>>()
}
class SwiftObjectWithBadPropertyName: SwiftFakeObject {
@objc dynamic var newValue = false
}
class SwiftObjectWithManagedLazyProperty: SwiftFakeObject {
lazy var foobar: String = "foo"
}
// swiftlint:disable:next type_name
class SwiftObjectWithDynamicManagedLazyProperty: SwiftFakeObject {
@objc dynamic lazy var foobar: String = "foo"
}
| e98dbdb3dda64349d0ea670433449cad | 42.478125 | 112 | 0.708546 | false | false | false | false |
kylebshr/DOFavoriteButton | refs/heads/master | DOFavoriteButton/DOFavoriteButton.swift | mit | 1 | //
// DOFavoriteButton.swift
// DOFavoriteButton
//
// Created by Daiki Okumura on 2015/07/09.
// Copyright (c) 2015 Daiki Okumura. All rights reserved.
//
// This software is released under the MIT License.
// http://opensource.org/licenses/mit-license.php
//
import UIKit
@IBDesignable
open class DOFavoriteButton: UIButton {
fileprivate var imageShape: CAShapeLayer!
@IBInspectable open var image: UIImage! {
didSet {
createLayers(image: image)
}
}
@IBInspectable open var imageColorOn: UIColor! = UIColor(red: 255/255, green: 172/255, blue: 51/255, alpha: 1.0) {
didSet {
if (isSelected) {
imageShape.fillColor = imageColorOn.cgColor
}
}
}
@IBInspectable open var imageColorOff: UIColor! = UIColor(red: 136/255, green: 153/255, blue: 166/255, alpha: 1.0) {
didSet {
if (!isSelected) {
imageShape.fillColor = imageColorOff.cgColor
}
}
}
fileprivate var circleShape: CAShapeLayer!
fileprivate var circleMask: CAShapeLayer!
@IBInspectable open var circleColor: UIColor! = UIColor(red: 255/255, green: 172/255, blue: 51/255, alpha: 1.0) {
didSet {
circleShape.fillColor = circleColor.cgColor
}
}
fileprivate var lines: [CAShapeLayer]!
@IBInspectable open var lineColor: UIColor! = UIColor(red: 250/255, green: 120/255, blue: 68/255, alpha: 1.0) {
didSet {
for line in lines {
line.strokeColor = lineColor.cgColor
}
}
}
fileprivate let circleTransform = CAKeyframeAnimation(keyPath: "transform")
fileprivate let circleMaskTransform = CAKeyframeAnimation(keyPath: "transform")
fileprivate let lineStrokeStart = CAKeyframeAnimation(keyPath: "strokeStart")
fileprivate let lineStrokeEnd = CAKeyframeAnimation(keyPath: "strokeEnd")
fileprivate let lineOpacity = CAKeyframeAnimation(keyPath: "opacity")
fileprivate let imageTransform = CAKeyframeAnimation(keyPath: "transform")
@IBInspectable open var duration: Double = 1.0 {
didSet {
circleTransform.duration = 0.333 * duration // 0.0333 * 10
circleMaskTransform.duration = 0.333 * duration // 0.0333 * 10
lineStrokeStart.duration = 0.6 * duration //0.0333 * 18
lineStrokeEnd.duration = 0.6 * duration //0.0333 * 18
lineOpacity.duration = 1.0 * duration //0.0333 * 30
imageTransform.duration = 1.0 * duration //0.0333 * 30
}
}
override open var isSelected : Bool {
didSet {
if (isSelected != oldValue) {
if isSelected {
imageShape.fillColor = imageColorOn.cgColor
} else {
deselect()
}
}
}
}
public convenience init() {
self.init(frame: CGRect.zero)
}
public override convenience init(frame: CGRect) {
self.init(frame: frame, image: UIImage())
}
public init(frame: CGRect, image: UIImage!) {
super.init(frame: frame)
self.image = image
createLayers(image: image)
addTargets()
}
public required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)!
createLayers(image: UIImage())
addTargets()
}
fileprivate func createLayers(image: UIImage!) {
self.layer.sublayers = nil
let imageFrame = CGRect(x: frame.size.width / 2 - frame.size.width / 4, y: frame.size.height / 2 - frame.size.height / 4, width: frame.size.width / 2, height: frame.size.height / 2)
let imgCenterPoint = CGPoint(x: imageFrame.midX, y: imageFrame.midY)
let lineFrame = CGRect(x: imageFrame.origin.x - imageFrame.width / 4, y: imageFrame.origin.y - imageFrame.height / 4 , width: imageFrame.width * 1.5, height: imageFrame.height * 1.5)
//===============
// circle layer
//===============
circleShape = CAShapeLayer()
circleShape.bounds = imageFrame
circleShape.position = imgCenterPoint
circleShape.path = UIBezierPath(ovalIn: imageFrame).cgPath
circleShape.fillColor = circleColor.cgColor
circleShape.transform = CATransform3DMakeScale(0.0, 0.0, 1.0)
self.layer.addSublayer(circleShape)
circleMask = CAShapeLayer()
circleMask.bounds = imageFrame
circleMask.position = imgCenterPoint
circleMask.fillRule = kCAFillRuleEvenOdd
circleShape.mask = circleMask
let maskPath = UIBezierPath(rect: imageFrame)
maskPath.addArc(withCenter: imgCenterPoint, radius: 0.1, startAngle: 0.0, endAngle: .pi * 2, clockwise: true)
circleMask.path = maskPath.cgPath
//===============
// line layer
//===============
lines = []
for i in 0 ..< 5 {
let line = CAShapeLayer()
line.bounds = lineFrame
line.position = imgCenterPoint
line.masksToBounds = true
line.actions = ["strokeStart": NSNull(), "strokeEnd": NSNull()]
line.strokeColor = lineColor.cgColor
line.lineWidth = 1.25
line.miterLimit = 1.25
line.path = {
let path = CGMutablePath()
path.move(to: CGPoint(x: lineFrame.midX, y: lineFrame.midY))
path.addLine(to: CGPoint(x: lineFrame.origin.x + lineFrame.width / 2, y: lineFrame.origin.y))
return path
}()
line.lineCap = kCALineCapRound
line.lineJoin = kCALineJoinRound
line.strokeStart = 0.0
line.strokeEnd = 0.0
line.opacity = 0.0
line.transform = CATransform3DMakeRotation(.pi / 5 * (CGFloat(i) * 2 + 1), 0.0, 0.0, 1.0)
self.layer.addSublayer(line)
lines.append(line)
}
//===============
// image layer
//===============
imageShape = CAShapeLayer()
imageShape.bounds = imageFrame
imageShape.position = imgCenterPoint
imageShape.path = UIBezierPath(rect: imageFrame).cgPath
imageShape.fillColor = imageColorOff.cgColor
imageShape.actions = ["fillColor": NSNull()]
self.layer.addSublayer(imageShape)
imageShape.mask = CALayer()
imageShape.mask!.contents = image.cgImage
imageShape.mask!.bounds = imageFrame
imageShape.mask!.position = imgCenterPoint
//==============================
// circle transform animation
//==============================
circleTransform.duration = 0.333 // 0.0333 * 10
circleTransform.values = [
NSValue(caTransform3D: CATransform3DMakeScale(0.0, 0.0, 1.0)), // 0/10
NSValue(caTransform3D: CATransform3DMakeScale(0.5, 0.5, 1.0)), // 1/10
NSValue(caTransform3D: CATransform3DMakeScale(1.0, 1.0, 1.0)), // 2/10
NSValue(caTransform3D: CATransform3DMakeScale(1.2, 1.2, 1.0)), // 3/10
NSValue(caTransform3D: CATransform3DMakeScale(1.3, 1.3, 1.0)), // 4/10
NSValue(caTransform3D: CATransform3DMakeScale(1.37, 1.37, 1.0)), // 5/10
NSValue(caTransform3D: CATransform3DMakeScale(1.4, 1.4, 1.0)), // 6/10
NSValue(caTransform3D: CATransform3DMakeScale(1.4, 1.4, 1.0)) // 10/10
]
circleTransform.keyTimes = [
0.0, // 0/10
0.1, // 1/10
0.2, // 2/10
0.3, // 3/10
0.4, // 4/10
0.5, // 5/10
0.6, // 6/10
1.0 // 10/10
]
circleMaskTransform.duration = 0.333 // 0.0333 * 10
circleMaskTransform.values = [
NSValue(caTransform3D: CATransform3DIdentity), // 0/10
NSValue(caTransform3D: CATransform3DIdentity), // 2/10
NSValue(caTransform3D: CATransform3DMakeScale(imageFrame.width * 1.25, imageFrame.height * 1.25, 1.0)), // 3/10
NSValue(caTransform3D: CATransform3DMakeScale(imageFrame.width * 2.688, imageFrame.height * 2.688, 1.0)), // 4/10
NSValue(caTransform3D: CATransform3DMakeScale(imageFrame.width * 3.923, imageFrame.height * 3.923, 1.0)), // 5/10
NSValue(caTransform3D: CATransform3DMakeScale(imageFrame.width * 4.375, imageFrame.height * 4.375, 1.0)), // 6/10
NSValue(caTransform3D: CATransform3DMakeScale(imageFrame.width * 4.731, imageFrame.height * 4.731, 1.0)), // 7/10
NSValue(caTransform3D: CATransform3DMakeScale(imageFrame.width * 5.0, imageFrame.height * 5.0, 1.0)), // 9/10
NSValue(caTransform3D: CATransform3DMakeScale(imageFrame.width * 5.0, imageFrame.height * 5.0, 1.0)) // 10/10
]
circleMaskTransform.keyTimes = [
0.0, // 0/10
0.2, // 2/10
0.3, // 3/10
0.4, // 4/10
0.5, // 5/10
0.6, // 6/10
0.7, // 7/10
0.9, // 9/10
1.0 // 10/10
]
//==============================
// line stroke animation
//==============================
lineStrokeStart.duration = 0.6 //0.0333 * 18
lineStrokeStart.values = [
0.0, // 0/18
0.0, // 1/18
0.18, // 2/18
0.2, // 3/18
0.26, // 4/18
0.32, // 5/18
0.4, // 6/18
0.6, // 7/18
0.71, // 8/18
0.89, // 17/18
0.92 // 18/18
]
lineStrokeStart.keyTimes = [
0.0, // 0/18
0.056, // 1/18
0.111, // 2/18
0.167, // 3/18
0.222, // 4/18
0.278, // 5/18
0.333, // 6/18
0.389, // 7/18
0.444, // 8/18
0.944, // 17/18
1.0, // 18/18
]
lineStrokeEnd.duration = 0.6 //0.0333 * 18
lineStrokeEnd.values = [
0.0, // 0/18
0.0, // 1/18
0.32, // 2/18
0.48, // 3/18
0.64, // 4/18
0.68, // 5/18
0.92, // 17/18
0.92 // 18/18
]
lineStrokeEnd.keyTimes = [
0.0, // 0/18
0.056, // 1/18
0.111, // 2/18
0.167, // 3/18
0.222, // 4/18
0.278, // 5/18
0.944, // 17/18
1.0, // 18/18
]
lineOpacity.duration = 1.0 //0.0333 * 30
lineOpacity.values = [
1.0, // 0/30
1.0, // 12/30
0.0 // 17/30
]
lineOpacity.keyTimes = [
0.0, // 0/30
0.4, // 12/30
0.567 // 17/30
]
//==============================
// image transform animation
//==============================
imageTransform.duration = 1.0 //0.0333 * 30
imageTransform.values = [
NSValue(caTransform3D: CATransform3DMakeScale(0.0, 0.0, 1.0)), // 0/30
NSValue(caTransform3D: CATransform3DMakeScale(0.0, 0.0, 1.0)), // 3/30
NSValue(caTransform3D: CATransform3DMakeScale(1.2, 1.2, 1.0)), // 9/30
NSValue(caTransform3D: CATransform3DMakeScale(1.25, 1.25, 1.0)), // 10/30
NSValue(caTransform3D: CATransform3DMakeScale(1.2, 1.2, 1.0)), // 11/30
NSValue(caTransform3D: CATransform3DMakeScale(0.9, 0.9, 1.0)), // 14/30
NSValue(caTransform3D: CATransform3DMakeScale(0.875, 0.875, 1.0)), // 15/30
NSValue(caTransform3D: CATransform3DMakeScale(0.875, 0.875, 1.0)), // 16/30
NSValue(caTransform3D: CATransform3DMakeScale(0.9, 0.9, 1.0)), // 17/30
NSValue(caTransform3D: CATransform3DMakeScale(1.013, 1.013, 1.0)), // 20/30
NSValue(caTransform3D: CATransform3DMakeScale(1.025, 1.025, 1.0)), // 21/30
NSValue(caTransform3D: CATransform3DMakeScale(1.013, 1.013, 1.0)), // 22/30
NSValue(caTransform3D: CATransform3DMakeScale(0.96, 0.96, 1.0)), // 25/30
NSValue(caTransform3D: CATransform3DMakeScale(0.95, 0.95, 1.0)), // 26/30
NSValue(caTransform3D: CATransform3DMakeScale(0.96, 0.96, 1.0)), // 27/30
NSValue(caTransform3D: CATransform3DMakeScale(0.99, 0.99, 1.0)), // 29/30
NSValue(caTransform3D: CATransform3DIdentity) // 30/30
]
imageTransform.keyTimes = [
0.0, // 0/30
0.1, // 3/30
0.3, // 9/30
0.333, // 10/30
0.367, // 11/30
0.467, // 14/30
0.5, // 15/30
0.533, // 16/30
0.567, // 17/30
0.667, // 20/30
0.7, // 21/30
0.733, // 22/30
0.833, // 25/30
0.867, // 26/30
0.9, // 27/30
0.967, // 29/30
1.0 // 30/30
]
}
fileprivate func addTargets() {
//===============
// add target
//===============
self.addTarget(self, action: #selector(DOFavoriteButton.touchDown(_:)), for: UIControlEvents.touchDown)
self.addTarget(self, action: #selector(DOFavoriteButton.touchUpInside(_:)), for: UIControlEvents.touchUpInside)
self.addTarget(self, action: #selector(DOFavoriteButton.touchDragExit(_:)), for: UIControlEvents.touchDragExit)
self.addTarget(self, action: #selector(DOFavoriteButton.touchDragEnter(_:)), for: UIControlEvents.touchDragEnter)
self.addTarget(self, action: #selector(DOFavoriteButton.touchCancel(_:)), for: UIControlEvents.touchCancel)
}
func touchDown(_ sender: DOFavoriteButton) {
self.layer.opacity = 0.4
}
func touchUpInside(_ sender: DOFavoriteButton) {
self.layer.opacity = 1.0
}
func touchDragExit(_ sender: DOFavoriteButton) {
self.layer.opacity = 1.0
}
func touchDragEnter(_ sender: DOFavoriteButton) {
self.layer.opacity = 0.4
}
func touchCancel(_ sender: DOFavoriteButton) {
self.layer.opacity = 1.0
}
open func select() {
isSelected = true
imageShape.fillColor = imageColorOn.cgColor
CATransaction.begin()
circleShape.add(circleTransform, forKey: "transform")
circleMask.add(circleMaskTransform, forKey: "transform")
imageShape.add(imageTransform, forKey: "transform")
for i in 0 ..< 5 {
lines[i].add(lineStrokeStart, forKey: "strokeStart")
lines[i].add(lineStrokeEnd, forKey: "strokeEnd")
lines[i].add(lineOpacity, forKey: "opacity")
}
CATransaction.commit()
}
open func deselect() {
isSelected = false
imageShape.fillColor = imageColorOff.cgColor
// remove all animations
circleShape.removeAllAnimations()
circleMask.removeAllAnimations()
imageShape.removeAllAnimations()
lines[0].removeAllAnimations()
lines[1].removeAllAnimations()
lines[2].removeAllAnimations()
lines[3].removeAllAnimations()
lines[4].removeAllAnimations()
}
}
| 99f4348387392936ee14fa153a20dce3 | 38.397985 | 190 | 0.53168 | false | false | false | false |
trentbranson/Simple-Stop-Watch | refs/heads/master | Stop Watch/StopWatch.swift | mit | 1 | //
// StopWatch.swift
// Stop Watch
//
// Created by Trent Branson on 9/10/16.
// Copyright © 2016 Trent Branson. All rights reserved.
//
import Foundation
class StopWatch: NSObject {
var timerOn = false
private var startTime: TimeInterval? = nil
private var lapTimes = [TimeInterval]()
private var reset = true
func toggleTimer() {
if (reset) {
// get the current time
startTime = NSDate.timeIntervalSinceReferenceDate
reset = false
}
timerOn = !timerOn
}
func resetTimer() {
reset = true
timerOn = false
startTime = nil
lapTimes.removeAll()
}
func getTime() -> String {
if let start = startTime {
// get the current time
let currentTime = NSDate.timeIntervalSinceReferenceDate
let elapsedTime: TimeInterval = currentTime - start
// get the individual hours, mins, secs, etc. for the time delta
return timeIntervalToString(timeInterval: elapsedTime)
} else {
return Constants.defaultTime
}
}
func addLapTime() {
if let start = startTime {
let currentTime = NSDate.timeIntervalSinceReferenceDate
let elapsedTime: TimeInterval = currentTime - start
lapTimes.append(elapsedTime)
}
}
func getLapTime(index: Int) -> String {
return timeIntervalToString(timeInterval: lapTimes[index])
}
func getNumLaps() -> Int {
return lapTimes.count
}
private func timeIntervalToString(timeInterval: TimeInterval) -> String {
var timeLeft = timeInterval
let hours = Int(timeLeft / (Constants.secondsPerMinute * Constants.secondsPerMinute))
timeLeft -= TimeInterval(hours) * Constants.secondsPerMinute * Constants.minutesPerHour
let minutes = Int(timeLeft / (Constants.secondsPerMinute))
timeLeft -= TimeInterval(minutes) * Constants.secondsPerMinute
let seconds = Int(timeLeft)
timeLeft -= TimeInterval(seconds)
let hundrendthSeconds = Int(timeLeft * Constants.hundradthsPerHunred)
return String(format: "%d:%02d:%02d.%02d", hours, minutes, seconds, hundrendthSeconds)
}
}
| 8c8d47864d6da8a09540aaf5800aa572 | 29.8 | 95 | 0.619913 | false | false | false | false |
RCacheaux/BitbucketKit | refs/heads/master | Carthage/Checkouts/Swinject/Sources/PlistPropertyLoader.swift | apache-2.0 | 3 | //
// PlistPropertyLoader.swift
// Swinject
//
// Created by mike.owens on 12/6/15.
// Copyright © 2015 Swinject Contributors. All rights reserved.
//
import Foundation
/// The PlistPropertyLoader will load properties from plist resources
final public class PlistPropertyLoader {
/// the bundle where the resource exists (defualts to mainBundle)
private let bundle: NSBundle
/// the name of the JSON resource. For example, if your resource is "properties.json" then this value will be set to "properties"
private let name: String
///
/// Will create a plist property loader
///
/// - parameter bundle: the bundle where the resource exists (defaults to mainBundle)
/// - parameter name: the name of the JSON resource. For example, if your resource is "properties.plist"
/// then this value will be set to "properties"
///
public init(bundle: NSBundle? = .mainBundle(), name: String) {
self.bundle = bundle!
self.name = name
}
}
// MARK: - PropertyLoadable
extension PlistPropertyLoader: PropertyLoaderType {
public func load() throws -> [String:AnyObject] {
let data = try loadDataFromBundle(bundle, withName: name, ofType: "plist")
let plist = try NSPropertyListSerialization.propertyListWithData(data, options: .Immutable, format: nil)
guard let props = plist as? [String:AnyObject] else {
throw PropertyLoaderError.InvalidPlistFormat(bundle: bundle, name: name)
}
return props
}
}
| 6654e48a23d46f0528cffef0214b8023 | 34.363636 | 133 | 0.672237 | false | false | false | false |
DrGo/LearningSwift | refs/heads/master | PLAYGROUNDS/LSB_C010_NaturalNumbers.playground/section-2.swift | gpl-3.0 | 2 | import UIKit
/*
// Natural Numbers
//
// Suggested Reading:
// http://www.fewbutripe.com/swift/math/2015/01/20/natural-numbers.html
// http://nshipster.com/swift-comparison-protocols/
// http://nshipster.com/swift-literal-convertible/
/===================================*/
/*---------------------------------------------------------/
// Box, a hack
/---------------------------------------------------------*/
class Box<T> {
let unbox: T
init(_ value: T) { self.unbox = value }
}
/*------------------------------------/
// As an Enum
/------------------------------------*/
enum Nat {
case Zero
case Succ(Box<Nat>)
}
func succ(v: Nat) -> Nat {
return .Succ(Box(v))
}
// A few examples
let zero: Nat = .Zero
let one: Nat = succ(.Zero)
let two: Nat = succ(one)
let three: Nat = succ(two)
let four: Nat = succ(succ(succ(succ(.Zero))))
/*------------------------------------/
// Equality ==
//
// Note: a-1 == b-1
/------------------------------------*/
extension Nat : Equatable {}
func == (a: Nat, b: Nat) -> Bool {
switch (a, b) {
case (.Zero, .Zero):
return true
case (.Zero, .Succ), (.Succ, .Zero):
return false
case let (.Succ(pred_a), .Succ(pred_b)):
return pred_a.unbox == pred_b.unbox
}
}
// Equality examples:
zero == zero
one == one
one == two
four == succ(succ(succ(succ(.Zero))))
/*------------------------------------/
// Addition +
//
// Note: a+b = (a-1)+(b+1)
/------------------------------------*/
func add (a: Nat, b: Nat) -> Nat {
switch (a, b) {
case (_, .Zero):
return a
case (.Zero, _):
return b
case let (.Succ(pred_a), _):
return add(pred_a.unbox, succ(b))
}
}
func + (a: Nat, b: Nat) -> Nat {
return add(a, b)
}
// Addition examples:
let five = two + three
let ten = five + five
ten == two + five + three
(one + three) == (two + two)
/*------------------------------------/
// Multiplication *
//
// Note: a*b = (a-1) * b + b
/------------------------------------*/
func * (a: Nat, b: Nat) -> Nat {
switch (a, b) {
case (_, .Zero), (.Zero, _):
return .Zero
case let (.Succ(pred_a), _):
return pred_a.unbox * b + b
}
}
// Multiplication examples:
one * four == four
two * two == four
four * three == two + two * five
two * three == five
/*------------------------------------/
// Power ^
//
// Note: a^b = (a^(b-1)) * a)
/------------------------------------*/
infix operator ^ {}
func ^ (a: Nat, b: Nat) -> Nat {
switch (a, b) {
case (.Zero, _):
return .Zero
case (_, .Zero):
return one
case let (_, .Succ(pred_b)):
return (a ^ pred_b.unbox) * a
}
}
// Power examples:
(zero ^ zero) == zero
(zero ^ one) == zero
(zero ^ two) == zero
(one ^ zero) == one
(two ^ zero) == one
(two ^ two) == four
/*------------------------------------/
// Comparable < <= >= >
//
// Note: a-1 < b-1
/------------------------------------*/
extension Nat : Comparable {}
func <(a: Nat, b: Nat) -> Bool {
switch (a, b) {
case (.Zero, .Zero):
return false
case (.Succ, .Zero):
return false
case (.Zero, .Succ):
return true
case let (.Succ(pred_a), .Succ(pred_b)):
return pred_a.unbox < pred_b.unbox
}
}
// Comparison examples:
one < two
two < one
one <= one
two <= one
one > zero
zero > one
two > one
three >= three
three >= two
two >= three
/*------------------------------------/
// Subtraction -
//
// Warning: This only handles positive
// results. (i.e. where a > b)
//
// Note: a-b = (a-1)-(b-1)
/------------------------------------*/
func subtract (a: Nat, b: Nat) -> Nat {
switch (a, b) {
case (.Zero, .Zero):
return .Zero
case (_, .Zero):
return a
case (.Zero, .Succ):
assertionFailure("Only handles Natural numbers! (a-b) where (b>a)")
case let (.Succ(pred_a), .Succ(pred_b)):
return subtract(pred_a.unbox, pred_b.unbox)
}
}
func - (a: Nat, b: Nat) -> Nat {
return subtract(a, b)
}
// Subtraction examples:
two - two == zero
two - one == one
three - one == two
three - two == one
/*------------------------------------/
// Division /
//
// Warning: Truncates return value,
// returning only Natural numbers.
// Effectively rounds down.
//
// Note: a/b =
// | b == 0 = error!
// | a < b = 0
// | a >= b = (a - b)/b + 1
/------------------------------------*/
func / (a: Nat, b: Nat) -> Nat {
if b == zero {
assertionFailure("Divide by zero error!")
} else if a < b {
return zero
} else {
return ((a - b) / b) + one
}
}
// Division examples:
three / four == zero
four / three == one
four / four == one
four / two == two
one / four == zero
/*------------------------------------/
// Min
/------------------------------------*/
func min (a: Nat, b: Nat) -> Nat {
return a <= b ? a : b
}
// Min examples:
min(zero, one) == zero
min(one, zero) == zero
min(one, two) == one
min(two, one) == one
min(three, one) == one
/*------------------------------------/
// Max
/------------------------------------*/
func max (a: Nat, b: Nat) -> Nat {
return a >= b ? a : b
}
// Max examples
max(zero, one) == one
max(one, zero) == one
max(one, two) == two
max(two, one) == two
max(three, one) == three
/*------------------------------------/
// Distance
/------------------------------------*/
func distance (a: Nat, b: Nat) -> Nat {
if a >= b {
return a - b
} else {
return b - a
}
}
// Distance examples:
distance(three, one) == two
distance(one, four) == three
distance(one, one) == zero
/*------------------------------------/
// Modulus
/------------------------------------*/
func % (a: Nat, b: Nat) -> Nat {
if b == zero {
assertionFailure("Divide by zero error!")
} else if a < b {
return a
} else {
return (a - b) % b
}
}
// Modulus examples:
three % five == three
five % three == two
zero % four == zero
four % two == zero
five % two == one
/*------------------------------------/
// Predecessor
/------------------------------------*/
func pred (n: Nat) -> Nat? {
switch n {
case .Zero:
return nil
case let .Succ(pred_n):
return pred_n.unbox as Nat?
}
}
let predOne = pred(one)
predOne!
//predOne == zero // <-- Huh?
predOne! == zero
pred(two)! == one
pred(five)! == four
pred(zero) == nil
/*------------------------------------/
// IntegerLiteralConvertible
/------------------------------------*/
extension Nat: IntegerLiteralConvertible {
typealias IntegerLiteralType = Int
init(integerLiteral value: IntegerLiteralType) {
if value < 0 {
assertionFailure("Must be >= 0")
} else if value == 0 {
self = .Zero
} else {
self = Array(0..<value).reduce(Nat.Zero) { sum, _ in
return succ(sum)
}
}
}
}
// Can use the verbose initializer with an Int
Nat(integerLiteral: 1) == one
Nat(integerLiteral: 0) == zero
Nat(integerLiteral: 2) == two
// Can convert from Int directly, as long as types match
let litZero: Nat = 0
litZero == zero
litZero == 0
one == 1 as Nat
two == 2 as Nat
let litThree: Nat = 3
litThree == three
litThree == 3
| 1d7bcc1dc998c4748e2b32391265a2b4 | 17.741333 | 72 | 0.460729 | false | false | false | false |
songzhw/2iOS | refs/heads/master | iOS_Swift/iOS_Swift/biz/basiclesson/todo/TodoCategoryViewController.swift | apache-2.0 | 1 | import UIKit
import RealmSwift
class TodoCategoryViewController: UITableViewController {
let realm = try! Realm()
var categoryArray:Results<TodoCategory>?
override func viewDidLoad() {
super.viewDidLoad()
// print(Realm.Configuration.defaultConfiguration.fileURL)
self.navigationController?.navigationBar.titleTextAttributes = [.foregroundColor: UIColor.orange]
self.navigationController?.navigationBar.tintColor = .white //所有图标就会变为白色
self.navigationController?.navigationBar.barTintColor = UIColor.orange
let btnAdd = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(addPressed))
self.navigationItem.rightBarButtonItem = btnAdd
categoryArray = realm.objects(TodoCategory.self)
self.tableView.reloadData() //UITableVC的子类中不需要为tableView另加outlet了
self.tableView.separatorStyle = .none
let nib = UINib(nibName: "TodoCell", bundle: nil)
self.tableView.register(nib, forCellReuseIdentifier: "TodoCell")
}
@objc func addPressed(){
var tf : UITextField? = nil
let alert = UIAlertController(title: "Add New Todo Category", message: "", preferredStyle: .alert)
alert.addTextField { tfRef in
tfRef.placeholder = "new category"
tf = tfRef
}
let action = UIAlertAction(title: "Add Category", style: .default) {action in
if let text = tf?.text {
let item = TodoCategory()
item.name = text
do {
try self.realm.write({
self.realm.add(item)
})
} catch {}
self.tableView.reloadData()
}
}
alert.addAction(action)
present(alert, animated: true, completion: nil)
}
// MARK: - TableView data source
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return categoryArray?.count ?? 1
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "TodoCell", for: indexPath) as! TodoCell
if let item = categoryArray?[indexPath.row] {
cell.lblMsg.text = item.name
}
return cell
}
// MARK: - TableView delegate
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let page = TodoListViewController()
page.selectedCategory = categoryArray?[indexPath.row]
self.navigationController?.pushViewController(page, animated: true)
}
}
| f76327c38873131588eecc13f42a3fdb | 33.39726 | 107 | 0.692951 | false | false | false | false |
lyft/SwiftLint | refs/heads/master | Source/SwiftLintFramework/Reporters/CSVReporter.swift | mit | 1 | import Foundation
private extension String {
func escapedForCSV() -> String {
let escapedString = replacingOccurrences(of: "\"", with: "\"\"")
if escapedString.contains(",") || escapedString.contains("\n") {
return "\"\(escapedString)\""
}
return escapedString
}
}
public struct CSVReporter: Reporter {
public static let identifier = "csv"
public static let isRealtime = false
public var description: String {
return "Reports violations as a newline-separated string of comma-separated values (CSV)."
}
public static func generateReport(_ violations: [StyleViolation]) -> String {
let keys = [
"file",
"line",
"character",
"severity",
"type",
"reason",
"rule_id"
].joined(separator: ",")
let rows = [keys] + violations.map(csvRow(for:))
return rows.joined(separator: "\n")
}
fileprivate static func csvRow(for violation: StyleViolation) -> String {
return [
violation.location.file?.escapedForCSV() ?? "",
violation.location.line?.description ?? "",
violation.location.character?.description ?? "",
violation.severity.rawValue.capitalized,
violation.ruleDescription.name.escapedForCSV(),
violation.reason.escapedForCSV(),
violation.ruleDescription.identifier
].joined(separator: ",")
}
}
| d73b675cb41034e3c59682ce0e9dc789 | 30.957447 | 98 | 0.584554 | false | false | false | false |
blockchain/My-Wallet-V3-iOS | refs/heads/master | Modules/Platform/Sources/PlatformUIKit/Components/RadioCell/RadioAccountSelectionTableViewCell/RadioAccountCellPresenter.swift | lgpl-3.0 | 1 | import PlatformKit
import RxCocoa
import RxDataSources
import RxSwift
public final class RadioAccountCellPresenter: IdentifiableType {
// MARK: - Public Properties
/// Streams the image content
public let imageContent: Driver<ImageViewContent>
// MARK: - RxDataSources
public let identity: AnyHashable
// MARK: - Internal
/// The `viewModel` for the `WalletView`
let viewModel: Driver<WalletViewViewModel>
// MARK: - Init
public init(
interactor: RadioAccountCellInteractor,
accessibilityPrefix: String = ""
) {
let model = WalletViewViewModel(
account: interactor.account,
descriptor: .init(
accessibilityPrefix: accessibilityPrefix
)
)
viewModel = .just(model)
identity = model.identifier
imageContent = interactor
.isSelected
.map { $0 ? "checkbox-selected" : "checkbox-empty" }
.asDriver(onErrorJustReturn: nil)
.compactMap { name -> ImageViewContent? in
guard let name = name else {
return nil
}
return ImageViewContent(
imageResource: .local(name: name, bundle: .platformUIKit),
accessibility: .id("\(accessibilityPrefix)\(name)"),
renderingMode: .normal
)
}
}
}
extension RadioAccountCellPresenter: Equatable {
public static func == (lhs: RadioAccountCellPresenter, rhs: RadioAccountCellPresenter) -> Bool {
lhs.identity == rhs.identity
}
}
| 1a49d74b63428212b495b7496bcc62a9 | 27.189655 | 100 | 0.592049 | false | false | false | false |
duming91/Hear-You | refs/heads/master | Hear You/ViewControllers/Base/HYTabBarController.swift | gpl-3.0 | 1 | //
// HYTabBarController.swift
// Hear You
//
// Created by 董亚珣 on 16/6/1.
// Copyright © 2016年 snow. All rights reserved.
//
import UIKit
import RAMAnimatedTabBarController
class HYTabBarController: UITabBarController {
override func viewDidLoad() {
super.viewDidLoad()
delegate = self
// Do any additional setup after loading the view.
}
func showPlayerViewControllerWithSong(song: Song, inCategory category: SongCategory) {
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let tmpVc = storyboard.instantiateViewControllerWithIdentifier("PlayerViewController") as! PlayerViewController
tmpVc.song = song
tmpVc.category = category
tmpVc.songlist = category.currentSonglist
let vc = UINavigationController(rootViewController: tmpVc)
vc.modalTransitionStyle = .CrossDissolve
self.presentViewController(vc, animated: true, completion: nil)
if let sideMenuViewController = sideMenuViewController {
sideMenuViewController.hideMenuViewController()
}
}
private func showPlayerViewController() {
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let tmpVc = storyboard.instantiateViewControllerWithIdentifier("PlayerViewController") as! PlayerViewController
if let song = AudioPlayer.sharedPlayer.currentSong,
let category = AudioPlayer.sharedPlayer.currentCategory,
let songlist = AudioPlayer.sharedPlayer.currentCategory?.currentSonglist {
tmpVc.song = song
tmpVc.category = category
tmpVc.songlist = songlist
} else if let song = gStorage.lastSong,
let category = gStorage.lastSongCategory {
tmpVc.song = song
tmpVc.category = category
tmpVc.songlist = category.currentSonglist
} else {
Alert.showMiddleHint("请先选择一首歌曲来播放")
return
}
let vc = UINavigationController(rootViewController: tmpVc)
vc.modalTransitionStyle = .CrossDissolve
self.presentViewController(vc, animated: true, completion: nil)
if let sideMenuViewController = sideMenuViewController {
sideMenuViewController.hideMenuViewController()
}
}
}
extension HYTabBarController: UITabBarControllerDelegate {
func tabBarController(tabBarController: UITabBarController, shouldSelectViewController viewController: UIViewController) -> Bool {
if viewController.isKindOfClass(PlayerViewController) {
self.showPlayerViewController()
return false
}
return true
}
}
| 0a6baa67c7adce614af411c8dd1afb83 | 33.822785 | 134 | 0.664849 | false | false | false | false |
mxcl/swift-package-manager | refs/heads/master | Sources/Get/PackagesDirectory.swift | apache-2.0 | 1 | /*
This source file is part of the Swift.org open source project
Copyright 2015 - 2016 Apple Inc. and the Swift project authors
Licensed under Apache License v2.0 with Runtime Library Exception
See http://swift.org/LICENSE.txt for license information
See http://swift.org/CONTRIBUTORS.txt for Swift project authors
*/
import Basic
import PackageLoading
import PackageModel
import Utility
import func POSIX.rename
/// A container for fetched packages.
///
/// Despite being currently called `PackagesDirectory`, this actually holds
/// repositories and is used to vend a set of resolved manifests.
///
/// This object also exposes the capability to resolve a package graph while
/// loading packages. This is not conceptually the right division of
/// responsibility, but it is pragmatic for now.
public final class PackagesDirectory {
/// The root package path.
let rootPath: AbsolutePath
/// The manifest loader.
let manifestLoader: ManifestLoader
/// Create a new package directory.
///
/// - Parameters
/// - rootPath: The path of the root package, inside which the "Packages/"
/// subdirectory will be created.
public init(root rootPath: AbsolutePath, manifestLoader: ManifestLoader) {
self.rootPath = rootPath
self.manifestLoader = manifestLoader
}
/// The path to the packages.
var packagesPath: AbsolutePath {
return rootPath.appending(component: "Packages")
}
/// The set of all repositories available within the `Packages` directory, by origin.
fileprivate lazy var availableRepositories: [String: Git.Repo] = { [unowned self] in
// FIXME: Lift this higher.
guard localFileSystem.isDirectory(self.packagesPath) else { return [:] }
var result = Dictionary<String, Git.Repo>()
for name in try! localFileSystem.getDirectoryContents(self.packagesPath) {
let prefix = self.packagesPath.appending(RelativePath(name))
guard let repo = Git.Repo(path: prefix), let origin = repo.origin else { continue } // TODO: Warn user.
result[origin] = repo
}
return result
}()
/// Recursively fetch the dependencies for the root package.
///
/// - Returns: The loaded root package and all external packages, with dependencies resolved.
/// - Throws: Error.InvalidDependencyGraph
public func loadManifests() throws -> (rootManifest: Manifest, externalManifests: [Manifest]) {
// Load the manifest for the root package.
let manifest = try manifestLoader.load(packagePath: rootPath, baseURL: rootPath.asString, version: nil)
// Resolve and fetch all package dependencies and their manifests.
let externalManifests = try recursivelyFetch(manifest.dependencies)
return (manifest, externalManifests)
}
}
/// Support fetching using the PackagesDirectory directly.
extension PackagesDirectory: Fetcher {
typealias T = Manifest
/// Extract the package version from a path.
//
// FIXME: This is really gross, and should not be necessary -- we should
// maintain the state we care about in a well defined format, not just via
// the file system path.
private func extractPackageVersion(_ name: String) -> Version? {
// Search each suffix separated by a '-'.
var name = name
while let separatorIndex = name.characters.rindex(of: "-") {
// See if there is a parseable version (there could be prerelease identifiers, etc.).
let versionString = String(name.characters.suffix(from: name.index(after: separatorIndex)))
if let version = Version(versionString) {
return version
}
// If not, keep looking.
name = String(name.characters.prefix(upTo: separatorIndex))
}
return nil
}
/// Create a Manifest for a given repositories current state.
private func createManifest(repo: Git.Repo) throws -> Manifest? {
guard let origin = repo.origin else {
throw Package.Error.noOrigin(repo.path.asString)
}
guard let version = extractPackageVersion(repo.path.basename) else {
return nil
}
return try manifestLoader.load(packagePath: repo.path, baseURL: origin, version: version)
}
func find(url: String) throws -> Fetchable? {
if let repo = availableRepositories[url] {
return try createManifest(repo: repo)
}
return nil
}
func fetch(url: String) throws -> Fetchable {
// Clone into a staging location, we will rename it once all versions are selected.
let manifestParser = { try self.manifestLoader.load(packagePath: $0, baseURL: $1, version: $2) }
let basename = url.components(separatedBy: "/").last!
let dstdir = packagesPath.appending(component: basename)
if let repo = Git.Repo(path: dstdir), repo.origin == url {
//TODO need to canonicalize the URL need URL struct
return try RawClone(path: dstdir, manifestParser: manifestParser)
}
// fetch as well, clone does not fetch all tags, only tags on the master branch
try Git.clone(url, to: dstdir).fetch()
return try RawClone(path: dstdir, manifestParser: manifestParser)
}
func finalize(_ fetchable: Fetchable) throws -> Manifest {
switch fetchable {
case let clone as RawClone:
let prefix = self.packagesPath.appending(component: clone.finalName)
try makeDirectories(packagesPath.parentDirectory)
try rename(old: clone.path.asString, new: prefix.asString)
//TODO don't reparse the manifest!
let repo = Git.Repo(path: prefix)!
// Update the available repositories.
availableRepositories[repo.origin!] = repo
return try createManifest(repo: repo)!
case let manifest as Manifest:
return manifest
default:
fatalError("Unexpected Fetchable Type: \(fetchable)")
}
}
}
//TODO normalize urls eg http://github.com -> https://github.com
//TODO probably should respect any relocation that applies during git transfer
//TODO detect cycles?
extension Manifest {
var dependencies: [(String, Range<Version>)] {
return package.dependencies.map{ ($0.url, $0.versionRange) }
}
}
| 19c510e5c5bc2974a6502df1d140557d | 37.843373 | 115 | 0.663617 | false | false | false | false |
IvanVorobei/TwitterLaunchAnimation | refs/heads/master | TwitterLaunchAnimation - project/TwitterLaucnhAnimation/sparrow/ui/views/collectionViews/layouts/SPPageItemsScalingCollectionLayout.swift | mit | 1 | // The MIT License (MIT)
// Copyright © 2017 Ivan Vorobei ([email protected])
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
import UIKit
public class SPPageItemsScalingCollectionLayout: UICollectionViewFlowLayout {
var itemSideRatio: CGFloat = 0.764
var itemSpacingFactor: CGFloat = 0.11
var scaleItems: Bool = true
var scalingOffset: CGFloat = 200
var minimumScaleFactor: CGFloat = 0.9
var minimumAlphaFactor: CGFloat = 0.3
var pageWidth: CGFloat {
get {
return self.itemSize.width + self.minimumLineSpacing
}
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override init() {
super.init()
scrollDirection = .horizontal
}
public override func targetContentOffset( forProposedContentOffset proposedContentOffset: CGPoint, withScrollingVelocity velocity: CGPoint) -> CGPoint {
let rawPageValue = (self.collectionView!.contentOffset.x) / self.pageWidth
let currentPage = (velocity.x > 0.0) ? floor(rawPageValue) : ceil(rawPageValue);
let nextPage = (velocity.x > 0.0) ? ceil(rawPageValue) : floor(rawPageValue);
let pannedLessThanAPage = fabs(1 + currentPage - rawPageValue) > 0.5;
let flicked = fabs(velocity.x) > 0.3
var proposedContentOffset = proposedContentOffset
if (pannedLessThanAPage && flicked) {
proposedContentOffset.x = nextPage * self.pageWidth
} else {
proposedContentOffset.x = round(rawPageValue) * self.pageWidth
}
return proposedContentOffset;
}
override public func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
guard let collectionView = self.collectionView,
let superAttributes = super.layoutAttributesForElements(in: rect) else {
return super.layoutAttributesForElements(in: rect)
}
if scaleItems == false {
return super.layoutAttributesForElements(in: rect)
}
let contentOffset = collectionView.contentOffset
let size = collectionView.bounds.size
let visibleRect = CGRect.init(x: contentOffset.x, y: contentOffset.y, width: size.width, height: size.height)
let visibleCenterX = visibleRect.midX
guard case let newAttributesArray as [UICollectionViewLayoutAttributes] = NSArray(array: superAttributes, copyItems: true) else {
return nil
}
newAttributesArray.forEach {
let distanceFromCenter = visibleCenterX - $0.center.x
let absDistanceFromCenter = min(abs(distanceFromCenter), self.scalingOffset)
let scale = absDistanceFromCenter * (self.minimumScaleFactor - 1) / self.scalingOffset + 1
$0.transform3D = CATransform3DScale(CATransform3DIdentity, scale, scale, 1)
let alpha = absDistanceFromCenter * (self.minimumAlphaFactor - 1) / self.scalingOffset + 1
$0.alpha = alpha
}
return newAttributesArray
}
override public func shouldInvalidateLayout(forBoundsChange newBounds: CGRect) -> Bool {
return true
}
override public func prepare() {
super.prepare()
guard let collectionView = self.collectionView else {
return
}
var heightItems = collectionView.bounds.height
if (heightItems > 400) {
heightItems = 400
}
self.itemSize = CGSize(width: heightItems * self.itemSideRatio, height: heightItems)
self.minimumLineSpacing = self.itemSize.width * self.itemSpacingFactor
}
}
| 43722b7b4d126eccccf9e71df89e4b06 | 40.145299 | 156 | 0.669713 | false | false | false | false |
flodolo/firefox-ios | refs/heads/main | Client/Frontend/Update/UpdateViewController.swift | mpl-2.0 | 2 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import UIKit
import Shared
class UpdateViewController: UIViewController, OnboardingViewControllerProtocol {
// Update view UX constants
struct UX {
static let closeButtonTopPadding: CGFloat = 32
static let closeButtonRightPadding: CGFloat = 16
static let closeButtonSize: CGFloat = 30
static let pageControlHeight: CGFloat = 40
static let pageControlBottomPadding: CGFloat = 8
}
// Public constants
var viewModel: UpdateViewModel
var didFinishFlow: (() -> Void)?
private var informationCards = [OnboardingCardViewController]()
var notificationCenter: NotificationProtocol = NotificationCenter.default
// MARK: - Private vars
private lazy var closeButton: UIButton = .build { button in
button.setImage(UIImage(named: ImageIdentifiers.bottomSheetClose), for: .normal)
button.addTarget(self, action: #selector(self.closeUpdate), for: .touchUpInside)
button.accessibilityIdentifier = AccessibilityIdentifiers.Upgrade.closeButton
}
private lazy var pageController: UIPageViewController = {
let pageVC = UIPageViewController(transitionStyle: .scroll, navigationOrientation: .horizontal)
pageVC.dataSource = self
pageVC.delegate = self
return pageVC
}()
private lazy var pageControl: UIPageControl = .build { pageControl in
pageControl.currentPage = 0
pageControl.numberOfPages = self.viewModel.enabledCards.count
pageControl.currentPageIndicatorTintColor = UIColor.Photon.Blue50
pageControl.pageIndicatorTintColor = UIColor.Photon.LightGrey40
pageControl.isUserInteractionEnabled = false
pageControl.accessibilityIdentifier = AccessibilityIdentifiers.Upgrade.pageControl
}
init(viewModel: UpdateViewModel) {
self.viewModel = viewModel
super.init(nibName: nil, bundle: nil)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
deinit {
notificationCenter.removeObserver(self)
}
override func viewDidLoad() {
super.viewDidLoad()
setupView()
setupNotifications(forObserver: self,
observing: [.DisplayThemeChanged])
applyTheme()
}
// MARK: View setup
private func setupView() {
view.backgroundColor = UIColor.theme.browser.background
if viewModel.shouldShowSingleCard {
setupSingleInfoCard()
} else {
setupMultipleCards()
setupMultipleCardsConstraints()
}
}
private func setupSingleInfoCard() {
guard let viewModel = viewModel.getCardViewModel(cardType: viewModel.enabledCards[0]) else { return }
let cardViewController = OnboardingCardViewController(viewModel: viewModel,
delegate: self)
view.addSubview(closeButton)
addChild(cardViewController)
view.addSubview(cardViewController.view)
cardViewController.didMove(toParent: self)
view.bringSubviewToFront(closeButton)
NSLayoutConstraint.activate([
closeButton.topAnchor.constraint(equalTo: view.topAnchor, constant: UX.closeButtonTopPadding),
closeButton.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -UX.closeButtonRightPadding),
closeButton.widthAnchor.constraint(equalToConstant: UX.closeButtonSize),
closeButton.heightAnchor.constraint(equalToConstant: UX.closeButtonSize)
])
}
private func setupMultipleCards() {
// Create onboarding card views
var cardViewController: OnboardingCardViewController
for cardType in viewModel.enabledCards {
if let viewModel = viewModel.getCardViewModel(cardType: cardType) {
cardViewController = OnboardingCardViewController(viewModel: viewModel,
delegate: self)
informationCards.append(cardViewController)
}
}
if let firstViewController = informationCards.first {
pageController.setViewControllers([firstViewController],
direction: .forward,
animated: true,
completion: nil)
}
}
private func setupMultipleCardsConstraints() {
addChild(pageController)
view.addSubview(pageController.view)
pageController.didMove(toParent: self)
view.addSubviews(pageControl, closeButton)
NSLayoutConstraint.activate([
pageControl.leadingAnchor.constraint(equalTo: view.leadingAnchor),
pageControl.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor,
constant: -UX.pageControlBottomPadding),
pageControl.trailingAnchor.constraint(equalTo: view.trailingAnchor),
closeButton.topAnchor.constraint(equalTo: view.topAnchor, constant: UX.closeButtonTopPadding),
closeButton.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -UX.closeButtonRightPadding),
closeButton.widthAnchor.constraint(equalToConstant: UX.closeButtonSize),
closeButton.heightAnchor.constraint(equalToConstant: UX.closeButtonSize),
])
}
// Button Actions
@objc private func closeUpdate() {
didFinishFlow?()
viewModel.sendCloseButtonTelemetry(index: pageControl.currentPage)
}
func getNextOnboardingCard(index: Int, goForward: Bool) -> OnboardingCardViewController? {
guard let index = viewModel.getNextIndex(currentIndex: index, goForward: goForward) else { return nil }
return informationCards[index]
}
// Used to programmatically set the pageViewController to show next card
func moveToNextPage(cardType: IntroViewModel.InformationCards) {
if let nextViewController = getNextOnboardingCard(index: cardType.position, goForward: true) {
pageControl.currentPage = cardType.position + 1
pageController.setViewControllers([nextViewController], direction: .forward, animated: false)
}
}
// Due to restrictions with PageViewController we need to get the index of the current view controller
// to calculate the next view controller
func getCardIndex(viewController: OnboardingCardViewController) -> Int? {
let cardType = viewController.viewModel.cardType
guard let index = viewModel.enabledCards.firstIndex(of: cardType) else { return nil }
return index
}
private func presentSignToSync(_ fxaOptions: FxALaunchParams? = nil,
flowType: FxAPageType = .emailLoginFlow,
referringPage: ReferringPage = .onboarding) {
let singInSyncVC = FirefoxAccountSignInViewController.getSignInOrFxASettingsVC(
fxaOptions,
flowType: flowType,
referringPage: referringPage,
profile: viewModel.profile)
let controller: DismissableNavigationViewController
let buttonItem = UIBarButtonItem(title: .SettingsSearchDoneButton,
style: .plain,
target: self,
action: #selector(dismissSignInViewController))
let theme = BuiltinThemeName(rawValue: LegacyThemeManager.instance.current.name) ?? .normal
buttonItem.tintColor = theme == .dark ? UIColor.theme.homePanel.activityStreamHeaderButton : UIColor.Photon.Blue50
singInSyncVC.navigationItem.rightBarButtonItem = buttonItem
controller = DismissableNavigationViewController(rootViewController: singInSyncVC)
controller.onViewDismissed = {
self.closeUpdate()
}
self.present(controller, animated: true)
}
@objc func dismissSignInViewController() {
dismiss(animated: true, completion: nil)
closeUpdate()
}
}
// MARK: UIPageViewControllerDataSource & UIPageViewControllerDelegate
extension UpdateViewController: UIPageViewControllerDataSource, UIPageViewControllerDelegate {
func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? {
guard let onboardingVC = viewController as? OnboardingCardViewController,
let index = getCardIndex(viewController: onboardingVC) else {
return nil
}
pageControl.currentPage = index
return getNextOnboardingCard(index: index, goForward: false)
}
func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? {
guard let onboardingVC = viewController as? OnboardingCardViewController,
let index = getCardIndex(viewController: onboardingVC) else {
return nil
}
pageControl.currentPage = index
return getNextOnboardingCard(index: index, goForward: true)
}
}
extension UpdateViewController: OnboardingCardDelegate {
func showNextPage(_ cardType: IntroViewModel.InformationCards) {
guard cardType != viewModel.enabledCards.last else {
self.didFinishFlow?()
return
}
moveToNextPage(cardType: cardType)
}
func primaryAction(_ cardType: IntroViewModel.InformationCards) {
switch cardType {
case .updateWelcome:
showNextPage(cardType)
case .updateSignSync:
presentSignToSync()
default:
break
}
}
// Extra step to make sure pageControl.currentPage is the right index card
// because UIPageViewControllerDataSource call fails
func pageChanged(_ cardType: IntroViewModel.InformationCards) {
if let cardIndex = viewModel.positionForCard(cardType: cardType),
cardIndex != pageControl.currentPage {
pageControl.currentPage = cardIndex
}
}
}
// MARK: UIViewController setup
extension UpdateViewController {
override var prefersStatusBarHidden: Bool {
return true
}
override var shouldAutorotate: Bool {
return false
}
override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
// This actually does the right thing on iPad where the modally
// presented version happily rotates with the iPad orientation.
return .portrait
}
}
// MARK: - NotificationThemeable and Notifiable
extension UpdateViewController: NotificationThemeable, Notifiable {
func handleNotifications(_ notification: Notification) {
switch notification.name {
case .DisplayThemeChanged:
applyTheme()
default:
break
}
}
func applyTheme() {
guard !viewModel.shouldShowSingleCard else { return }
let theme = BuiltinThemeName(rawValue: LegacyThemeManager.instance.current.name) ?? .normal
let indicatorColor = theme == .dark ? UIColor.theme.homePanel.activityStreamHeaderButton : UIColor.Photon.Blue50
pageControl.currentPageIndicatorTintColor = indicatorColor
view.backgroundColor = theme == .dark ? UIColor.Photon.DarkGrey40 : .white
informationCards.forEach { cardViewController in
cardViewController.applyTheme()
}
}
}
| 53370bdae94d8f433bb9530ea37e2c47 | 38.872054 | 149 | 0.67193 | false | false | false | false |
ngominhtrint/Twittient | refs/heads/master | Twittient/AppDelegate.swift | apache-2.0 | 1 | //
// AppDelegate.swift
// Twittient
//
// Created by TriNgo on 3/23/16.
// Copyright © 2016 TriNgo. All rights reserved.
//
import UIKit
import BDBOAuth1Manager
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
if User.currentUser != nil {
print("There is a current user")
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let vc = storyboard.instantiateViewControllerWithIdentifier("TweetsNavigationController")
window?.rootViewController = vc
}
NSNotificationCenter.defaultCenter().addObserverForName(User.userDidLogoutNotification, object: nil, queue: NSOperationQueue.mainQueue()) { (NSNotification) -> Void in
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let vc = storyboard.instantiateInitialViewController()
self.window?.rootViewController = vc
}
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
func application(app: UIApplication, openURL url: NSURL, options: [String : AnyObject]) -> Bool {
print(url)
TwitterClient.shareInstance.handleOpenUrl(url)
return true
}
}
| e3405bf1d03b224471be46264354ae00 | 44.323529 | 285 | 0.717391 | false | false | false | false |
krevis/MIDIApps | refs/heads/main | Frameworks/SnoizeMIDI/Device.swift | bsd-3-clause | 1 | /*
Copyright (c) 2021, Kurt Revis. All rights reserved.
This source code is licensed under the BSD-style license found in the
LICENSE file in the root directory of this source tree.
*/
import Foundation
import CoreMIDI
public class Device: MIDIObject, CoreMIDIObjectListable {
static let midiObjectType = MIDIObjectType.device
static func midiObjectCount(_ context: CoreMIDIContext) -> Int {
context.interface.getNumberOfDevices()
}
static func midiObjectSubscript(_ context: CoreMIDIContext, _ index: Int) -> MIDIObjectRef {
context.interface.getDevice(index)
}
override func midiPropertyChanged(_ property: CFString) {
super.midiPropertyChanged(property)
if property == kMIDIPropertyOffline {
// This device just went offline or online. If it went online,
// its sources might now appear in MIDIGetNumberOfSources/GetSourceAtIndex,
// and this is the only way we'll find out. (Same thing for destinations.)
// Similarly, if it went offline, its sources/destinations won't be
// in the list anymore.
midiContext.updateEndpointsForDevice(self)
}
if property == kMIDIPropertyName {
// This may affect the displayName of associated sources and destinations.
let interface = midiContext.interface
for entityIndex in 0 ..< interface.deviceGetNumberOfEntities(midiObjectRef) {
let entityRef = interface.deviceGetEntity(midiObjectRef, entityIndex)
for index in 0 ..< interface.entityGetNumberOfSources(entityRef) {
let sourceRef = interface.entityGetSource(entityRef, index)
midiContext.forcePropertyChanged(.source, sourceRef, kMIDIPropertyDisplayName)
}
for index in 0 ..< interface.entityGetNumberOfDestinations(entityRef) {
let destinationRef = interface.entityGetDestination(entityRef, index)
midiContext.forcePropertyChanged(.destination, destinationRef, kMIDIPropertyDisplayName)
}
}
}
}
}
| 51fc5b85c0aaef11e060bf4ad68d6beb | 40.730769 | 108 | 0.666359 | false | false | false | false |
wikimedia/wikipedia-ios | refs/heads/main | WMF Framework/CacheFetching.swift | mit | 1 | import Foundation
public struct CacheFetchingResult {
let data: Data
let response: URLResponse
}
enum CacheFetchingError: Error {
case missingDataAndURLResponse
case missingURLResponse
case unableToDetermineURLRequest
}
public protocol CacheFetching {
typealias TemporaryFileURL = URL
typealias MIMEType = String
typealias DownloadCompletion = (Error?, URLRequest?, URLResponse?, TemporaryFileURL?, MIMEType?) -> Void
typealias DataCompletion = (Result<CacheFetchingResult, Error>) -> Void
// internally populates urlRequest with cache header fields
func dataForURL(_ url: URL, persistType: Header.PersistItemType, headers: [String: String], completion: @escaping DataCompletion) -> URLSessionTask?
// assumes urlRequest is already populated with cache header fields
func dataForURLRequest(_ urlRequest: URLRequest, completion: @escaping DataCompletion) -> URLSessionTask?
// Session Passthroughs
func cachedResponseForURL(_ url: URL, type: Header.PersistItemType) -> CachedURLResponse?
func cachedResponseForURLRequest(_ urlRequest: URLRequest) -> CachedURLResponse? // assumes urlRequest is already populated with the proper cache headers
func uniqueKeyForURL(_ url: URL, type: Header.PersistItemType) -> String?
func cacheResponse(httpUrlResponse: HTTPURLResponse, content: CacheResponseContentType, urlRequest: URLRequest, success: @escaping () -> Void, failure: @escaping (Error) -> Void)
func uniqueFileNameForItemKey(_ itemKey: CacheController.ItemKey, variant: String?) -> String?
func uniqueHeaderFileNameForItemKey(_ itemKey: CacheController.ItemKey, variant: String?) -> String?
func uniqueFileNameForURLRequest(_ urlRequest: URLRequest) -> String?
func itemKeyForURLRequest(_ urlRequest: URLRequest) -> String?
func variantForURLRequest(_ urlRequest: URLRequest) -> String?
// Bundled migration only - copies files into cache
func writeBundledFiles(mimeType: String, bundledFileURL: URL, urlRequest: URLRequest, completion: @escaping (Result<Void, Error>) -> Void)
}
extension CacheFetching where Self:Fetcher {
@discardableResult public func dataForURLRequest(_ urlRequest: URLRequest, completion: @escaping DataCompletion) -> URLSessionTask? {
let task = session.dataTask(with: urlRequest) { (data, urlResponse, error) in
if let error = error {
completion(.failure(error))
return
}
guard let unwrappedResponse = urlResponse else {
completion(.failure(CacheFetchingError.missingURLResponse))
return
}
if let httpResponse = unwrappedResponse as? HTTPURLResponse, httpResponse.statusCode != 200 {
completion(.failure(RequestError.unexpectedResponse))
return
}
if let data = data,
let urlResponse = urlResponse {
let result = CacheFetchingResult(data: data, response: urlResponse)
completion(.success(result))
} else {
completion(.failure(CacheFetchingError.missingDataAndURLResponse))
}
}
task?.resume()
return task
}
@discardableResult public func dataForURL(_ url: URL, persistType: Header.PersistItemType, headers: [String: String] = [:], completion: @escaping DataCompletion) -> URLSessionTask? {
guard let urlRequest = session.urlRequestFromPersistence(with: url, persistType: persistType, headers: headers) else {
completion(.failure(CacheFetchingError.unableToDetermineURLRequest))
return nil
}
return dataForURLRequest(urlRequest, completion: completion)
}
}
// MARK: Session Passthroughs
extension CacheFetching where Self:Fetcher {
public func cachedResponseForURL(_ url: URL, type: Header.PersistItemType) -> CachedURLResponse? {
return session.cachedResponseForURL(url, type: type)
}
public func cachedResponseForURLRequest(_ urlRequest: URLRequest) -> CachedURLResponse? {
return session.cachedResponseForURLRequest(urlRequest)
}
public func uniqueFileNameForURLRequest(_ urlRequest: URLRequest) -> String? {
return session.uniqueFileNameForURLRequest(urlRequest)
}
public func uniqueKeyForURL(_ url: URL, type: Header.PersistItemType) -> String? {
return session.uniqueKeyForURL(url, type: type)
}
public func cacheResponse(httpUrlResponse: HTTPURLResponse, content: CacheResponseContentType, urlRequest: URLRequest, success: @escaping () -> Void, failure: @escaping (Error) -> Void) {
session.cacheResponse(httpUrlResponse: httpUrlResponse, content: content, urlRequest: urlRequest, success: success, failure: failure)
}
public func writeBundledFiles(mimeType: String, bundledFileURL: URL, urlRequest: URLRequest, completion: @escaping (Result<Void, Error>) -> Void) {
session.writeBundledFiles(mimeType: mimeType, bundledFileURL: bundledFileURL, urlRequest: urlRequest, completion: completion)
}
public func uniqueFileNameForItemKey(_ itemKey: CacheController.ItemKey, variant: String?) -> String? {
return session.uniqueFileNameForItemKey(itemKey, variant: variant)
}
public func itemKeyForURLRequest(_ urlRequest: URLRequest) -> String? {
return session.itemKeyForURLRequest(urlRequest)
}
public func variantForURLRequest(_ urlRequest: URLRequest) -> String? {
return session.variantForURLRequest(urlRequest)
}
public func itemKeyForURL(_ url: URL, type: Header.PersistItemType) -> String? {
return session.itemKeyForURL(url, type: type)
}
public func variantForURL(_ url: URL, type: Header.PersistItemType) -> String? {
return session.variantForURL(url, type: type)
}
public func urlRequestFromPersistence(with url: URL, persistType: Header.PersistItemType, cachePolicy: WMFCachePolicy? = nil, headers: [String: String] = [:]) -> URLRequest? {
return session.urlRequestFromPersistence(with: url, persistType: persistType, cachePolicy: cachePolicy, headers: headers)
}
public func uniqueHeaderFileNameForItemKey(_ itemKey: CacheController.ItemKey, variant: String?) -> String? {
return session.uniqueHeaderFileNameForItemKey(itemKey, variant: variant)
}
public func isCachedWithURLRequest(_ request: URLRequest, completion: @escaping (Bool) -> Void) {
return session.isCachedWithURLRequest(request, completion: completion)
}
}
| ac431dc38cdf4064541a2fa082d66122 | 45.441379 | 191 | 0.69706 | false | false | false | false |
seaburg/PHDiff | refs/heads/master | Example/Example/DemoTableViewController.swift | mit | 1 | //
// DemoTableViewController.swift
// Example
//
// Created by Andre Alves on 10/12/16.
// Copyright © 2016 Andre Alves. All rights reserved.
//
import UIKit
import PHDiff
final class DemoTableViewController: UITableViewController {
private var colors: [DemoColor] = []
override func viewDidLoad() {
super.viewDidLoad()
tableView.tableFooterView = UIView()
}
@IBAction func didTapShuffleButton(_ sender: UIBarButtonItem) {
shuffle()
}
private func shuffle() {
updateTableView(newColors: RandomDemoColors().randomColors())
}
private func updateTableView(newColors: [DemoColor]) {
let steps = newColors.difference(from: self.colors)
self.colors = newColors
tableView.beginUpdates()
tableView.ph_updateSection(0, steps: steps)
tableView.endUpdates()
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return colors.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "DemoCell", for: indexPath)
let color = colors[indexPath.row]
cell.textLabel?.text = color.name
cell.backgroundColor = color.toUIColor()
return cell
}
}
| 63c6d577f40edecb7c42246dc7ab4713 | 27.5 | 109 | 0.674708 | false | false | false | false |
khoren93/Fusuma | refs/heads/master | Sources/FSVideoCameraView.swift | mit | 1 | //
// FSVideoCameraView.swift
// Fusuma
//
// Created by Brendan Kirchner on 3/18/16.
// Copyright © 2016 CocoaPods. All rights reserved.
//
import UIKit
import AVFoundation
@objc protocol FSVideoCameraViewDelegate: class {
func videoFinished(withFileURL fileURL: URL)
}
final class FSVideoCameraView: UIView {
@IBOutlet weak var previewViewContainer: UIView!
@IBOutlet weak var shotButton: UIButton!
@IBOutlet weak var flashButton: UIButton!
@IBOutlet weak var flipButton: UIButton!
weak var delegate: FSVideoCameraViewDelegate? = nil
var session: AVCaptureSession?
var device: AVCaptureDevice?
var videoInput: AVCaptureDeviceInput?
var videoOutput: AVCaptureMovieFileOutput?
var focusView: UIView?
var flashOffImage: UIImage?
var flashOnImage: UIImage?
var videoStartImage: UIImage?
var videoStopImage: UIImage?
fileprivate var isRecording = false
static func instance() -> FSVideoCameraView {
return UINib(nibName: "FSVideoCameraView", bundle: Bundle(for: self.classForCoder())).instantiate(withOwner: self, options: nil)[0] as! FSVideoCameraView
}
func initialize() {
if session != nil {
return
}
self.backgroundColor = UIColor.hex("#FFFFFF", alpha: 1.0)
self.isHidden = false
// AVCapture
session = AVCaptureSession()
for device in AVCaptureDevice.devices() {
if let device = device as? AVCaptureDevice , device.position == AVCaptureDevicePosition.front {
self.device = device
if !device.hasFlash {
flashButton.isHidden = true
}
}
}
do {
if let session = session {
videoInput = try AVCaptureDeviceInput(device: device)
session.addInput(videoInput)
videoOutput = AVCaptureMovieFileOutput()
let totalSeconds = 60.0 //Total Seconds of capture time
let timeScale: Int32 = 30 //FPS
let maxDuration = CMTimeMakeWithSeconds(totalSeconds, timeScale)
videoOutput?.maxRecordedDuration = maxDuration
videoOutput?.minFreeDiskSpaceLimit = 1024 * 1024 //SET MIN FREE SPACE IN BYTES FOR RECORDING TO CONTINUE ON A VOLUME
if session.canAddOutput(videoOutput) {
session.addOutput(videoOutput)
}
let videoLayer = AVCaptureVideoPreviewLayer(session: session)
videoLayer?.frame = self.previewViewContainer.bounds
videoLayer?.videoGravity = AVLayerVideoGravityResizeAspectFill
for device in AVCaptureDevice.devices(withMediaType: AVMediaTypeAudio) {
let device = device as? AVCaptureDevice
let audioInput = try! AVCaptureDeviceInput(device: device)
session.addInput(audioInput)
}
if session.canSetSessionPreset(AVCaptureSessionPreset640x480) {
session.sessionPreset = AVCaptureSessionPreset640x480
}
self.previewViewContainer.layer.addSublayer(videoLayer!)
session.startRunning()
}
// Focus View
self.focusView = UIView(frame: CGRect(x: 0, y: 0, width: 90, height: 90))
let tapRecognizer = UITapGestureRecognizer(target: self, action: #selector(FSVideoCameraView.focus(_:)))
self.previewViewContainer.addGestureRecognizer(tapRecognizer)
} catch {
}
let bundle = Bundle(for: self.classForCoder)
flashOnImage = fusumaFlashOnImage != nil ? fusumaFlashOnImage : UIImage(named: "ic_flash_on", in: bundle, compatibleWith: nil)
flashOffImage = fusumaFlashOffImage != nil ? fusumaFlashOffImage : UIImage(named: "ic_flash_off", in: bundle, compatibleWith: nil)
let flipImage = fusumaFlipImage != nil ? fusumaFlipImage : UIImage(named: "ic_loop", in: bundle, compatibleWith: nil)
videoStartImage = fusumaVideoStartImage != nil ? fusumaVideoStartImage : UIImage(named: "video_button", in: bundle, compatibleWith: nil)
videoStopImage = fusumaVideoStopImage != nil ? fusumaVideoStopImage : UIImage(named: "video_button_rec", in: bundle, compatibleWith: nil)
if(fusumaTintIcons) {
flashButton.tintColor = fusumaBaseTintColor
flipButton.tintColor = fusumaBaseTintColor
shotButton.tintColor = fusumaBaseTintColor
flashButton.setImage(flashOffImage?.withRenderingMode(.alwaysOriginal), for: UIControlState())
flipButton.setImage(flipImage?.withRenderingMode(.alwaysOriginal), for: UIControlState())
shotButton.setImage(videoStartImage?.withRenderingMode(.alwaysOriginal), for: UIControlState())
} else {
flashButton.setImage(flashOffImage, for: UIControlState())
flipButton.setImage(flipImage, for: UIControlState())
shotButton.setImage(videoStartImage, for: UIControlState())
}
flashConfiguration()
self.startCamera()
}
deinit {
NotificationCenter.default.removeObserver(self)
}
func startCamera() {
let status = AVCaptureDevice.authorizationStatus(forMediaType: AVMediaTypeVideo)
if status == AVAuthorizationStatus.authorized {
session?.startRunning()
} else if status == AVAuthorizationStatus.denied || status == AVAuthorizationStatus.restricted {
session?.stopRunning()
}
}
func stopCamera() {
if self.isRecording {
self.toggleRecording()
}
session?.stopRunning()
}
@IBAction func shotButtonPressed(_ sender: UIButton) {
self.toggleRecording()
}
fileprivate func toggleRecording() {
guard let videoOutput = videoOutput else {
return
}
self.isRecording = !self.isRecording
let shotImage: UIImage?
if self.isRecording {
shotImage = videoStopImage
} else {
shotImage = videoStartImage
}
self.shotButton.setImage(shotImage, for: UIControlState())
if self.isRecording {
let outputPath = "\(NSTemporaryDirectory())output.mov"
let outputURL = URL(fileURLWithPath: outputPath)
let fileManager = FileManager.default
if fileManager.fileExists(atPath: outputPath) {
do {
try fileManager.removeItem(atPath: outputPath)
} catch {
print("error removing item at path: \(outputPath)")
self.isRecording = false
return
}
}
self.flipButton.isEnabled = false
self.flashButton.isEnabled = false
videoOutput.startRecording(toOutputFileURL: outputURL, recordingDelegate: self)
} else {
videoOutput.stopRecording()
self.flipButton.isEnabled = true
self.flashButton.isEnabled = true
}
return
}
@IBAction func flipButtonPressed(_ sender: UIButton) {
session?.stopRunning()
do {
session?.beginConfiguration()
if let session = session {
for input in session.inputs {
session.removeInput(input as! AVCaptureInput)
}
let position = (videoInput?.device.position == AVCaptureDevicePosition.front) ? AVCaptureDevicePosition.back : AVCaptureDevicePosition.front
for device in AVCaptureDevice.devices(withMediaType: AVMediaTypeVideo) {
if let device = device as? AVCaptureDevice , device.position == position {
videoInput = try AVCaptureDeviceInput(device: device)
session.addInput(videoInput)
}
}
for device in AVCaptureDevice.devices(withMediaType: AVMediaTypeAudio) {
let device = device as? AVCaptureDevice
let audioInput = try! AVCaptureDeviceInput(device: device)
session.addInput(audioInput)
}
if session.canSetSessionPreset(AVCaptureSessionPreset640x480) {
session.sessionPreset = AVCaptureSessionPreset640x480
}
}
session?.commitConfiguration()
} catch {
}
session?.startRunning()
}
@IBAction func flashButtonPressed(_ sender: UIButton) {
do {
if let device = device {
guard device.hasFlash else { return }
try device.lockForConfiguration()
let mode = device.flashMode
if mode == AVCaptureFlashMode.off {
device.flashMode = AVCaptureFlashMode.on
flashButton.setImage(flashOnImage, for: UIControlState())
} else if mode == AVCaptureFlashMode.on {
device.flashMode = AVCaptureFlashMode.off
flashButton.setImage(flashOffImage, for: UIControlState())
}
device.unlockForConfiguration()
}
} catch _ {
flashButton.setImage(flashOffImage, for: UIControlState())
return
}
}
}
extension FSVideoCameraView: AVCaptureFileOutputRecordingDelegate {
func capture(_ captureOutput: AVCaptureFileOutput!, didStartRecordingToOutputFileAt fileURL: URL!, fromConnections connections: [Any]!) {
print("started recording to: \(fileURL)")
}
func capture(_ captureOutput: AVCaptureFileOutput!, didFinishRecordingToOutputFileAt outputFileURL: URL!, fromConnections connections: [Any]!, error: Error!) {
print("finished recording to: \(outputFileURL)")
self.delegate?.videoFinished(withFileURL: outputFileURL)
}
}
extension FSVideoCameraView {
func focus(_ recognizer: UITapGestureRecognizer) {
let point = recognizer.location(in: self)
let viewsize = self.bounds.size
let newPoint = CGPoint(x: point.y/viewsize.height, y: 1.0-point.x/viewsize.width)
let device = AVCaptureDevice.defaultDevice(withMediaType: AVMediaTypeVideo)
do {
try device?.lockForConfiguration()
} catch _ {
return
}
if device?.isFocusModeSupported(AVCaptureFocusMode.autoFocus) == true {
device?.focusMode = AVCaptureFocusMode.autoFocus
device?.focusPointOfInterest = newPoint
}
if device?.isExposureModeSupported(AVCaptureExposureMode.continuousAutoExposure) == true {
device?.exposureMode = AVCaptureExposureMode.continuousAutoExposure
device?.exposurePointOfInterest = newPoint
}
device?.unlockForConfiguration()
self.focusView?.alpha = 0.0
self.focusView?.center = point
self.focusView?.backgroundColor = UIColor.clear
self.focusView?.layer.borderColor = UIColor.white.cgColor
self.focusView?.layer.borderWidth = 1.0
self.focusView!.transform = CGAffineTransform(scaleX: 1.0, y: 1.0)
self.addSubview(self.focusView!)
UIView.animate(withDuration: 0.8, delay: 0.0, usingSpringWithDamping: 0.8,
initialSpringVelocity: 3.0, options: UIViewAnimationOptions.curveEaseIn, // UIViewAnimationOptions.BeginFromCurrentState
animations: {
self.focusView!.alpha = 1.0
self.focusView!.transform = CGAffineTransform(scaleX: 0.7, y: 0.7)
}, completion: {(finished) in
self.focusView!.transform = CGAffineTransform(scaleX: 1.0, y: 1.0)
self.focusView!.removeFromSuperview()
})
}
func flashConfiguration() {
do {
if let device = device {
guard device.hasFlash else { return }
try device.lockForConfiguration()
if device.isFlashModeSupported(AVCaptureFlashMode.off) {
device.flashMode = AVCaptureFlashMode.off
}
flashButton.setImage(flashOffImage, for: UIControlState())
device.unlockForConfiguration()
}
} catch _ {
return
}
}
}
| d7dd0fc9c7d04ea68e5c9d9ca75bd4d4 | 33.856061 | 163 | 0.555676 | false | false | false | false |
Shivol/Swift-CS333 | refs/heads/master | examples/extras/location/track-my-steps/track-my-steps/TrackManager.swift | mit | 3 | //
// TracksStore.swift
// track-my-steps
//
// Created by Илья Лошкарёв on 14.04.17.
// Copyright © 2017 Илья Лошкарёв. All rights reserved.
//
import Foundation
import CoreLocation
protocol TrackManagerDelegate: class {
func trackManager(_ trackManager: TrackManager, didStopTracking track: Track)
func trackManager(_ trackManager: TrackManager, didStartTracking track: Track)
func trackManager(_ trackManager: TrackManager, didFinishAuthorizationWithError error: Error)
func trackManager(_ trackManager: TrackManager, didFinishAuthorizationWithStatus status: CLAuthorizationStatus)
}
class TrackManager: NSObject, CLLocationManagerDelegate {
// static let shared = TrackManager()
let locationManager = CLLocationManager()
var tracks = [Track]()
var updateInterval: TimeInterval = 15
private(set) var isRunning: Bool = false
weak var delegate: TrackManagerDelegate?
override init() {
super.init()
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
}
func start() {
if let lastTrack = tracks.last,
lastTrack.endTime == nil {
lastTrack.endTime = Date()
}
let newTrack = Track()
tracks.append(newTrack)
locationManager.startUpdatingLocation()
locationManager.allowsBackgroundLocationUpdates = true
isRunning = true
delegate?.trackManager(self, didStartTracking: newTrack)
}
func stop() {
locationManager.stopUpdatingLocation()
isRunning = false
if let lastTrack = tracks.last {
lastTrack.endTime = Date()
delegate?.trackManager(self, didStopTracking: lastTrack)
}
}
func pause() {
locationManager.stopUpdatingLocation()
isRunning = false
}
func resume() {
locationManager.startUpdatingLocation()
locationManager.startMonitoringSignificantLocationChanges()
isRunning = true
}
var isAuthorized: Bool {
let status = CLLocationManager.authorizationStatus()
return status == .authorizedAlways || status == .authorizedWhenInUse
}
func authorize(with authorizationStatus: CLAuthorizationStatus){
switch authorizationStatus {
case .authorizedAlways:
locationManager.requestAlwaysAuthorization()
case .authorizedWhenInUse:
locationManager.requestWhenInUseAuthorization()
default:
break
delegate?.trackManager(self, didFinishAuthorizationWithError:
NSError(domain: "Authorization.InvalidStatus", code: 0, userInfo: [:]))
}
}
func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
delegate?.trackManager(self, didFinishAuthorizationWithStatus: status)
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
guard let track = tracks.last else {return}
for location in locations {
if location.timestamp > track.startTime
{
if let last = track.locations.last {
track.distance += location.distance(from: last)
}
track.locations.append(location)
}
}
}
func locationManager(_ manager: CLLocationManager, didFinishDeferredUpdatesWithError error: Error?) {
guard let error = error else { return }
print(error.localizedDescription)
}
}
| 1cd21ffd61feb95ae44fa77f1f2ca4d7 | 31.522124 | 115 | 0.651429 | false | false | false | false |
eBardX/XestiMonitors | refs/heads/master | Sources/Core/UIKit/Accessibility/AccessibilityAnnouncementMonitor.swift | mit | 1 | //
// AccessibilityAnnouncementMonitor.swift
// XestiMonitors
//
// Created by J. G. Pusey on 2017-01-16.
//
// © 2017 J. G. Pusey (see LICENSE.md)
//
#if os(iOS) || os(tvOS)
import Foundation
import UIKit
///
/// An `AccessibilityAnnouncementMonitor` instance monitors the system for
/// accessibility announcements that VoiceOver has finished outputting.
///
public class AccessibilityAnnouncementMonitor: BaseNotificationMonitor {
///
/// Encapsulates accessibility announcements that VoiceOver has
/// finished outputting.
///
public enum Event {
///
/// VoiceOver has finished outputting an accessibility
/// announcement.
///
case didFinish(Info)
}
///
/// Encapsulates information associated with an accessibility
/// announcement that VoiceOver has finished outputting.
///
public struct Info {
///
/// The text used for the announcement.
///
public let stringValue: String
///
/// Indicates whether VoiceOver successfully outputted the
/// announcement.
///
public let wasSuccessful: Bool
fileprivate init(_ notification: Notification) {
let userInfo = notification.userInfo
if let value = userInfo?[UIAccessibilityAnnouncementKeyStringValue] as? String {
self.stringValue = value
} else {
self.stringValue = " "
}
if let value = (userInfo?[UIAccessibilityAnnouncementKeyWasSuccessful] as? NSNumber)?.boolValue {
self.wasSuccessful = value
} else {
self.wasSuccessful = false
}
}
}
///
/// Initializes a new `AccessibilityAnnouncementMonitor`.
///
/// - Parameters:
/// - queue: The operation queue on which the handler executes.
/// By default, the main operation queue is used.
/// - handler: The handler to call when VoiceOver finishes
/// outputting an announcement.
///
public init(queue: OperationQueue = .main,
handler: @escaping (Event) -> Void) {
self.handler = handler
super.init(queue: queue)
}
private let handler: (Event) -> Void
override public func addNotificationObservers() {
super.addNotificationObservers()
observe(.UIAccessibilityAnnouncementDidFinish) { [unowned self] in
self.handler(.didFinish(Info($0)))
}
}
}
#endif
| 80b4cfd3424d97c31fc6f87913f91858 | 26.826087 | 109 | 0.598828 | false | false | false | false |
Subsets and Splits