repo_name
stringlengths 7
91
| path
stringlengths 8
658
| copies
stringclasses 125
values | size
stringlengths 3
6
| content
stringlengths 118
674k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6.09
99.2
| line_max
int64 17
995
| alpha_frac
float64 0.3
0.9
| ratio
float64 2
9.18
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
spritekitbook/flappybird-swift | Chapter 10/Finish/FloppyBird/FloppyBird/PauseButton.swift | 1 | 1931 | //
// PauseButton.swift
// FloppyBird
//
// Created by Jeremy Novak on 9/28/16.
// Copyright © 2016 SpriteKit Book. All rights reserved.
//
import SpriteKit
class PauseButton:SKSpriteNode {
// MARK: - Private class constants
private let pauseTexture = Textures.sharedInstance.textureWith(name: SpriteName.pauseButton)
private let resumeTexture = Textures.sharedInstance.textureWith(name: SpriteName.resumeButton)
// MARK: - Private class variables
private var gamePaused = false
// MARK: - Init
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override init(texture: SKTexture?, color: UIColor, size: CGSize) {
super.init(texture: texture, color: color, size: size)
}
convenience init() {
let texture = Textures.sharedInstance.textureWith(name: SpriteName.pauseButton)
self.init(texture: texture, color: SKColor.white, size: texture.size())
setup()
}
// MARK: - Setup
private func setup() {
// Put the anchorPoint in the top right corner of the sprite
self.anchorPoint = CGPoint(x: 1.0, y: 1.0)
// Position at top right corner of screen
self.position = CGPoint(x: kViewSize.width, y: kViewSize.height)
}
// MARK: - Actions
func tapped() {
// Flip the value of gamePaused
gamePaused = !gamePaused
// Which texture should we use?
self.texture = gamePaused ? resumeTexture : pauseTexture
// Play the button clip
self.run(Sound.sharedInstance.playSound(sound: .pop))
// Pause or resume background music.
if gamePaused {
Sound.sharedInstance.pauseMusic()
} else {
Sound.sharedInstance.resumeMusic()
}
}
func getPauseState() -> Bool {
return gamePaused
}
}
| apache-2.0 | 6d90ecb13c49f5ff801a330d6c2cee3c | 27.382353 | 98 | 0.615026 | 4.457275 | false | false | false | false |
Jugale/TVPickerView | TVPickerView/TVPickerView.swift | 1 | 13151 | //
// TVPickerView.swift
// TVPickerView
//
// Created by Max Chuquimia on 21/10/2015.
// Copyright © 2015 Chuquimian Productions. All rights reserved.
//
import UIKit
import QuartzCore
//MARK: TVPickerView Class
@objc open class TVPickerView: UIView, TVPickerInterface {
weak open var focusDelegate: TVPickerViewFocusDelegate?
weak open var dataSource: TVPickerViewDataSource?
weak open var delegate: TVPickerViewDelegate?
static fileprivate let AnimationInterval: TimeInterval = 0.1
static fileprivate let SwipeMultiplier: CGFloat = 0.5
static fileprivate let MaxDrawn = 4
fileprivate let mover = TVPickerMover()
fileprivate let contentView = UIView()
fileprivate let visualEffectView = UIVisualEffectView(effect: UIBlurEffect(style: .dark))
override public init(frame: CGRect) {
super.init(frame: frame)
setup()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup()
}
fileprivate(set) open var deepFocus = false {
didSet {
UIView.animate(withDuration: TVPickerView.AnimationInterval, animations: deepFocus ? bringIntoDeepFocus : bringOutOfDeepFocus)
if deepFocus {
becomeFirstResponder()
}
else {
resignFirstResponder()
}
}
}
fileprivate var currentIndex: Int = 0 {
didSet {
if currentIndex != oldValue {
delegate?.pickerView(self, didChangeToIndex: currentIndex)
}
}
}
open var selectedIndex: Int {
return currentIndex
}
fileprivate var itemCount: Int = 0
fileprivate var indexesAndViews = [Int: UIView]()
open func reloadData() {
guard let dataSource = dataSource else {
return
}
layoutMargins = UIEdgeInsets.zero
itemCount = dataSource.numberOfViewsInPickerView(self)
loadFromIndex(0)
if currentIndex < itemCount - 1 {
scrollToIndex(currentIndex, animated: false)
}
else {
scrollToIndex(0, animated: false)
}
}
fileprivate func loadFromIndex(_ index: Int) {
guard let dataSource = dataSource else {
return
}
indexesAndViews.values.forEach({$0.removeFromSuperview()})
indexesAndViews.removeAll()
var nIndex = index + 1
if nIndex == itemCount {
nIndex = itemCount - 1
}
if nIndex >= (itemCount - TVPickerView.MaxDrawn) {
nIndex = nIndex - TVPickerView.MaxDrawn
}
if nIndex < 0 {
nIndex = 0
}
for idx in nIndex..<min(TVPickerView.MaxDrawn + nIndex, itemCount) {
let v = dataSource.pickerView(self, viewForIndex: idx, reusingView: nil)
contentView.addSubview(v.setupForPicker(self))
indexesAndViews[idx] = v
v.setX(xPositionForIndex(idx), 1)
}
iterate(0)
scrollToNearestIndex(0.0)
//Waiting fixes everything
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + Double(Int64(0.1 * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC)) {
self.internalScrollToIndex(index, animated: true, multiplier: 2.0, speed: 0.1)
}
}
}
extension TVPickerView {
fileprivate func setup() {
visualEffectView.sizeToView(self)
visualEffectView.clipsToBounds = true
addSubview(visualEffectView)
contentView.sizeToView(self)
contentView.backgroundColor = .clear
addSubview(contentView)
backgroundColor = .clear
layer.shadowColor = UIColor.black.cgColor
layer.shadowOffset = CGSize(width: 0, height: 10)
layer.cornerRadius = 7.0
contentView.clipsToBounds = true
contentView.layer.cornerRadius = 7.0
visualEffectView.layer.cornerRadius = 7.0
bringOutOfFocus()
}
}
//MARK: Focus Control
extension TVPickerView {
override open func didUpdateFocus(in context: UIFocusUpdateContext, with coordinator: UIFocusAnimationCoordinator) {
super.didUpdateFocus(in: context, with: coordinator)
if context.nextFocusedView == self {
UIView.animate(withDuration: TVPickerView.AnimationInterval, animations: bringIntoFocus)
}
else if context.previouslyFocusedView == self {
UIView.animate(withDuration: TVPickerView.AnimationInterval, animations: bringOutOfFocus)
}
}
override open func shouldUpdateFocus(in context: UIFocusUpdateContext) -> Bool {
return !deepFocus
}
fileprivate func bringIntoFocus() {
layer.transform = CATransform3DMakeScale(1.2, 1.2, 1.0)
layer.shadowRadius = 7.0
layer.shadowOpacity = 0.2
contentView.backgroundColor = UIColor(white: 1.0, alpha: 0.7)
}
fileprivate func bringOutOfFocus() {
layer.transform = CATransform3DMakeScale(1.0, 1.0, 1.0)
layer.shadowRadius = 0.0
layer.shadowOpacity = 0.0
contentView.backgroundColor = .clear
}
fileprivate func bringIntoDeepFocus() {
layer.transform = CATransform3DMakeScale(1.4, 1.4, 1.0)
layer.shadowRadius = 15.0
layer.shadowOpacity = 0.7
contentView.backgroundColor = .white
focusDelegate?.pickerView(self, deepFocusStateChanged: true)
}
fileprivate func bringOutOfDeepFocus() {
bringIntoFocus()
focusDelegate?.pickerView(self, deepFocusStateChanged: false)
}
override open var canBecomeFocused : Bool {
return true
}
override open var canBecomeFirstResponder : Bool {
return true
}
}
//MARK: Touch Control
extension TVPickerView: UIGestureRecognizerDelegate {
override open func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesBegan(touches, with: event)
if !deepFocus {
return
}
mover.stopGenerating()
}
override open func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesMoved(touches, with: event)
if !deepFocus {
return
}
guard let touch = touches.first else {
return
}
let lastLocation = touch.previousLocation(in: self)
let thisLocation = touch.location(in: self)
let dx = thisLocation.x - lastLocation.x
iterate(dx)
}
override open func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesEnded(touches, with: event)
if !deepFocus {
return
}
scrollToNearestIndex(0.3)
}
override open func pressesBegan(_ presses: Set<UIPress>, with event: UIPressesEvent?) {
super.pressesBegan(presses, with: event)
guard let press = presses.first else {
return
}
if press.type == .select {
let changedValue = !deepFocus
if !changedValue {
scrollToNearestIndex(0.3, uncancellable: true)
}
deepFocus = changedValue
}
if !deepFocus {
return
}
switch press.type {
case .upArrow, .rightArrow:
iterateForwards()
case .downArrow, .leftArrow:
iterateBackwards()
default:
break
}
}
}
//MARK: Iteration
extension TVPickerView {
func iterate(_ dx: CGFloat) {
for (_, v) in indexesAndViews {
let newViewX = dx * TVPickerView.SwipeMultiplier + CGFloat(v.center.x)
let containerCenter = CGPoint(x: bounds.width / 2.0, y: bounds.height / 2.0)
let vdx = min(fabs(containerCenter.x - newViewX) / containerCenter.x, 1.0)
v.setX(newViewX, vdx)
}
calculate()
}
func iterateForwards() {
if currentIndex >= (itemCount - 1) {
return
}
internalScrollToIndex(currentIndex + 1, animated: true, multiplier: 1.0, speed: 0.1)
}
func iterateBackwards() {
if currentIndex == 0 {
return
}
internalScrollToIndex(currentIndex - 1, animated: true, multiplier: 1.0, speed: 0.1)
}
fileprivate func scrollToNearestIndex(_ speed: TimeInterval, uncancellable: Bool = false) {
let (locatedIndex, offset) = nearestViewToCenter()
if uncancellable {
self.currentIndex = locatedIndex
}
mover.startGenerating(time: speed, totalDistance: offset * 2.0, call: iterate, completed: {
//Don't want to tell the delegate until now because the user could cancel the animation
self.currentIndex = locatedIndex
})
}
fileprivate func nearestViewToCenter() -> (index: Int, distance: CGFloat) {
let targetX = bounds.width / 2.0
var locatedIndex = 0
var smallestDistance = CGFloat.greatestFiniteMagnitude
var offset: CGFloat = 0.0
for (idx, v) in indexesAndViews {
let x = v.center.x
let dx = fabs(targetX - x)
if dx < smallestDistance {
locatedIndex = idx
smallestDistance = dx
offset = targetX - x
}
if smallestDistance < v.frame.width / 2.0 {
//No need to continue searching at this point
break
}
}
return (locatedIndex, offset)
}
public func scrollToIndex(_ idx: Int) {
scrollToIndex(idx, animated: true)
}
//TODO: animated doesn't work. Fix it and make it public
fileprivate func scrollToIndex(_ idx: Int, animated: Bool) {
let di = abs(idx - currentIndex)
var a = animated
if di > 5 {
a = false
}
internalScrollToIndex(idx, animated: a, multiplier: 2.0, speed: 0.2)
}
fileprivate func internalScrollToIndex(_ idx: Int, animated: Bool, multiplier: CGFloat, speed: TimeInterval) {
if !animated {
loadFromIndex(idx)
return
}
let x = xPositionForIndex(idx)
let distance = xPositionForIndex(currentIndex) - x
let s = animated ? speed : 0.0
mover.startGenerating(time: s, totalDistance: distance * multiplier, call: iterate, completed: {
self.scrollToNearestIndex(s)
})
}
fileprivate func xPositionForIndex(_ idx: Int) -> CGFloat {
return ((CGFloat(idx) * frame.width) / CGFloat(2.0)) + frame.width / 2.0
}
}
//MARK: - Lazy
extension TVPickerView {
fileprivate func calculate() {
guard let dataSource = dataSource else {
return
}
let indexesDrawn: [Int] = indexesAndViews.keys.map {$0}.sorted(by: <)
if indexesDrawn.count < TVPickerView.MaxDrawn {
//No laziness here!
return
}
let (locatedIndex, _) = nearestViewToCenter()
if locatedIndex == 0 || locatedIndex == (itemCount - 1) {
//TODO: maybe add looping? Nah.
return
}
guard let n = indexesDrawn.index(of: locatedIndex) else {
return
}
//Add / Reuse a view if required
var newIdx: Int?
var reuseIndex = 0
var xPosition: CGFloat = 0.0
let locatedView = indexesAndViews[locatedIndex]!
if n == 0 {
newIdx = locatedIndex - 1
reuseIndex = indexesDrawn[TVPickerView.MaxDrawn - 1]
xPosition = locatedView.center.x - locatedView.bounds.width
}
else if n == (TVPickerView.MaxDrawn - 1) {
newIdx = locatedIndex + 1
reuseIndex = indexesDrawn[0]
xPosition = locatedView.center.x + locatedView.bounds.width
}
guard let newIndex = newIdx else {
return
}
let reusingView = indexesAndViews[reuseIndex]
indexesAndViews.removeValue(forKey: reuseIndex)
let newView = dataSource.pickerView(self, viewForIndex: newIndex, reusingView: reusingView)
indexesAndViews[newIndex] = newView
if newView !== reusingView {
reusingView?.removeFromSuperview()
contentView.addSubview(newView.setupForPicker(self))
}
newView.setX(xPosition, 1.0)
}
}
| mit | d49ed0309673790331e1eccf5baad399 | 27.649237 | 138 | 0.568897 | 4.904886 | false | false | false | false |
redeyeapps/JSON | Sources/JSON/JSONOptionalExtensions.swift | 2 | 3132 |
/// WARNING: Internal type. Used to constrain an extension on Optional to be sudo non Generic.
public protocol _JSON {}
extension JSON: _JSON {}
// Would be best if we could constrain extensions to be Non-Generic. Swift3?
// TODO: Test setters ensure behaviour is predictable and expected when operating on nested JSON
// TODO: Check if it is viable to use JSONRepresentable as the contraint and be rid of _JSON
extension Optional where Wrapped: _JSON {
/// returns the `JSON` value for key iff `Wrapped == JSON.object(_)` and there is a value for the key
/// - Note: you will get better performance if you chain your subscript eg. ["key"]?.string This is because the compiler will retain more type information.
public subscript(key: String) -> JSON? {
get {
return object?[key]
}
set {
guard var json = self as? JSON else { return }
guard case .object(_) = json else { return }
json[key] = newValue
self = json as? Wrapped
}
}
/// returns the JSON value at index iff `Wrapped == JSON.array(_)` and the index is within the arrays bounds
public subscript(index: Int) -> JSON? {
get {
guard let `self` = self as? JSON else { return nil }
guard case .array(let a) = self, a.indices ~= index else { return nil }
return a[index]
}
set {
guard var a = (self as? JSON)?.array else { return }
switch newValue {
case .none: a.remove(at: index)
case .some(let value):
a[index] = value
self = (JSON.array(a) as? Wrapped)
}
}
}
}
// MARK: - Standard typed accessors
extension Optional where Wrapped: _JSON {
/// Returns an array of `JSON` iff `Wrapped == JSON.array(_)`
public var array: [JSON]? {
guard let `self` = self as? JSON else { return nil }
return self.array
}
/// Returns a `JSON` object iff `Wrapped == JSON.object(_)`
public var object: [String: JSON]? {
guard let `self` = self as? JSON else { return nil }
return self.object
}
/// Returns a `String` iff `Wrapped == JSON.string(_)`
public var string: String? {
guard let `self` = self as? JSON else { return nil }
return self.string
}
/// Returns this enum's associated `Int64` iff `self == .integer(_)`, `nil` otherwise.
public var int64: Int64? {
guard let `self` = self as? JSON else { return nil }
return self.int64
}
/// Returns a `Bool` iff `Wrapped == JSON.bool(_)`
public var bool: Bool? {
guard let `self` = self as? JSON else { return nil }
return self.bool
}
/// Returns a `Double` iff `Wrapped == JSON.double(_)`
public var double: Double? {
guard let `self` = self as? JSON else { return nil }
return self.double
}
}
// MARK: Non RFC JSON types
extension Optional where Wrapped: _JSON {
/// Returns an `Int` iff `Wrapped == JSON.integer(_)`
public var int: Int? {
guard let `self` = self as? JSON else { return nil }
return self.int
}
/// Returns an `Float` iff `Wrapped == JSON.double(_)`
public var float: Float? {
guard let `self` = self as? JSON else { return nil }
return self.float
}
}
| mit | 62a1b923578b647111586ddf641afb65 | 28.54717 | 157 | 0.62963 | 3.787183 | false | false | false | false |
qimuyunduan/ido_ios | ido_ios/ConsumeTableViewController.swift | 1 | 3248 | //
// ConsumeTableViewController.swift
// ido_ios
//
// Created by qimuyunduan on 16/6/3.
// Copyright © 2016年 qimuyunduan. All rights reserved.
//
import UIKit
import Alamofire
import MJRefresh
class ConsumeTableViewController: UITableViewController {
private var data:[AnyObject] = [AnyObject](){
didSet{
tableView.reloadData()
}
}
private var time = 3
private var timer:NSTimer?
private var footerRefresh:MJRefreshBackNormalFooter?
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
getData()
}
override func viewDidLoad() {
super.viewDidLoad()
footerRefresh = MJRefreshBackNormalFooter(refreshingTarget: self, refreshingAction: #selector(ConsumeTableViewController.refresh))
footerRefresh!.setTitle("下拉刷新", forState: MJRefreshState.Idle)
footerRefresh!.setTitle("正在刷新", forState: MJRefreshState.Refreshing)
footerRefresh!.setTitle("松开即可刷新", forState: MJRefreshState.Pulling)
self.tableView.mj_footer = footerRefresh
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("consumeCell") as! ConsTableViewCell
let cellData = data[indexPath.row] as! Dictionary<String,String>
cell.orderImage.image = UIImage(named: "onlineDrugStore")
cell.orderTime.text = cellData["orderTime"]
cell.orderMoney.text = cellData["orderMoney"]
cell.orderTitle.text = cellData["orderTitle"]
cell.orderState.text = cellData["orderState"]
return cell
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return data.count
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
print("你选中的某某单元格....")
}
func refresh() -> Void {
timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: #selector(ConsumeTableViewController.timerAction), userInfo: nil, repeats: true)
}
func getData() -> Void {
let url = HOST + "consumeOrder"
Alamofire.request(.GET, url).validate().responseJSON { response in
switch response.result {
case .Success:
if let value = response.result.value {
self.data = value as! [AnyObject]
print(self.data)
}
case .Failure(let error):
print(error)
}
}
}
func timerAction() -> Void {
time -= 1
if time == 0 {
getData()
if let mytimer = timer {
mytimer.invalidate()
}
footerRefresh?.endRefreshing()
time = 3
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
| mit | 17122eb01f9ad7b034b2b5c4a18835db | 30.362745 | 162 | 0.615817 | 5.093949 | false | false | false | false |
bradhowes/SynthInC | SynthInC/VolumeBarView.swift | 1 | 1452 | // VolumeBarView.swift
// SynthInC
//
// Created by Brad Howes on 6/12/16.
// Copyright © 2016 Brad Howes. All rights reserved.
import UIKit
/// Custom UIView for showing Instrument volume and pan setting
final class VolumeBarView: UIView {
var volume: Float = 0.0
var pan: Float = 0.0
var muted: Bool = false
/**
Drawing routine to show the volume and pan settings.
- parameter rect: area to update
*/
override func draw(_ rect: CGRect) {
guard let cgc = UIGraphicsGetCurrentContext() else { return }
// Fill the entire view
//
cgc.setFillColor(red: 1.0, green: 1.0, blue: 1.0, alpha: 0.20)
cgc.fill(bounds)
// Set the volume color depending on mute status
//
if muted {
cgc.setFillColor(red: 0.8, green: 0, blue: 0, alpha: 0.80)
}
else {
cgc.setFillColor(red: 0.2, green: 0.8, blue: 0.2, alpha: 0.80)
}
// Draw the bar for volume
let w = bounds.width
let rect = CGRect(x: bounds.minX, y: bounds.minY, width: w * CGFloat(volume), height: bounds.height)
cgc.fill(rect)
// Draw a small indicator for the pan
//
let px = bounds.minX + w * CGFloat((pan + 1.0) / 2.0)
cgc.setFillColor(red: 1, green: 1, blue: 1, alpha: 0.90)
cgc.fill(CGRect(x: px - 2, y: bounds.minY, width: 4, height: bounds.height))
}
}
| mit | 9def51263d995564d07c39ab80f02ff7 | 28.612245 | 108 | 0.574776 | 3.573892 | false | false | false | false |
rb-de0/tech.reb-dev.com | Sources/App/Controllers/SubContentEditController.swift | 2 | 1788 |
final class SubContentEditController: ResourceRepresentable {
private let view: ViewRenderer
init(view: ViewRenderer) {
self.view = view
}
func makeResource() -> Resource<Subcontent>{
return Resource(
index: index,
show: show
)
}
func index(request: Request) throws -> ResponseRepresentable {
return try view.makeWithBase(request: request, path: "subcontent-edit")
}
func store(request: Request) throws -> ResponseRepresentable {
let subContent = try request.parameters.next(Subcontent.self)
do{
try subContent.update(for: request)
try subContent.validate()
try subContent.save()
return Response(redirect: "/subcontents/edit/\(subContent.name)?message=\(SuccessMessage.subContentUpdate)")
} catch {
let context: NodeRepresentable = [
"name": subContent.name,
"content": subContent.content,
"error_message": error.localizedDescription
]
return try view.makeWithBase(request: request, path: "subcontent-update", context: context)
}
}
func show(request: Request, subContent: Subcontent) throws -> ResponseRepresentable {
return try view.makeWithBase(request: request, path: "subcontent-update", context: subContent.makeJSON())
}
func delete(request: Request) throws -> ResponseRepresentable {
let subContent = try request.parameters.next(Subcontent.self)
try subContent.delete()
return Response(redirect: "/subcontents/edit")
}
}
| mit | 54c4aaebbcdfc0be22fc73b0089cdd71 | 28.8 | 120 | 0.581096 | 5.22807 | false | false | false | false |
shahmishal/swift | stdlib/public/core/ContiguousArrayBuffer.swift | 1 | 23216 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import SwiftShims
/// Class used whose sole instance is used as storage for empty
/// arrays. The instance is defined in the runtime and statically
/// initialized. See stdlib/runtime/GlobalObjects.cpp for details.
/// Because it's statically referenced, it requires non-lazy realization
/// by the Objective-C runtime.
///
/// NOTE: older runtimes called this _EmptyArrayStorage. The two must
/// coexist, so it was renamed. The old name must not be used in the new
/// runtime.
@_fixed_layout
@usableFromInline
@_objc_non_lazy_realization
internal final class __EmptyArrayStorage
: __ContiguousArrayStorageBase {
@inlinable
@nonobjc
internal init(_doNotCallMe: ()) {
_internalInvariantFailure("creating instance of __EmptyArrayStorage")
}
#if _runtime(_ObjC)
override internal func _withVerbatimBridgedUnsafeBuffer<R>(
_ body: (UnsafeBufferPointer<AnyObject>) throws -> R
) rethrows -> R? {
return try body(UnsafeBufferPointer(start: nil, count: 0))
}
override internal func _getNonVerbatimBridgingBuffer() -> _BridgingBuffer {
return _BridgingBuffer(0)
}
#endif
@inlinable
override internal func canStoreElements(ofDynamicType _: Any.Type) -> Bool {
return false
}
/// A type that every element in the array is.
@inlinable
override internal var staticElementType: Any.Type {
return Void.self
}
}
/// The empty array prototype. We use the same object for all empty
/// `[Native]Array<Element>`s.
@inlinable
internal var _emptyArrayStorage: __EmptyArrayStorage {
return Builtin.bridgeFromRawPointer(
Builtin.addressof(&_swiftEmptyArrayStorage))
}
// The class that implements the storage for a ContiguousArray<Element>
@_fixed_layout
@usableFromInline
internal final class _ContiguousArrayStorage<
Element
>: __ContiguousArrayStorageBase {
@inlinable
deinit {
_elementPointer.deinitialize(count: countAndCapacity.count)
_fixLifetime(self)
}
#if _runtime(_ObjC)
/// If the `Element` is bridged verbatim, invoke `body` on an
/// `UnsafeBufferPointer` to the elements and return the result.
/// Otherwise, return `nil`.
internal final override func _withVerbatimBridgedUnsafeBuffer<R>(
_ body: (UnsafeBufferPointer<AnyObject>) throws -> R
) rethrows -> R? {
var result: R?
try self._withVerbatimBridgedUnsafeBufferImpl {
result = try body($0)
}
return result
}
/// If `Element` is bridged verbatim, invoke `body` on an
/// `UnsafeBufferPointer` to the elements.
internal final func _withVerbatimBridgedUnsafeBufferImpl(
_ body: (UnsafeBufferPointer<AnyObject>) throws -> Void
) rethrows {
if _isBridgedVerbatimToObjectiveC(Element.self) {
let count = countAndCapacity.count
let elements = UnsafeRawPointer(_elementPointer)
.assumingMemoryBound(to: AnyObject.self)
defer { _fixLifetime(self) }
try body(UnsafeBufferPointer(start: elements, count: count))
}
}
/// Bridge array elements and return a new buffer that owns them.
///
/// - Precondition: `Element` is bridged non-verbatim.
override internal func _getNonVerbatimBridgingBuffer() -> _BridgingBuffer {
_internalInvariant(
!_isBridgedVerbatimToObjectiveC(Element.self),
"Verbatim bridging should be handled separately")
let count = countAndCapacity.count
let result = _BridgingBuffer(count)
let resultPtr = result.baseAddress
let p = _elementPointer
for i in 0..<count {
(resultPtr + i).initialize(to: _bridgeAnythingToObjectiveC(p[i]))
}
_fixLifetime(self)
return result
}
#endif
/// Returns `true` if the `proposedElementType` is `Element` or a subclass of
/// `Element`. We can't store anything else without violating type
/// safety; for example, the destructor has static knowledge that
/// all of the elements can be destroyed as `Element`.
@inlinable
internal override func canStoreElements(
ofDynamicType proposedElementType: Any.Type
) -> Bool {
#if _runtime(_ObjC)
return proposedElementType is Element.Type
#else
// FIXME: Dynamic casts don't currently work without objc.
// rdar://problem/18801510
return false
#endif
}
/// A type that every element in the array is.
@inlinable
internal override var staticElementType: Any.Type {
return Element.self
}
@inlinable
internal final var _elementPointer: UnsafeMutablePointer<Element> {
return UnsafeMutablePointer(Builtin.projectTailElems(self, Element.self))
}
}
@usableFromInline
@frozen
internal struct _ContiguousArrayBuffer<Element>: _ArrayBufferProtocol {
/// Make a buffer with uninitialized elements. After using this
/// method, you must either initialize the `count` elements at the
/// result's `.firstElementAddress` or set the result's `.count`
/// to zero.
@inlinable
internal init(
_uninitializedCount uninitializedCount: Int,
minimumCapacity: Int
) {
let realMinimumCapacity = Swift.max(uninitializedCount, minimumCapacity)
if realMinimumCapacity == 0 {
self = _ContiguousArrayBuffer<Element>()
}
else {
_storage = Builtin.allocWithTailElems_1(
_ContiguousArrayStorage<Element>.self,
realMinimumCapacity._builtinWordValue, Element.self)
let storageAddr = UnsafeMutableRawPointer(Builtin.bridgeToRawPointer(_storage))
let endAddr = storageAddr + _swift_stdlib_malloc_size(storageAddr)
let realCapacity = endAddr.assumingMemoryBound(to: Element.self) - firstElementAddress
_initStorageHeader(
count: uninitializedCount, capacity: realCapacity)
}
}
/// Initialize using the given uninitialized `storage`.
/// The storage is assumed to be uninitialized. The returned buffer has the
/// body part of the storage initialized, but not the elements.
///
/// - Warning: The result has uninitialized elements.
///
/// - Warning: storage may have been stack-allocated, so it's
/// crucial not to call, e.g., `malloc_size` on it.
@inlinable
internal init(count: Int, storage: _ContiguousArrayStorage<Element>) {
_storage = storage
_initStorageHeader(count: count, capacity: count)
}
@inlinable
internal init(_ storage: __ContiguousArrayStorageBase) {
_storage = storage
}
/// Initialize the body part of our storage.
///
/// - Warning: does not initialize elements
@inlinable
internal func _initStorageHeader(count: Int, capacity: Int) {
#if _runtime(_ObjC)
let verbatim = _isBridgedVerbatimToObjectiveC(Element.self)
#else
let verbatim = false
#endif
// We can initialize by assignment because _ArrayBody is a trivial type,
// i.e. contains no references.
_storage.countAndCapacity = _ArrayBody(
count: count,
capacity: capacity,
elementTypeIsBridgedVerbatim: verbatim)
}
/// True, if the array is native and does not need a deferred type check.
@inlinable
internal var arrayPropertyIsNativeTypeChecked: Bool {
return true
}
/// A pointer to the first element.
@inlinable
internal var firstElementAddress: UnsafeMutablePointer<Element> {
return UnsafeMutablePointer(Builtin.projectTailElems(_storage,
Element.self))
}
@inlinable
internal var firstElementAddressIfContiguous: UnsafeMutablePointer<Element>? {
return firstElementAddress
}
/// Call `body(p)`, where `p` is an `UnsafeBufferPointer` over the
/// underlying contiguous storage.
@inlinable
internal func withUnsafeBufferPointer<R>(
_ body: (UnsafeBufferPointer<Element>) throws -> R
) rethrows -> R {
defer { _fixLifetime(self) }
return try body(UnsafeBufferPointer(start: firstElementAddress,
count: count))
}
/// Call `body(p)`, where `p` is an `UnsafeMutableBufferPointer`
/// over the underlying contiguous storage.
@inlinable
internal mutating func withUnsafeMutableBufferPointer<R>(
_ body: (UnsafeMutableBufferPointer<Element>) throws -> R
) rethrows -> R {
defer { _fixLifetime(self) }
return try body(
UnsafeMutableBufferPointer(start: firstElementAddress, count: count))
}
//===--- _ArrayBufferProtocol conformance -----------------------------------===//
/// Create an empty buffer.
@inlinable
internal init() {
_storage = _emptyArrayStorage
}
@inlinable
internal init(_buffer buffer: _ContiguousArrayBuffer, shiftedToStartIndex: Int) {
_internalInvariant(shiftedToStartIndex == 0, "shiftedToStartIndex must be 0")
self = buffer
}
@inlinable
internal mutating func requestUniqueMutableBackingBuffer(
minimumCapacity: Int
) -> _ContiguousArrayBuffer<Element>? {
if _fastPath(isUniquelyReferenced() && capacity >= minimumCapacity) {
return self
}
return nil
}
@inlinable
internal mutating func isMutableAndUniquelyReferenced() -> Bool {
return isUniquelyReferenced()
}
/// If this buffer is backed by a `_ContiguousArrayBuffer`
/// containing the same number of elements as `self`, return it.
/// Otherwise, return `nil`.
@inlinable
internal func requestNativeBuffer() -> _ContiguousArrayBuffer<Element>? {
return self
}
@inlinable
@inline(__always)
internal func getElement(_ i: Int) -> Element {
_internalInvariant(i >= 0 && i < count, "Array index out of range")
return firstElementAddress[i]
}
/// Get or set the value of the ith element.
@inlinable
internal subscript(i: Int) -> Element {
@inline(__always)
get {
return getElement(i)
}
@inline(__always)
nonmutating set {
_internalInvariant(i >= 0 && i < count, "Array index out of range")
// FIXME: Manually swap because it makes the ARC optimizer happy. See
// <rdar://problem/16831852> check retain/release order
// firstElementAddress[i] = newValue
var nv = newValue
let tmp = nv
nv = firstElementAddress[i]
firstElementAddress[i] = tmp
}
}
/// The number of elements the buffer stores.
@inlinable
internal var count: Int {
get {
return _storage.countAndCapacity.count
}
nonmutating set {
_internalInvariant(newValue >= 0)
_internalInvariant(
newValue <= capacity,
"Can't grow an array buffer past its capacity")
_storage.countAndCapacity.count = newValue
}
}
/// Traps unless the given `index` is valid for subscripting, i.e.
/// `0 ≤ index < count`.
@inlinable
@inline(__always)
internal func _checkValidSubscript(_ index: Int) {
_precondition(
(index >= 0) && (index < count),
"Index out of range"
)
}
/// The number of elements the buffer can store without reallocation.
@inlinable
internal var capacity: Int {
return _storage.countAndCapacity.capacity
}
/// Copy the elements in `bounds` from this buffer into uninitialized
/// memory starting at `target`. Return a pointer "past the end" of the
/// just-initialized memory.
@inlinable
@discardableResult
internal __consuming func _copyContents(
subRange bounds: Range<Int>,
initializing target: UnsafeMutablePointer<Element>
) -> UnsafeMutablePointer<Element> {
_internalInvariant(bounds.lowerBound >= 0)
_internalInvariant(bounds.upperBound >= bounds.lowerBound)
_internalInvariant(bounds.upperBound <= count)
let initializedCount = bounds.upperBound - bounds.lowerBound
target.initialize(
from: firstElementAddress + bounds.lowerBound, count: initializedCount)
_fixLifetime(owner)
return target + initializedCount
}
public __consuming func _copyContents(
initializing buffer: UnsafeMutableBufferPointer<Element>
) -> (Iterator,UnsafeMutableBufferPointer<Element>.Index) {
// This customization point is not implemented for internal types.
// Accidentally calling it would be a catastrophic performance bug.
fatalError("unsupported")
}
/// Returns a `_SliceBuffer` containing the given `bounds` of values
/// from this buffer.
@inlinable
internal subscript(bounds: Range<Int>) -> _SliceBuffer<Element> {
get {
return _SliceBuffer(
owner: _storage,
subscriptBaseAddress: subscriptBaseAddress,
indices: bounds,
hasNativeBuffer: true)
}
set {
fatalError("not implemented")
}
}
/// Returns `true` iff this buffer's storage is uniquely-referenced.
///
/// - Note: This does not mean the buffer is mutable. Other factors
/// may need to be considered, such as whether the buffer could be
/// some immutable Cocoa container.
@inlinable
internal mutating func isUniquelyReferenced() -> Bool {
return _isUnique(&_storage)
}
#if _runtime(_ObjC)
/// Convert to an NSArray.
///
/// - Precondition: `Element` is bridged to Objective-C.
///
/// - Complexity: O(1).
@inlinable
internal __consuming func _asCocoaArray() -> AnyObject {
if count == 0 {
return _emptyArrayStorage
}
if _isBridgedVerbatimToObjectiveC(Element.self) {
return _storage
}
return __SwiftDeferredNSArray(_nativeStorage: _storage)
}
#endif
/// An object that keeps the elements stored in this buffer alive.
@inlinable
internal var owner: AnyObject {
return _storage
}
/// An object that keeps the elements stored in this buffer alive.
@inlinable
internal var nativeOwner: AnyObject {
return _storage
}
/// A value that identifies the storage used by the buffer.
///
/// Two buffers address the same elements when they have the same
/// identity and count.
@inlinable
internal var identity: UnsafeRawPointer {
return UnsafeRawPointer(firstElementAddress)
}
/// Returns `true` iff we have storage for elements of the given
/// `proposedElementType`. If not, we'll be treated as immutable.
@inlinable
func canStoreElements(ofDynamicType proposedElementType: Any.Type) -> Bool {
return _storage.canStoreElements(ofDynamicType: proposedElementType)
}
/// Returns `true` if the buffer stores only elements of type `U`.
///
/// - Precondition: `U` is a class or `@objc` existential.
///
/// - Complexity: O(*n*)
@inlinable
internal func storesOnlyElementsOfType<U>(
_: U.Type
) -> Bool {
_internalInvariant(_isClassOrObjCExistential(U.self))
if _fastPath(_storage.staticElementType is U.Type) {
// Done in O(1)
return true
}
// Check the elements
for x in self {
if !(x is U) {
return false
}
}
return true
}
@usableFromInline
internal var _storage: __ContiguousArrayStorageBase
}
/// Append the elements of `rhs` to `lhs`.
@inlinable
internal func += <Element, C: Collection>(
lhs: inout _ContiguousArrayBuffer<Element>, rhs: __owned C
) where C.Element == Element {
let oldCount = lhs.count
let newCount = oldCount + numericCast(rhs.count)
let buf: UnsafeMutableBufferPointer<Element>
if _fastPath(newCount <= lhs.capacity) {
buf = UnsafeMutableBufferPointer(start: lhs.firstElementAddress + oldCount, count: numericCast(rhs.count))
lhs.count = newCount
}
else {
var newLHS = _ContiguousArrayBuffer<Element>(
_uninitializedCount: newCount,
minimumCapacity: _growArrayCapacity(lhs.capacity))
newLHS.firstElementAddress.moveInitialize(
from: lhs.firstElementAddress, count: oldCount)
lhs.count = 0
(lhs, newLHS) = (newLHS, lhs)
buf = UnsafeMutableBufferPointer(start: lhs.firstElementAddress + oldCount, count: numericCast(rhs.count))
}
var (remainders,writtenUpTo) = buf.initialize(from: rhs)
// ensure that exactly rhs.count elements were written
_precondition(remainders.next() == nil, "rhs underreported its count")
_precondition(writtenUpTo == buf.endIndex, "rhs overreported its count")
}
extension _ContiguousArrayBuffer: RandomAccessCollection {
/// The position of the first element in a non-empty collection.
///
/// In an empty collection, `startIndex == endIndex`.
@inlinable
internal var startIndex: Int {
return 0
}
/// The collection's "past the end" position.
///
/// `endIndex` is not a valid argument to `subscript`, and is always
/// reachable from `startIndex` by zero or more applications of
/// `index(after:)`.
@inlinable
internal var endIndex: Int {
return count
}
@usableFromInline
internal typealias Indices = Range<Int>
}
extension Sequence {
@inlinable
public __consuming func _copyToContiguousArray() -> ContiguousArray<Element> {
return _copySequenceToContiguousArray(self)
}
}
@inlinable
internal func _copySequenceToContiguousArray<
S: Sequence
>(_ source: S) -> ContiguousArray<S.Element> {
let initialCapacity = source.underestimatedCount
var builder =
_UnsafePartiallyInitializedContiguousArrayBuffer<S.Element>(
initialCapacity: initialCapacity)
var iterator = source.makeIterator()
// FIXME(performance): use _copyContents(initializing:).
// Add elements up to the initial capacity without checking for regrowth.
for _ in 0..<initialCapacity {
builder.addWithExistingCapacity(iterator.next()!)
}
// Add remaining elements, if any.
while let element = iterator.next() {
builder.add(element)
}
return builder.finish()
}
extension Collection {
@inlinable
public __consuming func _copyToContiguousArray() -> ContiguousArray<Element> {
return _copyCollectionToContiguousArray(self)
}
}
extension _ContiguousArrayBuffer {
@inlinable
internal __consuming func _copyToContiguousArray() -> ContiguousArray<Element> {
return ContiguousArray(_buffer: self)
}
}
/// This is a fast implementation of _copyToContiguousArray() for collections.
///
/// It avoids the extra retain, release overhead from storing the
/// ContiguousArrayBuffer into
/// _UnsafePartiallyInitializedContiguousArrayBuffer. Since we do not support
/// ARC loops, the extra retain, release overhead cannot be eliminated which
/// makes assigning ranges very slow. Once this has been implemented, this code
/// should be changed to use _UnsafePartiallyInitializedContiguousArrayBuffer.
@inlinable
internal func _copyCollectionToContiguousArray<
C: Collection
>(_ source: C) -> ContiguousArray<C.Element>
{
let count: Int = numericCast(source.count)
if count == 0 {
return ContiguousArray()
}
let result = _ContiguousArrayBuffer<C.Element>(
_uninitializedCount: count,
minimumCapacity: 0)
let p = UnsafeMutableBufferPointer(start: result.firstElementAddress, count: count)
var (itr, end) = source._copyContents(initializing: p)
_debugPrecondition(itr.next() == nil,
"invalid Collection: more than 'count' elements in collection")
// We also have to check the evil shrink case in release builds, because
// it can result in uninitialized array elements and therefore undefined
// behavior.
_precondition(end == p.endIndex,
"invalid Collection: less than 'count' elements in collection")
return ContiguousArray(_buffer: result)
}
/// A "builder" interface for initializing array buffers.
///
/// This presents a "builder" interface for initializing an array buffer
/// element-by-element. The type is unsafe because it cannot be deinitialized
/// until the buffer has been finalized by a call to `finish`.
@usableFromInline
@frozen
internal struct _UnsafePartiallyInitializedContiguousArrayBuffer<Element> {
@usableFromInline
internal var result: _ContiguousArrayBuffer<Element>
@usableFromInline
internal var p: UnsafeMutablePointer<Element>
@usableFromInline
internal var remainingCapacity: Int
/// Initialize the buffer with an initial size of `initialCapacity`
/// elements.
@inlinable
@inline(__always) // For performance reasons.
internal init(initialCapacity: Int) {
if initialCapacity == 0 {
result = _ContiguousArrayBuffer()
} else {
result = _ContiguousArrayBuffer(
_uninitializedCount: initialCapacity,
minimumCapacity: 0)
}
p = result.firstElementAddress
remainingCapacity = result.capacity
}
/// Add an element to the buffer, reallocating if necessary.
@inlinable
@inline(__always) // For performance reasons.
internal mutating func add(_ element: Element) {
if remainingCapacity == 0 {
// Reallocate.
let newCapacity = max(_growArrayCapacity(result.capacity), 1)
var newResult = _ContiguousArrayBuffer<Element>(
_uninitializedCount: newCapacity, minimumCapacity: 0)
p = newResult.firstElementAddress + result.capacity
remainingCapacity = newResult.capacity - result.capacity
if !result.isEmpty {
// This check prevents a data race writting to _swiftEmptyArrayStorage
// Since count is always 0 there, this code does nothing anyway
newResult.firstElementAddress.moveInitialize(
from: result.firstElementAddress, count: result.capacity)
result.count = 0
}
(result, newResult) = (newResult, result)
}
addWithExistingCapacity(element)
}
/// Add an element to the buffer, which must have remaining capacity.
@inlinable
@inline(__always) // For performance reasons.
internal mutating func addWithExistingCapacity(_ element: Element) {
_internalInvariant(remainingCapacity > 0,
"_UnsafePartiallyInitializedContiguousArrayBuffer has no more capacity")
remainingCapacity -= 1
p.initialize(to: element)
p += 1
}
/// Finish initializing the buffer, adjusting its count to the final
/// number of elements.
///
/// Returns the fully-initialized buffer. `self` is reset to contain an
/// empty buffer and cannot be used afterward.
@inlinable
@inline(__always) // For performance reasons.
internal mutating func finish() -> ContiguousArray<Element> {
// Adjust the initialized count of the buffer.
result.count = result.capacity - remainingCapacity
return finishWithOriginalCount()
}
/// Finish initializing the buffer, assuming that the number of elements
/// exactly matches the `initialCount` for which the initialization was
/// started.
///
/// Returns the fully-initialized buffer. `self` is reset to contain an
/// empty buffer and cannot be used afterward.
@inlinable
@inline(__always) // For performance reasons.
internal mutating func finishWithOriginalCount() -> ContiguousArray<Element> {
_internalInvariant(remainingCapacity == result.capacity - result.count,
"_UnsafePartiallyInitializedContiguousArrayBuffer has incorrect count")
var finalResult = _ContiguousArrayBuffer<Element>()
(finalResult, result) = (result, finalResult)
remainingCapacity = 0
return ContiguousArray(_buffer: finalResult)
}
}
| apache-2.0 | a329f0128f360a7523c7f9eff28311ee | 30.8 | 110 | 0.699362 | 4.7943 | false | false | false | false |
lab111/hedwig | Sources/WindowShade.swift | 1 | 2819 | import UIKit
/// `WindowShade` is a view with slide functionality.
public class WindowShade: UIView {
/// The default value is `UINavigationControllerHideShowBarDuration`.
public var slideDuration: TimeInterval = TimeInterval(UINavigationControllerHideShowBarDuration)
/// It's true after the `windowShade` completes sliding down and before it completes sliding up.
internal(set) public var isDown: Bool = false
internal(set) public var isSliding: Bool = false
/// The swipe gesture recognizer that supports sliding up with swipe-up gesture.
private(set) public var swipeGestureRecognizer: UISwipeGestureRecognizer!
internal override init(frame: CGRect) {
super.init(frame: frame)
self.swipeGestureRecognizer = UISwipeGestureRecognizer(target: self, action: #selector(self.handleSwipeGesture))
self.swipeGestureRecognizer.direction = .up
self.addGestureRecognizer(self.swipeGestureRecognizer)
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
/// The action of `swipeGestureRecognizer`.
@objc private func handleSwipeGesture() {
self.slideUp()
}
/// - note:
/// It only works when both `isDown` and `isSliding` are false.
internal func slideDown(completion: ((Bool) -> Void)? = nil) {
if !self.isDown && !self.isSliding {
self.isSliding = true
UIView.animate(withDuration: self.slideDuration, animations: {
self.frame.origin.y = 0
}, completion: { (complete) in
self.isSliding = false
if complete {
self.isDown = true
}
if let completion = completion {
completion(complete)
}
})
} else {
if let completion = completion {
completion(false)
}
}
}
/// - note:
/// It only works when `isDown` is true and `isSliding` is false.
internal func slideUp(completion: ((Bool) -> Void)? = nil) {
if self.isDown && !self.isSliding {
self.isSliding = true
UIView.animate(withDuration: self.slideDuration, animations: {
self.frame.origin.y = -self.frame.height
}, completion: { complete in
self.isSliding = false
if complete {
self.isDown = false
}
if let completion = completion {
completion(complete)
}
})
} else {
if let completion = completion {
completion(false)
}
}
}
}
| mit | 029810882942fce296022bc1a1b095ce | 35.141026 | 120 | 0.569351 | 5.051971 | false | false | false | false |
PerfectServers/Perfect-Authentication-Server | Sources/PerfectAuthServer/handlers/user/userModAction.swift | 1 | 2494 | //
// userModAction.swift
// ServerMonitor
//
// Created by Jonathan Guthrie on 2017-04-30.
//
//
import PerfectHTTP
import PerfectLogger
import PerfectLocalAuthentication
extension Handlers {
static func userModAction(data: [String:Any]) throws -> RequestHandler {
return {
request, response in
let contextAccountID = request.session?.userid ?? ""
let contextAuthenticated = !(request.session?.userid ?? "").isEmpty
if !contextAuthenticated { response.redirect(path: "/login") }
// Verify Admin
Account.adminBounce(request, response)
let user = Account()
var msg = ""
if let id = request.urlVariables["id"] {
try? user.get(id)
if user.id.isEmpty {
redirectRequest(request, response, msg: "Invalid User", template: request.documentRoot + "/views/user.mustache")
}
}
if let firstname = request.param(name: "firstname"), !firstname.isEmpty,
let lastname = request.param(name: "lastname"), !lastname.isEmpty,
let email = request.param(name: "email"), !email.isEmpty,
let username = request.param(name: "username"), !username.isEmpty{
user.username = username
user.detail["firstname"] = firstname
user.detail["lastname"] = lastname
user.email = email
if let pwd = request.param(name: "pw"), !pwd.isEmpty {
user.makePassword(pwd)
}
switch request.param(name: "usertype") ?? "" {
case "standard":
user.usertype = .standard
case "admin":
user.usertype = .admin
case "inactive":
user.usertype = .inactive
default:
user.usertype = .provisional
}
if user.id.isEmpty {
user.makeID()
try? user.create()
} else {
try? user.save()
}
} else {
msg = "Please enter the user's first and last name, as well as a valid email."
redirectRequest(request, response, msg: msg, template: request.documentRoot + "/views/users.mustache", additional: [
"usermod?":"true",
])
}
let users = Account.listUsers()
var context: [String : Any] = [
"accountID": contextAccountID,
"authenticated": contextAuthenticated,
"userlist?":"true",
"users": users,
"msg": msg
]
if contextAuthenticated {
for i in Handlers.extras(request) {
context[i.0] = i.1
}
}
// add app config vars
for i in Handlers.appExtras(request) {
context[i.0] = i.1
}
response.renderMustache(template: request.documentRoot + "/views/users.mustache", context: context)
}
}
}
| apache-2.0 | 1591b17f14aa20a2b5675266456f6372 | 23.45098 | 120 | 0.643144 | 3.459085 | false | false | false | false |
Cellane/iWeb | Sources/App/Controllers/Web/Admin/AdminUsersController.swift | 1 | 2269 | import Vapor
import Paginator
extension Controllers.Web {
final class AdminUsersController {
private let droplet: Droplet
private let context = AdminContext()
init(droplet: Droplet) {
self.droplet = droplet
}
func addRoutes() {
let users = droplet.grouped("admin", "users")
let adminAuthorized = users.grouped(SessionRolesMiddleware(User.self, roles: [Role.admin]))
adminAuthorized.get(handler: showUsers)
adminAuthorized.post(User.parameter, "edit", handler: editUser)
adminAuthorized.get(User.parameter, "delete", handler: deleteUser)
adminAuthorized.get(String.parameter, "restore", handler: restoreUser)
}
func showUsers(req: Request) throws -> ResponseRepresentable {
let users = try User
.makeQuery()
.withSoftDeleted()
.sort(User.createdAtKey, .ascending)
.paginator(50, request: req)
return try droplet.view.makeDefault("admin/users/list", for: req, [
"users": users.makeNode(in: context),
"roles": Role.all().makeNode(in: context)
])
}
func editUser(req: Request) throws -> ResponseRepresentable {
do {
let user = try req.parameters.next(User.self)
let roleId = req.data["roleId"]?.string
let role = try Role.find(roleId)
user.roleId = try role?.assertExists()
try user.save()
return Response(redirect: "/admin/users")
.flash(.success, "User successfully edited.")
} catch {
return Response(redirect: "/admin/users")
.flash(.error, "Unexpected error occurred.")
}
}
func deleteUser(req: Request) throws -> ResponseRepresentable {
do {
let user = try req.parameters.next(User.self)
try user.delete()
return Response(redirect: "/admin/users")
.flash(.success, "User deleted.")
} catch {
return Response(redirect: "/admin/users")
.flash(.error, "Couldn't modify user.")
}
}
func restoreUser(req: Request) throws -> ResponseRepresentable {
do {
let userId = try req.parameters.next(String.self)
let user = try User.withSoftDeleted().find(userId)!
try user.restore()
return Response(redirect: "/admin/users")
.flash(.success, "User restored.")
} catch {
return Response(redirect: "/admin/users")
.flash(.error, "Couldn't modify user.")
}
}
}
}
| mit | bdfe0d1bb16638390dce70ebc44642f4 | 26.337349 | 94 | 0.674306 | 3.534268 | false | false | false | false |
naokits/bluemix-swift-demo-ios | Pods/BMSSecurity/Source/mca/internal/AuthorizationManagerPreferences.swift | 2 | 6257 | /*
* Copyright 2015 IBM Corp.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import BMSCore
internal class AuthorizationManagerPreferences {
private static var sharedPreferences:NSUserDefaults = NSUserDefaults.standardUserDefaults()
internal var persistencePolicy:PolicyPreference
internal var clientId:StringPreference
internal var accessToken:TokenPreference
internal var idToken:TokenPreference
internal var userIdentity:JSONPreference
internal var deviceIdentity:JSONPreference
internal var appIdentity:JSONPreference
internal init() {
persistencePolicy = PolicyPreference(prefName: BMSSecurityConstants.PERSISTENCE_POLICY_LABEL, defaultValue: PersistencePolicy.ALWAYS, idToken: nil, accessToken: nil)
clientId = StringPreference(prefName: BMSSecurityConstants.clientIdLabel)
accessToken = TokenPreference(prefName: BMSSecurityConstants.accessTokenLabel, persistencePolicy: persistencePolicy)
idToken = TokenPreference(prefName: BMSSecurityConstants.idTokenLabel, persistencePolicy: persistencePolicy)
persistencePolicy.idToken = idToken
persistencePolicy.accessToken = accessToken
userIdentity = JSONPreference(prefName: BMSSecurityConstants.USER_IDENTITY_LABEL)
deviceIdentity = JSONPreference(prefName : BMSSecurityConstants.DEVICE_IDENTITY_LABEL)
appIdentity = JSONPreference(prefName: BMSSecurityConstants.APP_IDENTITY_LABEL)
}
}
/**
* Holds single string preference value
*/
internal class StringPreference {
var prefName:String
var value:String?
internal convenience init(prefName:String) {
self.init(prefName: prefName, defaultValue: nil)
}
internal init(prefName:String, defaultValue:String?) {
self.prefName = prefName
if let val = AuthorizationManagerPreferences.sharedPreferences.valueForKey(prefName) as? String {
self.value = val
} else {
self.value = defaultValue
}
}
internal func get() ->String?{
return value
}
internal func set(value:String?) {
self.value = value
commit()
}
internal func clear() {
self.value = nil
commit()
}
private func commit() {
AuthorizationManagerPreferences.sharedPreferences.setValue(value, forKey: prefName)
AuthorizationManagerPreferences.sharedPreferences.synchronize()
}
}
/**
* Holds single JSON preference value
*/
internal class JSONPreference:StringPreference {
internal init(prefName:String) {
super.init(prefName: prefName, defaultValue: nil)
}
internal func set(json:[String:AnyObject])
{
set(try? Utils.JSONStringify(json))
}
internal func getAsMap() -> [String:AnyObject]?{
do {
if let json = get() {
return try Utils.parseJsonStringtoDictionary(json)
} else {
return nil
}
} catch {
print(error)
return nil
}
}
}
/**
* Holds authorization manager Policy preference
*/
internal class PolicyPreference {
private var value:PersistencePolicy
private var prefName:String
internal weak var idToken:TokenPreference?
internal weak var accessToken:TokenPreference?
init(prefName:String, defaultValue:PersistencePolicy, idToken:TokenPreference?, accessToken:TokenPreference?) {
self.accessToken = accessToken
self.idToken = idToken
self.prefName = prefName
if let rawValue = AuthorizationManagerPreferences.sharedPreferences.valueForKey(prefName) as? String , newValue = PersistencePolicy(rawValue: rawValue){
self.value = newValue
} else {
self.value = defaultValue
}
}
internal func get() -> PersistencePolicy {
return self.value
}
internal func set(value:PersistencePolicy ) {
self.value = value
self.accessToken!.updateStateByPolicy()
self.idToken!.updateStateByPolicy()
AuthorizationManagerPreferences.sharedPreferences.setValue(value.rawValue, forKey: prefName)
AuthorizationManagerPreferences.sharedPreferences.synchronize()
}
}
/**
* Holds authorization manager Token preference
*/
internal class TokenPreference {
var runtimeValue:String?
var prefName:String
var persistencePolicy:PolicyPreference
init(prefName:String, persistencePolicy:PolicyPreference){
self.prefName = prefName
self.persistencePolicy = persistencePolicy
}
internal func set(value:String) {
runtimeValue = value
if self.persistencePolicy.get() == PersistencePolicy.ALWAYS {
SecurityUtils.saveItemToKeyChain(value, label: prefName)
} else {
SecurityUtils.removeItemFromKeyChain(prefName)
}
}
internal func get() -> String?{
if (self.runtimeValue == nil && self.persistencePolicy.get() == PersistencePolicy.ALWAYS) {
return SecurityUtils.getItemFromKeyChain(prefName)
}
return runtimeValue
}
internal func updateStateByPolicy() {
if (self.persistencePolicy.get() == PersistencePolicy.ALWAYS) {
if let unWrappedRuntimeValue = runtimeValue {
SecurityUtils.saveItemToKeyChain(unWrappedRuntimeValue, label: prefName)
}
} else {
SecurityUtils.removeItemFromKeyChain(prefName)
}
}
internal func clear() {
SecurityUtils.removeItemFromKeyChain(prefName)
runtimeValue = nil
}
}
| mit | 12acc25ebfe7eabce2f1e30ba9977ad2 | 31.94709 | 173 | 0.678015 | 5.046191 | false | false | false | false |
Andgfaria/MiniGitClient-iOS | MiniGitClient/MiniGitClient/Scenes/Detail/RepositoryDetailViewController.swift | 1 | 5475 | /*
Copyright 2017 - André Gimenez Faria
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 RxSwift
class RepositoryDetailViewController: UIViewController {
weak var presenter : RepositoryDetailPresenterType?
weak var tableViewModel : RepositoryDetailTableViewModelType?
fileprivate let tableView = UITableView(frame: CGRect.zero, style: .plain)
fileprivate let headerView = RepositoryDetailHeaderView()
fileprivate let disposeBag = DisposeBag()
override func viewDidLoad() {
super.viewDidLoad()
tableViewModel?.register(tableView: tableView)
addShareButton()
setup(withViews: [tableView])
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
adjustHeaderLayout()
}
}
extension RepositoryDetailViewController {
fileprivate func adjustHeaderLayout() {
headerView.adjustLayout(withWidth: tableView.bounds.size.width)
view.layoutIfNeeded()
headerView.frame = CGRect(x: 0, y: 0, width: tableView.bounds.size.width, height: headerView.intrinsicContentSize.height)
tableView.tableHeaderView = headerView
}
}
extension RepositoryDetailViewController {
fileprivate func addShareButton() {
self.navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .action, target: self, action: #selector(share(sender:)))
}
func share(sender : UIBarButtonItem) {
if let shareItems = presenter?.shareItems {
let activityViewController = UIActivityViewController(activityItems: shareItems, applicationActivities: nil)
activityViewController.popoverPresentationController?.barButtonItem = sender
present(activityViewController, animated: true, completion: nil)
}
}
}
extension RepositoryDetailViewController : ViewCodable {
func setupConstraints() {
tableView.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true
tableView.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true
tableView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
tableView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
}
func setupStyles() {
tableView.estimatedRowHeight = 56
tableView.rowHeight = UITableViewAutomaticDimension
tableView.tableFooterView = UIView(frame: CGRect.zero)
}
func bindComponents() {
if let presenter = presenter {
presenter.repository
.asObservable()
.subscribe(onNext: { [weak self] in
if let headerView = self?.headerView {
RepositoryDetailHeaderViewModel.configureHeader(headerView, withRepository: $0)
}
})
.addDisposableTo(disposeBag)
presenter.pullRequests
.asObservable()
.subscribe(onNext: { [weak self] in
self?.tableViewModel?.update(withPullRequests: $0)
})
.addDisposableTo(disposeBag)
presenter.currentState
.asObservable()
.map {
[RepositoryDetailState.loading : RepositoryDetailHeaderState.loading,
RepositoryDetailState.showingPullRequests : RepositoryDetailHeaderState.loaded,
RepositoryDetailState.onError : RepositoryDetailHeaderState.showingRetryOption][$0]
?? RepositoryDetailHeaderState.showingRetryOption
}
.bind(to: headerView.currentState)
.addDisposableTo(disposeBag)
headerView.currentState
.asObservable()
.skip(1)
.subscribe(onNext: { [weak self] in
if $0 == .loading {
self?.presenter?.currentState.value = .loading
}
})
.addDisposableTo(disposeBag)
}
}
func setupAccessibilityIdentifiers() {
tableView.accessibilityIdentifier = "PullRequestsTableView"
navigationItem.rightBarButtonItem?.accessibilityIdentifier = "RepositoryDetailShareButton"
}
}
| mit | 08c65633131132e3165800143d210b72 | 42.444444 | 461 | 0.651809 | 5.969466 | false | false | false | false |
spacedrabbit/100-days | One00Days/One00Days/Day34Playground.playground/Contents.swift | 1 | 1025 | //: Playground - noun: a place where people can play
// see: https://robots.thoughtbot.com/swift-sequences
// https://www.natashatherobot.com/swift-conform-to-sequence-protocol/
// http://lillylabs.no/2014/09/30/make-iterable-swift-collection-type-sequencetype/
import UIKit
struct Cat {
var name: String
init(name: String) {
self.name = name
}
}
struct CatClub: SequenceType, GeneratorType {
typealias Element = Cat
private var allCats: [Cat] = [Cat]()
private var nextIndex: Int
init(cats: [Cat]) {
self.allCats = cats
self.nextIndex = 0
}
mutating func next() -> Cat? {
if nextIndex < self.allCats.count {
print("Index: \(nextIndex) is returning a cat: \(allCats[nextIndex])")
return allCats[nextIndex++]
}
return nil
}
}
var applicantCats: [Cat] = [ Cat(name: "Fiddles"), Cat(name: "Jerry"), Cat(name: "Meowser"), Cat(name: "Sir Bottom Waggles")]
let clubCats: CatClub = CatClub(cats: applicantCats)
for cat in clubCats {
print("Name: \(cat.name)")
}
| mit | 06b4e39540572a2bf1e53b3b72d2bb8c | 23.404762 | 125 | 0.668293 | 3.264331 | false | false | false | false |
NikAshanin/Design-Patterns-In-Swift-Compare-Kotlin | Structural/Flyweight/flyweight.swift | 1 | 1093 | // Implementation
final class SpecialityCoffee: CustomStringConvertible {
var origin: String
var description: String {
get {
return origin
}
}
init(origin: String) {
self.origin = origin
}
}
final class Menu {
private var coffeeAvailable: [String: SpecialityCoffee] = [:]
func lookup(origin: String) -> SpecialityCoffee? {
if coffeeAvailable.index(forKey: origin) == nil {
coffeeAvailable[origin] = SpecialityCoffee(origin: origin)
}
return coffeeAvailable[origin]
}
}
final class CoffeeShop {
private var orders: [Int: SpecialityCoffee] = [:]
private var menu = Menu()
func takeOrder(origin: String, table: Int) {
orders[table] = menu.lookup(origin: origin)
}
func serve() {
for (table, origin) in orders {
print("Serving \(origin) to table \(table)")
}
}
}
// Usage
val coffeeShop = CoffeeShop()
coffeeShop.takeOrder("Yirgacheffe, Ethiopia", 1)
coffeeShop.takeOrder("Buziraguhindwa, Burundi", 3)
coffeeShop.serve()
| mit | 302cc880d255086fc98181706a9f91ff | 20.86 | 70 | 0.622141 | 3.903571 | false | false | false | false |
ello/ello-ios | Specs/Extensions/URLExtensionsSpec.swift | 1 | 1710 | ////
/// URLSpec.swift
//
@testable import Ello
import Quick
import Nimble
class URLExtensionSpec: QuickSpec {
override func spec() {
describe("URL") {
describe("hasGifExtension") {
let expectations: [(String, Bool)] = [
("http://ello.co/file.gif", true),
("http://ello.co/file.GIF", true),
("http://ello.co/file.Gif", true),
("http://ello.co/filegif", false),
("http://ello.co/file/gif", false),
]
for (url, expected) in expectations {
it("should be \(expected) for \(url)") {
expect(URL(string: url)?.hasGifExtension) == expected
}
}
}
describe("isValidShorthand") {
let expectations: [(String, Bool)] = [
("", false),
("http://", false),
("://", false),
("://ello.co", false),
("ello", false),
("http://ello", false),
("http://ello.", false),
("http://ello/foo.html", false),
("ello.co", true),
("http://ello.co", true),
("https://ello.co", true),
("http://any.where/foo", true),
]
for (url, expected) in expectations {
it("\(url) should\(expected ? "" : " not") be valid") {
expect(URL.isValidShorthand(url)) == expected
}
}
}
}
}
}
| mit | 7e9be846442c43db52c11c284d97e224 | 32.529412 | 77 | 0.376023 | 4.871795 | false | false | false | false |
22377832/swiftdemo | Google/Google/AppDelegate.swift | 1 | 3620 | //
// AppDelegate.swift
// Google
//
// Created by adults on 2017/3/31.
// Copyright © 2017年 adults. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, GIDSignInDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
GIDSignIn.sharedInstance().clientID = "585991931439-0bkg7ea831bedgh4sq1rj007honn9q3r.apps.googleusercontent.com"
GIDSignIn.sharedInstance().delegate = self
FBSDKApplicationDelegate.sharedInstance().application(application, didFinishLaunchingWithOptions: launchOptions)
return true
}
func sign(_ signIn: GIDSignIn!, didDisconnectWith user: GIDGoogleUser!, withError error: Error!) {
print("disConnect")
}
func sign(_ signIn: GIDSignIn!, didSignInFor user: GIDGoogleUser!, withError error: Error!) {
print("SignIn")
// Perform any operations on signed in user here.
NotificationCenter.default.post(name: NSNotification.Name(rawValue: "GoogleSignIn"), object: nil, userInfo: ["user": user])
}
func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool {
print(url)
let FBHandle = FBSDKApplicationDelegate.sharedInstance().application(app, open: url, options: options)
let GoogleHandle = GIDSignIn.sharedInstance().handle(url, sourceApplication: options[UIApplicationOpenURLOptionsKey.sourceApplication] as? String, annotation: options[UIApplicationOpenURLOptionsKey.annotation])
print(FBHandle)
print(GoogleHandle)
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
FBSDKAppEvents.activateApp()
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| mit | 3d04a65caf3939fcb1e6c32df2fd88e8 | 43.654321 | 285 | 0.721869 | 5.547546 | false | false | false | false |
jaanussiim/weather-scrape | Sources/Log.swift | 1 | 1778 | /*
* Copyright 2015 Coodly LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import Foundation
public class Log {
public enum Level: Int {
case VERBOSE = 0, DEBUG, INFO, ERROR, NONE
}
public static var logLevel = Level.NONE
public class func info<T>(_ object: T, file: String = #file, function: String = #function, line: Int = #line) {
Logger.sharedInstance.log(object, file: file, function: function, line: line, level: .INFO)
}
public class func debug<T>(_ object: T, file: String = #file, function: String = #function, line: Int = #line) {
Logger.sharedInstance.log(object, file: file, function: function, line: line, level: .DEBUG)
}
public class func error<T>(_ object: T, file: String = #file, function: String = #function, line: Int = #line) {
Logger.sharedInstance.log(object, file: file, function: function, line: line, level: .ERROR)
}
public class func verbose<T>(_ object: T, file: String = #file, function: String = #function, line: Int = #line) {
Logger.sharedInstance.log(object, file: file, function: function, line: line, level: .VERBOSE)
}
public class func addOutput(output: LogOutput) {
Logger.sharedInstance.addOutput(output: output)
}
}
| apache-2.0 | 1dce9ed6e83f034be45a961a520aceb2 | 38.511111 | 118 | 0.68279 | 3.890591 | false | false | false | false |
Sage-Bionetworks/BridgeAppSDK | BridgeAppSDK/SBAOnboardingStepController.swift | 1 | 3561 | //
// SBAOnboardingStepController.swift
// BridgeAppSDK
//
// Copyright © 2016-2017 Sage Bionetworks. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation and/or
// other materials provided with the distribution.
//
// 3. Neither the name of the copyright holder(s) nor the names of any contributors
// may be used to endorse or promote products derived from this software without
// specific prior written permission. No license is granted to the trademarks of
// the copyright holders even if such marks are included in this software.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
import Foundation
/**
The `SBAOnboardingStepController` protocol is used during onboarding to update the different model objects
stored on with the participant info to determine the user's onboarding state. Some values (such as name
and age) are saved as a part of that process. This is intended for subclasses of `ORKStepViewController`
where the specific subclasses may not share a superclass inheritance.
*/
public protocol SBAOnboardingStepController: SBAAccountStepController, SBAResearchKitResultConverter {
}
extension SBAOnboardingStepController {
/**
Look for profile keys and set them if found.
*/
func updateUserProfileInfo() {
guard let profileKeys = (self.step as? SBAProfileInfoForm)?.formItems?.map({ $0.identifier }) else { return }
let excludeKeys: [SBAProfileInfoOption] = [.email, .password]
let keySet = Set(profileKeys).subtracting(excludeKeys.map({ $0.rawValue }))
self.update(participantInfo: self.sharedUser, with: Array(keySet))
}
/**
During consent and registration, update the consent signature with new values
before finishing.
*/
func updateUserConsentSignature(_ consentSignature: SBAConsentSignature? = nil) {
guard let signature = consentSignature ?? sharedUser.consentSignature else { return }
// Look for full name and birthdate to use in populating the consent
if let fullName = self.fullName ?? self.sharedNameDataSource?.fullName {
signature.signatureName = fullName
}
if let birthdate = self.birthdate ?? sharedUser.birthdate {
signature.signatureBirthdate = birthdate
}
// Update the signature back to the shared user
sharedUser.consentSignature = signature
}
}
| bsd-3-clause | 3e8e914c53d4819b16e0b201abe95404 | 45.842105 | 117 | 0.739607 | 4.930748 | false | false | false | false |
LamGiauKhongKhoTeam/LGKK | ModulesTests/CryptoSwiftTests/BlowfishTests.swift | 1 | 10143 | //
// BlowfishTests.swift
// CryptoSwift
//
// Created by Marcin Krzyzanowski on 26/10/16.
// Copyright © 2016 Marcin Krzyzanowski. All rights reserved.
//
// Test vector from http://www.schneier.com/code/vectors.txt
//
import XCTest
@testable import CryptoSwift
class BlowfishTests: XCTestCase {
struct TestData {
let key: Array<UInt8>
let input: Array<UInt8>
let output: Array<UInt8>
}
let tests = [
TestData(key: [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00],
input: [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00],
output: [0x4E, 0xF9, 0x97, 0x45, 0x61, 0x98, 0xDD, 0x78]),
TestData(key: [0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF],
input: [0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF],
output: [0x51, 0x86, 0x6F, 0xD5, 0xB8, 0x5E, 0xCB, 0x8A]),
TestData(key: [0x30, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00],
input: [0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01],
output: [0x7D, 0x85, 0x6F, 0x9A, 0x61, 0x30, 0x63, 0xF2]),
TestData(key: [0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11],
input: [0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11],
output: [0x24, 0x66, 0xDD, 0x87, 0x8B, 0x96, 0x3C, 0x9D]),
TestData(key: [0x01, 0x23, 0x45, 0x67, 0x89, 0xAB, 0xCD, 0xEF],
input: [0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11],
output:[0x61, 0xF9, 0xC3, 0x80, 0x22, 0x81, 0xB0, 0x96]),
TestData(key: [0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11],
input: [0x01, 0x23, 0x45, 0x67, 0x89, 0xAB, 0xCD, 0xEF],
output:[0x7D, 0x0C, 0xC6, 0x30, 0xAF, 0xDA, 0x1E, 0xC7]),
TestData(key: [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00],
input: [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00],
output:[0x4E, 0xF9, 0x97, 0x45, 0x61, 0x98, 0xDD, 0x78]),
TestData(key: [0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10],
input: [0x01, 0x23, 0x45, 0x67, 0x89, 0xAB, 0xCD, 0xEF],
output:[0x0A, 0xCE, 0xAB, 0x0F, 0xC6, 0xA0, 0xA2, 0x8D]),
TestData(key: [0x7C, 0xA1, 0x10, 0x45, 0x4A, 0x1A, 0x6E, 0x57],
input: [0x01, 0xA1, 0xD6, 0xD0, 0x39, 0x77, 0x67, 0x42],
output:[0x59, 0xC6, 0x82, 0x45, 0xEB, 0x05, 0x28, 0x2B]),
TestData(key: [0x01, 0x31, 0xD9, 0x61, 0x9D, 0xC1, 0x37, 0x6E],
input: [0x5C, 0xD5, 0x4C, 0xA8, 0x3D, 0xEF, 0x57, 0xDA],
output:[0xB1, 0xB8, 0xCC, 0x0B, 0x25, 0x0F, 0x09, 0xA0]),
TestData(key: [0x07, 0xA1, 0x13, 0x3E, 0x4A, 0x0B, 0x26, 0x86],
input: [0x02, 0x48, 0xD4, 0x38, 0x06, 0xF6, 0x71, 0x72],
output:[0x17, 0x30, 0xE5, 0x77, 0x8B, 0xEA, 0x1D, 0xA4]),
TestData(key: [0x38, 0x49, 0x67, 0x4C, 0x26, 0x02, 0x31, 0x9E],
input: [0x51, 0x45, 0x4B, 0x58, 0x2D, 0xDF, 0x44, 0x0A],
output:[0xA2, 0x5E, 0x78, 0x56, 0xCF, 0x26, 0x51, 0xEB]),
TestData(key: [0x04, 0xB9, 0x15, 0xBA, 0x43, 0xFE, 0xB5, 0xB6],
input: [0x42, 0xFD, 0x44, 0x30, 0x59, 0x57, 0x7F, 0xA2],
output:[0x35, 0x38, 0x82, 0xB1, 0x09, 0xCE, 0x8F, 0x1A]),
TestData(key: [0x01, 0x13, 0xB9, 0x70, 0xFD, 0x34, 0xF2, 0xCE],
input: [0x05, 0x9B, 0x5E, 0x08, 0x51, 0xCF, 0x14, 0x3A],
output:[0x48, 0xF4, 0xD0, 0x88, 0x4C, 0x37, 0x99, 0x18]),
TestData(key: [0x01, 0x70, 0xF1, 0x75, 0x46, 0x8F, 0xB5, 0xE6],
input: [0x07, 0x56, 0xD8, 0xE0, 0x77, 0x47, 0x61, 0xD2],
output:[0x43, 0x21, 0x93, 0xB7, 0x89, 0x51, 0xFC, 0x98]),
TestData(key: [0x43, 0x29, 0x7F, 0xAD, 0x38, 0xE3, 0x73, 0xFE],
input: [0x76, 0x25, 0x14, 0xB8, 0x29, 0xBF, 0x48, 0x6A],
output:[0x13, 0xF0, 0x41, 0x54, 0xD6, 0x9D, 0x1A, 0xE5]),
TestData(key: [0x07, 0xA7, 0x13, 0x70, 0x45, 0xDA, 0x2A, 0x16],
input: [0x3B, 0xDD, 0x11, 0x90, 0x49, 0x37, 0x28, 0x02],
output:[0x2E, 0xED, 0xDA, 0x93, 0xFF, 0xD3, 0x9C, 0x79]),
TestData(key: [0x04, 0x68, 0x91, 0x04, 0xC2, 0xFD, 0x3B, 0x2F],
input: [0x26, 0x95, 0x5F, 0x68, 0x35, 0xAF, 0x60, 0x9A],
output:[0xD8, 0x87, 0xE0, 0x39, 0x3C, 0x2D, 0xA6, 0xE3]),
TestData(key: [0x37, 0xD0, 0x6B, 0xB5, 0x16, 0xCB, 0x75, 0x46],
input: [0x16, 0x4D, 0x5E, 0x40, 0x4F, 0x27, 0x52, 0x32],
output:[0x5F, 0x99, 0xD0, 0x4F, 0x5B, 0x16, 0x39, 0x69]),
TestData(key: [0x1F, 0x08, 0x26, 0x0D, 0x1A, 0xC2, 0x46, 0x5E],
input: [0x6B, 0x05, 0x6E, 0x18, 0x75, 0x9F, 0x5C, 0xCA],
output:[0x4A, 0x05, 0x7A, 0x3B, 0x24, 0xD3, 0x97, 0x7B]),
TestData(key: [0x58, 0x40, 0x23, 0x64, 0x1A, 0xBA, 0x61, 0x76],
input: [0x00, 0x4B, 0xD6, 0xEF, 0x09, 0x17, 0x60, 0x62],
output:[0x45, 0x20, 0x31, 0xC1, 0xE4, 0xFA, 0xDA, 0x8E]),
TestData(key: [0x02, 0x58, 0x16, 0x16, 0x46, 0x29, 0xB0, 0x07],
input: [0x48, 0x0D, 0x39, 0x00, 0x6E, 0xE7, 0x62, 0xF2],
output:[0x75, 0x55, 0xAE, 0x39, 0xF5, 0x9B, 0x87, 0xBD]),
TestData(key: [0x49, 0x79, 0x3E, 0xBC, 0x79, 0xB3, 0x25, 0x8F],
input: [0x43, 0x75, 0x40, 0xC8, 0x69, 0x8F, 0x3C, 0xFA],
output:[0x53, 0xC5, 0x5F, 0x9C, 0xB4, 0x9F, 0xC0, 0x19]),
TestData(key: [0x4F, 0xB0, 0x5E, 0x15, 0x15, 0xAB, 0x73, 0xA7],
input: [0x07, 0x2D, 0x43, 0xA0, 0x77, 0x07, 0x52, 0x92],
output:[0x7A, 0x8E, 0x7B, 0xFA, 0x93, 0x7E, 0x89, 0xA3]),
TestData(key: [0x49, 0xE9, 0x5D, 0x6D, 0x4C, 0xA2, 0x29, 0xBF],
input: [0x02, 0xFE, 0x55, 0x77, 0x81, 0x17, 0xF1, 0x2A],
output:[0xCF, 0x9C, 0x5D, 0x7A, 0x49, 0x86, 0xAD, 0xB5]),
TestData(key: [0x01, 0x83, 0x10, 0xDC, 0x40, 0x9B, 0x26, 0xD6],
input: [0x1D, 0x9D, 0x5C, 0x50, 0x18, 0xF7, 0x28, 0xC2],
output:[0xD1, 0xAB, 0xB2, 0x90, 0x65, 0x8B, 0xC7, 0x78]),
TestData(key: [0x1C, 0x58, 0x7F, 0x1C, 0x13, 0x92, 0x4F, 0xEF],
input: [0x30, 0x55, 0x32, 0x28, 0x6D, 0x6F, 0x29, 0x5A],
output:[0x55, 0xCB, 0x37, 0x74, 0xD1, 0x3E, 0xF2, 0x01]),
TestData(key: [0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01],
input: [0x01, 0x23, 0x45, 0x67, 0x89, 0xAB, 0xCD, 0xEF],
output:[0xFA, 0x34, 0xEC, 0x48, 0x47, 0xB2, 0x68, 0xB2]),
TestData(key: [0x1F, 0x1F, 0x1F, 0x1F, 0x0E, 0x0E, 0x0E, 0x0E],
input: [0x01, 0x23, 0x45, 0x67, 0x89, 0xAB, 0xCD, 0xEF],
output:[0xA7, 0x90, 0x79, 0x51, 0x08, 0xEA, 0x3C, 0xAE]),
TestData(key: [0xE0, 0xFE, 0xE0, 0xFE, 0xF1, 0xFE, 0xF1, 0xFE],
input: [0x01, 0x23, 0x45, 0x67, 0x89, 0xAB, 0xCD, 0xEF],
output:[0xC3, 0x9E, 0x07, 0x2D, 0x9F, 0xAC, 0x63, 0x1D]),
TestData(key: [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00],
input: [0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF],
output:[0x01, 0x49, 0x33, 0xE0, 0xCD, 0xAF, 0xF6, 0xE4]),
TestData(key: [0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF],
input: [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00],
output:[0xF2, 0x1E, 0x9A, 0x77, 0xB7, 0x1C, 0x49, 0xBC]),
TestData(key: [0x01, 0x23, 0x45, 0x67, 0x89, 0xAB, 0xCD, 0xEF],
input: [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00],
output:[0x24, 0x59, 0x46, 0x88, 0x57, 0x54, 0x36, 0x9A]),
TestData(key: [0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10],
input: [0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF],
output:[0x6B, 0x5C, 0x5A, 0x9C, 0x5D, 0x9E, 0x0A, 0x5A]),
]
func testEncrypt() {
for test in self.tests {
XCTAssertEqual(try Blowfish(key: test.key, blockMode: .ECB, padding: NoPadding()).encrypt(test.input), test.output)
}
}
func testDecrypt() {
for test in self.tests {
XCTAssertEqual(try Blowfish(key: test.key, blockMode: .ECB, padding: NoPadding()).decrypt(test.output), test.input)
}
}
func testCBCZeroPadding() {
let key = Array<UInt8>.init(hex: "0123456789ABCDEFF0E1D2C3B4A59687")
let iv = Array<UInt8>.init(hex: "FEDCBA9876543210")
let input = Array<UInt8>.init(hex: "37363534333231204E6F77206973207468652074696D6520666F722000")
XCTAssertEqual(try Blowfish(key: key, iv: iv, blockMode: .CBC, padding: ZeroPadding()).encrypt(input), Array<UInt8>(hex: "6B77B4D63006DEE605B156E27403979358DEB9E7154616D959F1652BD5FF92CC"))
}
func testEncryptDecrypt() {
let key = Array<UInt8>.init(hex: "0123456789ABCDEFF0E1D2C3B4A59687")
let iv = Array<UInt8>.init(hex: "FEDCBA9876543210")
let input = Array<UInt8>.init(hex: "37363534333231204E6F77206973207468652074696D6520666F722000")
do {
let cipher = try Blowfish(key: key, iv: iv, blockMode: .CBC, padding: PKCS7())
let ciphertext = try cipher.encrypt(input)
let plaintext = try cipher.decrypt(ciphertext)
XCTAssertEqual(plaintext, input)
} catch {
XCTFail(error.localizedDescription)
}
}
// https://github.com/krzyzanowskim/CryptoSwift/issues/415
func testDecryptCFB415() {
do {
let plaintext = Array("secret12".utf8)
let encrypted = try Blowfish(key: "passwordpassword", iv: "12345678", blockMode: .CFB, padding: NoPadding()).encrypt(plaintext)
let decrypted = try Blowfish(key: "passwordpassword", iv: "12345678", blockMode: .CFB, padding: NoPadding()).decrypt(encrypted)
XCTAssertEqual(plaintext, decrypted)
} catch {
XCTFail(error.localizedDescription)
}
}
}
| mit | 81f547356c3c1a3258ed7b041dcf09d2 | 49.207921 | 197 | 0.55778 | 2.281665 | false | true | false | false |
honghaoz/UW-Quest-iOS | UW Quest/SearchClasses/SearchClassInstitutionCell.swift | 1 | 1759 | //
// SearchClassInstitutionCell.swift
// UW Quest
//
// Created by Honghao Zhang on 1/21/15.
// Copyright (c) 2015 Honghao. All rights reserved.
//
import UIKit
class SearchClassInstitutionCell: UITableViewCell {
@IBOutlet weak var institutionMenu: ZHDropDownMenu!
@IBOutlet weak var termMenu: ZHDropDownMenu!
override func awakeFromNib() {
super.awakeFromNib()
self.backgroundColor = UIColor.clearColor()
self.contentView.backgroundColor = UIColor.clearColor()
institutionMenu.textColor = UQLabelFontColor
institutionMenu.titleFont = UIFont.helveticaNeueLightFont(17)
termMenu.textColor = UQLabelFontColor
termMenu.titleFont = UIFont.helveticaNeueLightFont(17)
setup()
}
private func setup() {
institutionMenu.dataSource = self
institutionMenu.delegate = self
institutionMenu.currentSelectedIndex = 1
termMenu.dataSource = self
termMenu.delegate = self
}
}
extension SearchClassInstitutionCell: ZHDropDownMenuDataSource, ZHDropDownMenuDelegate {
func numberOfItemsInDropDownMenu(menu: ZHDropDownMenu) -> Int {
return 6
}
func zhDropDownMenu(menu: ZHDropDownMenu, itemTitleForIndex index: Int) -> String {
switch index {
case 0:
return "abcd"
case 1:
return "hahah this "
case 2:
return "great man"
case 3:
return "awesome!"
case 4:
return "cool guys"
default:
return "this is amazing!"
}
}
func zhDropDownMenu(menu: ZHDropDownMenu, didSelectIndex index: Int) {
logDebug("didSelected: \(index)")
}
} | apache-2.0 | 63f07f2f26aaceedae524092a50c47ea | 26.5 | 88 | 0.632177 | 4.715818 | false | false | false | false |
almazrafi/Metatron | Sources/ID3v2/ID3v2FrameRegistry.swift | 1 | 12779 | //
// ID3v2FrameRegistry.swift
// Metatron
//
// Copyright (c) 2016 Almaz Ibragimov
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
public class ID3v2FrameRegistry {
// MARK: Type Properties
public static let regular = ID3v2FrameRegistry()
// MARK: Instance Properties
public private(set) var nativeIDs: [String: ID3v2FrameID]
public private(set) var customIDs: [String: ID3v2FrameID]
public private(set) var stuffs: [ID3v2FrameID: ID3v2FrameStuffFormat]
// MARK: Initializers
private init() {
self.nativeIDs = ["AENC": ID3v2FrameID.aenc,
"APIC": ID3v2FrameID.apic,
"ASPI": ID3v2FrameID.aspi,
"COMM": ID3v2FrameID.comm,
"COMR": ID3v2FrameID.comr,
"CRM": ID3v2FrameID.crm,
"ENCR": ID3v2FrameID.encr,
"EQUA": ID3v2FrameID.equa,
"EQU2": ID3v2FrameID.equ2,
"ETCO": ID3v2FrameID.etco,
"GEOB": ID3v2FrameID.geob,
"GRID": ID3v2FrameID.grid,
"IPLS": ID3v2FrameID.ipls,
"LINK": ID3v2FrameID.link,
"MCDI": ID3v2FrameID.mcdi,
"MLLT": ID3v2FrameID.mllt,
"OWNE": ID3v2FrameID.owne,
"PRIV": ID3v2FrameID.priv,
"PCNT": ID3v2FrameID.pcnt,
"POPM": ID3v2FrameID.popm,
"POSS": ID3v2FrameID.poss,
"RBUF": ID3v2FrameID.rbuf,
"RVAD": ID3v2FrameID.rvad,
"RVA2": ID3v2FrameID.rva2,
"RVRB": ID3v2FrameID.rvrb,
"SEEK": ID3v2FrameID.seek,
"SIGN": ID3v2FrameID.sign,
"SYLT": ID3v2FrameID.sylt,
"SYTC": ID3v2FrameID.sytc,
"TALB": ID3v2FrameID.talb,
"TBPM": ID3v2FrameID.tbpm,
"TCOM": ID3v2FrameID.tcom,
"TCON": ID3v2FrameID.tcon,
"TCOP": ID3v2FrameID.tcop,
"TDEN": ID3v2FrameID.tden,
"TDAT": ID3v2FrameID.tdat,
"TDLY": ID3v2FrameID.tdly,
"TDOR": ID3v2FrameID.tdor,
"TDRC": ID3v2FrameID.tdrc,
"TDRL": ID3v2FrameID.tdrl,
"TDTG": ID3v2FrameID.tdtg,
"TENC": ID3v2FrameID.tenc,
"TEXT": ID3v2FrameID.text,
"TFLT": ID3v2FrameID.tflt,
"TIPL": ID3v2FrameID.tipl,
"TIME": ID3v2FrameID.time,
"TIT1": ID3v2FrameID.tit1,
"TIT2": ID3v2FrameID.tit2,
"TIT3": ID3v2FrameID.tit3,
"TKEY": ID3v2FrameID.tkey,
"TLAN": ID3v2FrameID.tlan,
"TLEN": ID3v2FrameID.tlen,
"TMCL": ID3v2FrameID.tmcl,
"TMED": ID3v2FrameID.tmed,
"TMOO": ID3v2FrameID.tmoo,
"TOAL": ID3v2FrameID.toal,
"TOFN": ID3v2FrameID.tofn,
"TOLY": ID3v2FrameID.toly,
"TOPE": ID3v2FrameID.tope,
"TORY": ID3v2FrameID.tory,
"TOWN": ID3v2FrameID.town,
"TPE1": ID3v2FrameID.tpe1,
"TPE2": ID3v2FrameID.tpe2,
"TPE3": ID3v2FrameID.tpe3,
"TPE4": ID3v2FrameID.tpe4,
"TPOS": ID3v2FrameID.tpos,
"TPRO": ID3v2FrameID.tpro,
"TPUB": ID3v2FrameID.tpub,
"TRCK": ID3v2FrameID.trck,
"TRDA": ID3v2FrameID.trda,
"TRSN": ID3v2FrameID.trsn,
"TRSO": ID3v2FrameID.trso,
"TSOA": ID3v2FrameID.tsoa,
"TSOP": ID3v2FrameID.tsop,
"TSOT": ID3v2FrameID.tsot,
"TSIZ": ID3v2FrameID.tsiz,
"TSRC": ID3v2FrameID.tsrc,
"TSSE": ID3v2FrameID.tsse,
"TSST": ID3v2FrameID.tsst,
"TYER": ID3v2FrameID.tyer,
"TXXX": ID3v2FrameID.txxx,
"UFID": ID3v2FrameID.ufid,
"USER": ID3v2FrameID.user,
"USLT": ID3v2FrameID.uslt,
"WCOM": ID3v2FrameID.wcom,
"WCOP": ID3v2FrameID.wcop,
"WOAF": ID3v2FrameID.woaf,
"WOAR": ID3v2FrameID.woar,
"WOAS": ID3v2FrameID.woas,
"WORS": ID3v2FrameID.wors,
"WPAY": ID3v2FrameID.wpay,
"WPUB": ID3v2FrameID.wpub,
"WXXX": ID3v2FrameID.wxxx,
"ATXT": ID3v2FrameID.atxt,
"CHAP": ID3v2FrameID.chap,
"CTOC": ID3v2FrameID.ctoc]
self.customIDs = [:]
self.stuffs = [ID3v2FrameID.aenc: ID3v2AudioEncryptionFormat.regular,
ID3v2FrameID.apic: ID3v2AttachedPictureFormat.regular,
ID3v2FrameID.comm: ID3v2CommentsFormat.regular,
ID3v2FrameID.encr: ID3v2FeatureRegistrationFormat.regular,
ID3v2FrameID.etco: ID3v2EventTimingCodesFormat.regular,
ID3v2FrameID.grid: ID3v2FeatureRegistrationFormat.regular,
ID3v2FrameID.ipls: ID3v2InvolvedPeopleListFormat.regular,
ID3v2FrameID.pcnt: ID3v2PlayCounterFormat.regular,
ID3v2FrameID.popm: ID3v2PopularimeterFormat.regular,
ID3v2FrameID.sign: ID3v2FeatureSignatureFormat.regular,
ID3v2FrameID.sylt: ID3v2SyncedLyricsFormat.regular,
ID3v2FrameID.sytc: ID3v2SyncedTempoCodesFormat.regular,
ID3v2FrameID.talb: ID3v2TextInformationFormat.regular,
ID3v2FrameID.tbpm: ID3v2TextInformationFormat.regular,
ID3v2FrameID.tcom: ID3v2TextInformationFormat.regular,
ID3v2FrameID.tcon: ID3v2ContentTypeFormat.regular,
ID3v2FrameID.tcop: ID3v2TextInformationFormat.regular,
ID3v2FrameID.tden: ID3v2TextInformationFormat.regular,
ID3v2FrameID.tdat: ID3v2TextInformationFormat.regular,
ID3v2FrameID.tdly: ID3v2TextInformationFormat.regular,
ID3v2FrameID.tdor: ID3v2TextInformationFormat.regular,
ID3v2FrameID.tdrc: ID3v2TextInformationFormat.regular,
ID3v2FrameID.tdrl: ID3v2TextInformationFormat.regular,
ID3v2FrameID.tdtg: ID3v2TextInformationFormat.regular,
ID3v2FrameID.tenc: ID3v2TextInformationFormat.regular,
ID3v2FrameID.text: ID3v2TextInformationFormat.regular,
ID3v2FrameID.tflt: ID3v2TextInformationFormat.regular,
ID3v2FrameID.tipl: ID3v2TextInformationFormat.regular,
ID3v2FrameID.time: ID3v2TextInformationFormat.regular,
ID3v2FrameID.tit1: ID3v2TextInformationFormat.regular,
ID3v2FrameID.tit2: ID3v2TextInformationFormat.regular,
ID3v2FrameID.tit3: ID3v2TextInformationFormat.regular,
ID3v2FrameID.tkey: ID3v2TextInformationFormat.regular,
ID3v2FrameID.tlan: ID3v2TextInformationFormat.regular,
ID3v2FrameID.tlen: ID3v2TextInformationFormat.regular,
ID3v2FrameID.tmcl: ID3v2TextInformationFormat.regular,
ID3v2FrameID.tmed: ID3v2TextInformationFormat.regular,
ID3v2FrameID.tmoo: ID3v2TextInformationFormat.regular,
ID3v2FrameID.toal: ID3v2TextInformationFormat.regular,
ID3v2FrameID.tofn: ID3v2TextInformationFormat.regular,
ID3v2FrameID.toly: ID3v2TextInformationFormat.regular,
ID3v2FrameID.tope: ID3v2TextInformationFormat.regular,
ID3v2FrameID.tory: ID3v2TextInformationFormat.regular,
ID3v2FrameID.town: ID3v2TextInformationFormat.regular,
ID3v2FrameID.tpe1: ID3v2TextInformationFormat.regular,
ID3v2FrameID.tpe2: ID3v2TextInformationFormat.regular,
ID3v2FrameID.tpe3: ID3v2TextInformationFormat.regular,
ID3v2FrameID.tpe4: ID3v2TextInformationFormat.regular,
ID3v2FrameID.tpos: ID3v2TextInformationFormat.regular,
ID3v2FrameID.tpro: ID3v2TextInformationFormat.regular,
ID3v2FrameID.tpub: ID3v2TextInformationFormat.regular,
ID3v2FrameID.trck: ID3v2TextInformationFormat.regular,
ID3v2FrameID.trda: ID3v2TextInformationFormat.regular,
ID3v2FrameID.trsn: ID3v2TextInformationFormat.regular,
ID3v2FrameID.trso: ID3v2TextInformationFormat.regular,
ID3v2FrameID.tsoa: ID3v2TextInformationFormat.regular,
ID3v2FrameID.tsop: ID3v2TextInformationFormat.regular,
ID3v2FrameID.tsot: ID3v2TextInformationFormat.regular,
ID3v2FrameID.tsiz: ID3v2TextInformationFormat.regular,
ID3v2FrameID.tsrc: ID3v2TextInformationFormat.regular,
ID3v2FrameID.tsse: ID3v2TextInformationFormat.regular,
ID3v2FrameID.tsst: ID3v2TextInformationFormat.regular,
ID3v2FrameID.tyer: ID3v2TextInformationFormat.regular,
ID3v2FrameID.txxx: ID3v2UserTextInformationFormat.regular,
ID3v2FrameID.wcom: ID3v2URLLinkFormat.regular,
ID3v2FrameID.wcop: ID3v2URLLinkFormat.regular,
ID3v2FrameID.woaf: ID3v2URLLinkFormat.regular,
ID3v2FrameID.woar: ID3v2URLLinkFormat.regular,
ID3v2FrameID.woas: ID3v2URLLinkFormat.regular,
ID3v2FrameID.wors: ID3v2URLLinkFormat.regular,
ID3v2FrameID.wpay: ID3v2URLLinkFormat.regular,
ID3v2FrameID.wpub: ID3v2URLLinkFormat.regular,
ID3v2FrameID.wxxx: ID3v2UserURLLinkFormat.regular,
ID3v2FrameID.user: ID3v2TermsOfUseFormat.regular,
ID3v2FrameID.uslt: ID3v2UnsyncedLyricsFormat.regular,
ID3v2FrameID.ufid: ID3v2UniqueFileIdentifierFormat.regular]
}
// MARK: Instance Methods
public func identifySignature(_ signature: [UInt8], version: ID3v2Version) -> ID3v2FrameID? {
guard !signature.isEmpty else {
return nil
}
for (_, customID) in self.customIDs {
if let customSignature = customID.signatures[version] {
if customSignature == signature {
return customID
}
}
}
for (_, nativeID) in self.nativeIDs {
if let nativeSignature = nativeID.signatures[version] {
if nativeSignature == signature {
return nativeID
}
}
}
if (version == ID3v2Version.v3) && (signature.count == 4) && (signature[3] == 0) {
let signaturePrefix = [UInt8](signature.prefix(3))
for (_, nativeID) in self.nativeIDs {
if let nativeSignature = nativeID.signatures[ID3v2Version.v2] {
if nativeSignature == signaturePrefix {
return nativeID
}
}
}
}
guard let identifier = String(bytes: signature, encoding: String.Encoding.isoLatin1) else {
return nil
}
return ID3v2FrameID(customID: identifier, signatures: [version: signature])
}
@discardableResult
public func registerCustomID(_ name: String, signatures: [ID3v2Version: [UInt8]]) -> ID3v2FrameID? {
guard self.customIDs[name] == nil else {
return nil
}
for (version, signature) in signatures {
for (_, customID) in self.customIDs {
if let customSignature = customID.signatures[version] {
guard customSignature != signature else {
return nil
}
}
}
}
guard let customID = ID3v2FrameID(customID: name, signatures: signatures) else {
return nil
}
self.customIDs[name] = customID
return customID
}
@discardableResult
public func registerStuff(format: ID3v2FrameStuffFormat, identifier: ID3v2FrameID) -> Bool {
guard self.stuffs[identifier] == nil else {
return false
}
self.stuffs[identifier] = format
return true
}
}
| mit | 667266fb086d038339c54167f45b30df | 38.686335 | 104 | 0.630331 | 3.369101 | false | false | false | false |
belatrix/iOSAllStarsRemake | AllStars/AllStars/iPhone/Classes/SignUp/SignUpViewController.swift | 1 | 2285 | //
// SignUpViewController.swift
// AllStars
//
// Created by Flavio Franco Tunqui on 5/31/16.
// Copyright © 2016 Belatrix SF. All rights reserved.
//
import UIKit
class SignUpViewController: UIViewController, UITextFieldDelegate {
@IBOutlet weak var edtEmail : UITextField!
@IBOutlet weak var actRegister : UIActivityIndicatorView!
@IBOutlet weak var imgRegister : UIImageView!
@IBOutlet weak var viewEdtEmail : UIView!
@IBOutlet weak var btnRegister : UIButton!
override func viewDidLoad() {
super.viewDidLoad()
setViews()
}
// MARK: - UI
func setViews() {
viewEdtEmail.backgroundColor = UIColor.colorPrimary()
btnRegister.backgroundColor = UIColor.colorPrimary()
let image = UIImage(named: "mail")
imgRegister.image = image?.imageWithRenderingMode(.AlwaysTemplate)
imgRegister.tintColor = UIColor.colorPrimary()
}
func lockScreen() {
self.view.userInteractionEnabled = false
self.actRegister.startAnimating()
}
func unlockScreen() {
self.view.userInteractionEnabled = true
self.actRegister.stopAnimating()
}
// MARK: - IBActions
@IBAction func btnRegisterTUI(sender: UIButton) {
self.view.endEditing(true)
self.createUser(edtEmail.text!)
}
@IBAction func btnBackTUI(sender: UIButton) {
self.view.endEditing(true)
self.dismissViewControllerAnimated(true, completion: nil)
}
@IBAction func tapCloseKeyboard(sender: AnyObject) {
self.view.endEditing(true)
}
// MARK: - WebServices
func createUser(email : String) -> Void {
lockScreen()
SignUpBC.createUser(email) { (successful) in
self.unlockScreen()
if (successful) {
self.dismissViewControllerAnimated(true, completion: nil)
}
}
}
// MARK: - UITextFieldDelegate
func textFieldShouldReturn(textField: UITextField) -> Bool {
textField.resignFirstResponder()
self.createUser(edtEmail.text!)
return true
}
} | mit | ab99898ae1147074534a84ac29a00f0f | 26.202381 | 74 | 0.602014 | 5.041943 | false | false | false | false |
apple/swift-nio | Sources/NIOCore/SocketAddresses.swift | 1 | 30350 | //===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftNIO open source project
//
// Copyright (c) 2017-2021 Apple Inc. and the SwiftNIO project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
#if os(Windows)
import ucrt
import let WinSDK.AF_INET
import let WinSDK.AF_INET6
import let WinSDK.INET_ADDRSTRLEN
import let WinSDK.INET6_ADDRSTRLEN
import func WinSDK.FreeAddrInfoW
import func WinSDK.GetAddrInfoW
import struct WinSDK.ADDRESS_FAMILY
import struct WinSDK.ADDRINFOW
import struct WinSDK.IN_ADDR
import struct WinSDK.IN6_ADDR
import struct WinSDK.sockaddr
import struct WinSDK.sockaddr_in
import struct WinSDK.sockaddr_in6
import struct WinSDK.sockaddr_storage
import struct WinSDK.sockaddr_un
import typealias WinSDK.u_short
fileprivate typealias in_addr = WinSDK.IN_ADDR
fileprivate typealias in6_addr = WinSDK.IN6_ADDR
fileprivate typealias in_port_t = WinSDK.u_short
fileprivate typealias sa_family_t = WinSDK.ADDRESS_FAMILY
#elseif os(macOS) || os(iOS) || os(tvOS) || os(watchOS)
import Darwin
#elseif os(Linux) || os(FreeBSD) || os(Android)
import Glibc
import CNIOLinux
#endif
/// Special `Error` that may be thrown if we fail to create a `SocketAddress`.
public enum SocketAddressError: Error {
/// The host is unknown (could not be resolved).
case unknown(host: String, port: Int)
/// The requested `SocketAddress` is not supported.
case unsupported
/// The requested UDS path is too long.
case unixDomainSocketPathTooLong
/// Unable to parse a given IP string
case failedToParseIPString(String)
}
extension SocketAddressError {
/// Unable to parse a given IP ByteBuffer
public struct FailedToParseIPByteBuffer: Error, Hashable {
public var address: ByteBuffer
public init(address: ByteBuffer) {
self.address = address
}
}
}
/// Represent a socket address to which we may want to connect or bind.
public enum SocketAddress: CustomStringConvertible, Sendable {
/// A single IPv4 address for `SocketAddress`.
public struct IPv4Address {
private let _storage: Box<(address: sockaddr_in, host: String)>
/// The libc socket address for an IPv4 address.
public var address: sockaddr_in { return _storage.value.address }
/// The host this address is for, if known.
public var host: String { return _storage.value.host }
fileprivate init(address: sockaddr_in, host: String) {
self._storage = Box((address: address, host: host))
}
}
/// A single IPv6 address for `SocketAddress`.
public struct IPv6Address {
private let _storage: Box<(address: sockaddr_in6, host: String)>
/// The libc socket address for an IPv6 address.
public var address: sockaddr_in6 { return _storage.value.address }
/// The host this address is for, if known.
public var host: String { return _storage.value.host }
fileprivate init(address: sockaddr_in6, host: String) {
self._storage = Box((address: address, host: host))
}
}
/// A single Unix socket address for `SocketAddress`.
public struct UnixSocketAddress: Sendable {
private let _storage: Box<sockaddr_un>
/// The libc socket address for a Unix Domain Socket.
public var address: sockaddr_un { return _storage.value }
fileprivate init(address: sockaddr_un) {
self._storage = Box(address)
}
}
/// An IPv4 `SocketAddress`.
case v4(IPv4Address)
/// An IPv6 `SocketAddress`.
case v6(IPv6Address)
/// An UNIX Domain `SocketAddress`.
case unixDomainSocket(UnixSocketAddress)
/// A human-readable description of this `SocketAddress`. Mostly useful for logging.
public var description: String {
let addressString: String
let port: String
let host: String?
let type: String
switch self {
case .v4(let addr):
host = addr.host.isEmpty ? nil : addr.host
type = "IPv4"
var mutAddr = addr.address.sin_addr
// this uses inet_ntop which is documented to only fail if family is not AF_INET or AF_INET6 (or ENOSPC)
addressString = try! descriptionForAddress(family: .inet, bytes: &mutAddr, length: Int(INET_ADDRSTRLEN))
port = "\(self.port!)"
case .v6(let addr):
host = addr.host.isEmpty ? nil : addr.host
type = "IPv6"
var mutAddr = addr.address.sin6_addr
// this uses inet_ntop which is documented to only fail if family is not AF_INET or AF_INET6 (or ENOSPC)
addressString = try! descriptionForAddress(family: .inet6, bytes: &mutAddr, length: Int(INET6_ADDRSTRLEN))
port = "\(self.port!)"
case .unixDomainSocket(_):
host = nil
type = "UDS"
return "[\(type)]\(self.pathname ?? "")"
}
return "[\(type)]\(host.map { "\($0)/\(addressString):" } ?? "\(addressString):")\(port)"
}
@available(*, deprecated, renamed: "SocketAddress.protocol")
public var protocolFamily: Int32 {
return Int32(self.protocol.rawValue)
}
/// Returns the protocol family as defined in `man 2 socket` of this `SocketAddress`.
public var `protocol`: NIOBSDSocket.ProtocolFamily {
switch self {
case .v4:
return .inet
case .v6:
return .inet6
case .unixDomainSocket:
return .unix
}
}
/// Get the IP address as a string
public var ipAddress: String? {
switch self {
case .v4(let addr):
var mutAddr = addr.address.sin_addr
// this uses inet_ntop which is documented to only fail if family is not AF_INET or AF_INET6 (or ENOSPC)
return try! descriptionForAddress(family: .inet, bytes: &mutAddr, length: Int(INET_ADDRSTRLEN))
case .v6(let addr):
var mutAddr = addr.address.sin6_addr
// this uses inet_ntop which is documented to only fail if family is not AF_INET or AF_INET6 (or ENOSPC)
return try! descriptionForAddress(family: .inet6, bytes: &mutAddr, length: Int(INET6_ADDRSTRLEN))
case .unixDomainSocket(_):
return nil
}
}
/// Get and set the port associated with the address, if defined.
/// When setting to `nil` the port will default to `0` for compatible sockets. The rationale for this is that both `nil` and `0` can
/// be interpreted as "no preference".
/// Setting a non-nil value for a unix domain socket is invalid and will result in a fatal error.
public var port: Int? {
get {
switch self {
case .v4(let addr):
// looks odd but we need to first convert the endianness as `in_port_t` and then make the result an `Int`.
return Int(in_port_t(bigEndian: addr.address.sin_port))
case .v6(let addr):
// looks odd but we need to first convert the endianness as `in_port_t` and then make the result an `Int`.
return Int(in_port_t(bigEndian: addr.address.sin6_port))
case .unixDomainSocket:
return nil
}
}
set {
switch self {
case .v4(let addr):
var mutAddr = addr.address
mutAddr.sin_port = in_port_t(newValue ?? 0).bigEndian
self = .v4(.init(address: mutAddr, host: addr.host))
case .v6(let addr):
var mutAddr = addr.address
mutAddr.sin6_port = in_port_t(newValue ?? 0).bigEndian
self = .v6(.init(address: mutAddr, host: addr.host))
case .unixDomainSocket:
precondition(newValue == nil, "attempting to set a non-nil value to a unix socket is not valid")
}
}
}
/// Get the pathname of a UNIX domain socket as a string
public var pathname: String? {
switch self {
case .v4:
return nil
case .v6:
return nil
case .unixDomainSocket(let addr):
// This is a static assert that exists just to verify the safety of the assumption below.
assert(Swift.type(of: addr.address.sun_path.0) == CChar.self)
let pathname: String = withUnsafePointer(to: addr.address.sun_path) { ptr in
// Homogeneous tuples are always implicitly also bound to their element type, so this assumption below is safe.
let charPtr = UnsafeRawPointer(ptr).assumingMemoryBound(to: CChar.self)
return String(cString: charPtr)
}
return pathname
}
}
/// Calls the given function with a pointer to a `sockaddr` structure and the associated size
/// of that structure.
public func withSockAddr<T>(_ body: (UnsafePointer<sockaddr>, Int) throws -> T) rethrows -> T {
switch self {
case .v4(let addr):
return try addr.address.withSockAddr({ try body($0, $1) })
case .v6(let addr):
return try addr.address.withSockAddr({ try body($0, $1) })
case .unixDomainSocket(let addr):
return try addr.address.withSockAddr({ try body($0, $1) })
}
}
/// Creates a new IPv4 `SocketAddress`.
///
/// - parameters:
/// - addr: the `sockaddr_in` that holds the ipaddress and port.
/// - host: the hostname that resolved to the ipaddress.
public init(_ addr: sockaddr_in, host: String) {
self = .v4(.init(address: addr, host: host))
}
/// Creates a new IPv6 `SocketAddress`.
///
/// - parameters:
/// - addr: the `sockaddr_in` that holds the ipaddress and port.
/// - host: the hostname that resolved to the ipaddress.
public init(_ addr: sockaddr_in6, host: String) {
self = .v6(.init(address: addr, host: host))
}
/// Creates a new IPv4 `SocketAddress`.
///
/// - parameters:
/// - addr: the `sockaddr_in` that holds the ipaddress and port.
public init(_ addr: sockaddr_in) {
self = .v4(.init(address: addr, host: addr.addressDescription()))
}
/// Creates a new IPv6 `SocketAddress`.
///
/// - parameters:
/// - addr: the `sockaddr_in` that holds the ipaddress and port.
public init(_ addr: sockaddr_in6) {
self = .v6(.init(address: addr, host: addr.addressDescription()))
}
/// Creates a new Unix Domain Socket `SocketAddress`.
///
/// - parameters:
/// - addr: the `sockaddr_un` that holds the socket path.
public init(_ addr: sockaddr_un) {
self = .unixDomainSocket(.init(address: addr))
}
/// Creates a new UDS `SocketAddress`.
///
/// - parameters:
/// - path: the path to use for the `SocketAddress`.
/// - returns: the `SocketAddress` for the given path.
/// - throws: may throw `SocketAddressError.unixDomainSocketPathTooLong` if the path is too long.
public init(unixDomainSocketPath: String) throws {
guard unixDomainSocketPath.utf8.count <= 103 else {
throw SocketAddressError.unixDomainSocketPathTooLong
}
let pathBytes = unixDomainSocketPath.utf8 + [0]
var addr = sockaddr_un()
addr.sun_family = sa_family_t(NIOBSDSocket.AddressFamily.unix.rawValue)
pathBytes.withUnsafeBytes { srcBuffer in
withUnsafeMutableBytes(of: &addr.sun_path) { dstPtr in
dstPtr.copyMemory(from: srcBuffer)
}
}
self = .unixDomainSocket(.init(address: addr))
}
/// Create a new `SocketAddress` for an IP address in string form.
///
/// - parameters:
/// - string: The IP address, in string form.
/// - port: The target port.
/// - returns: the `SocketAddress` corresponding to this string and port combination.
/// - throws: may throw `SocketAddressError.failedToParseIPString` if the IP address cannot be parsed.
public init(ipAddress: String, port: Int) throws {
self = try ipAddress.withCString {
do {
var ipv4Addr = in_addr()
try NIOBSDSocket.inet_pton(addressFamily: .inet, addressDescription: $0, address: &ipv4Addr)
var addr = sockaddr_in()
addr.sin_family = sa_family_t(NIOBSDSocket.AddressFamily.inet.rawValue)
addr.sin_port = in_port_t(port).bigEndian
addr.sin_addr = ipv4Addr
return .v4(.init(address: addr, host: ""))
} catch {
// If `inet_pton` fails as an IPv4 address, we will try as an
// IPv6 address.
}
do {
var ipv6Addr = in6_addr()
try NIOBSDSocket.inet_pton(addressFamily: .inet6, addressDescription: $0, address: &ipv6Addr)
var addr = sockaddr_in6()
addr.sin6_family = sa_family_t(NIOBSDSocket.AddressFamily.inet6.rawValue)
addr.sin6_port = in_port_t(port).bigEndian
addr.sin6_flowinfo = 0
addr.sin6_addr = ipv6Addr
addr.sin6_scope_id = 0
return .v6(.init(address: addr, host: ""))
} catch {
// If `inet_pton` fails as an IPv6 address (and has failed as an
// IPv4 address above), we will throw an error below.
}
throw SocketAddressError.failedToParseIPString(ipAddress)
}
}
/// Create a new `SocketAddress` for an IP address in ByteBuffer form.
///
/// - parameters:
/// - packedIPAddress: The IP address, in ByteBuffer form.
/// - port: The target port.
/// - returns: the `SocketAddress` corresponding to this string and port combination.
/// - throws: may throw `SocketAddressError.failedToParseIPByteBuffer` if the IP address cannot be parsed.
public init(packedIPAddress: ByteBuffer, port: Int) throws {
let packed = packedIPAddress.readableBytesView
switch packedIPAddress.readableBytes {
case 4:
var ipv4Addr = sockaddr_in()
ipv4Addr.sin_family = sa_family_t(AF_INET)
ipv4Addr.sin_port = in_port_t(port).bigEndian
withUnsafeMutableBytes(of: &ipv4Addr.sin_addr) { $0.copyBytes(from: packed) }
self = .v4(.init(address: ipv4Addr, host: ""))
case 16:
var ipv6Addr = sockaddr_in6()
ipv6Addr.sin6_family = sa_family_t(AF_INET6)
ipv6Addr.sin6_port = in_port_t(port).bigEndian
withUnsafeMutableBytes(of: &ipv6Addr.sin6_addr) { $0.copyBytes(from: packed) }
self = .v6(.init(address: ipv6Addr, host: ""))
default:
throw SocketAddressError.FailedToParseIPByteBuffer(address: packedIPAddress)
}
}
/// Creates a new `SocketAddress` corresponding to the netmask for a subnet prefix.
///
/// As an example, consider the subnet "127.0.0.1/8". The "subnet prefix" is "8", and the corresponding netmask is "255.0.0.0".
/// This initializer will produce a `SocketAddress` that contains "255.0.0.0".
///
/// - parameters:
/// - prefix: The prefix of the subnet.
/// - returns: A `SocketAddress` containing the associated netmask.
internal init(ipv4MaskForPrefix prefix: Int) {
precondition((0...32).contains(prefix))
let packedAddress = (UInt32(0xFFFFFFFF) << (32 - prefix)).bigEndian
var ipv4Addr = sockaddr_in()
ipv4Addr.sin_family = sa_family_t(AF_INET)
ipv4Addr.sin_port = 0
withUnsafeMutableBytes(of: &ipv4Addr.sin_addr) { $0.storeBytes(of: packedAddress, as: UInt32.self) }
self = .v4(.init(address: ipv4Addr, host: ""))
}
/// Creates a new `SocketAddress` corresponding to the netmask for a subnet prefix.
///
/// As an example, consider the subnet "fe80::/10". The "subnet prefix" is "10", and the corresponding netmask is "ff30::".
/// This initializer will produce a `SocketAddress` that contains "ff30::".
///
/// - parameters:
/// - prefix: The prefix of the subnet.
/// - returns: A `SocketAddress` containing the associated netmask.
internal init(ipv6MaskForPrefix prefix: Int) {
precondition((0...128).contains(prefix))
// This defends against the possibility of a greater-than-/64 subnet, which would produce a negative shift
// operand which is absolutely not what we want.
let highShift = min(prefix, 64)
let packedAddressHigh = (UInt64(0xFFFFFFFFFFFFFFFF) << (64 - highShift)).bigEndian
let packedAddressLow = (UInt64(0xFFFFFFFFFFFFFFFF) << (128 - prefix)).bigEndian
let packedAddress = (packedAddressHigh, packedAddressLow)
var ipv6Addr = sockaddr_in6()
ipv6Addr.sin6_family = sa_family_t(AF_INET6)
ipv6Addr.sin6_port = 0
withUnsafeMutableBytes(of: &ipv6Addr.sin6_addr) { $0.storeBytes(of: packedAddress, as: (UInt64, UInt64).self) }
self = .v6(.init(address: ipv6Addr, host: ""))
}
/// Creates a new `SocketAddress` for the given host (which will be resolved) and port.
///
/// - warning: This is a blocking call, so please avoid calling this from an `EventLoop`.
///
/// - parameters:
/// - host: the hostname which should be resolved.
/// - port: the port itself
/// - returns: the `SocketAddress` for the host / port pair.
/// - throws: a `SocketAddressError.unknown` if we could not resolve the `host`, or `SocketAddressError.unsupported` if the address itself is not supported (yet).
public static func makeAddressResolvingHost(_ host: String, port: Int) throws -> SocketAddress {
#if os(Windows)
return try host.withCString(encodedAs: UTF16.self) { wszHost in
return try String(port).withCString(encodedAs: UTF16.self) { wszPort in
var pResult: UnsafeMutablePointer<ADDRINFOW>?
guard GetAddrInfoW(wszHost, wszPort, nil, &pResult) == 0 else {
throw SocketAddressError.unknown(host: host, port: port)
}
defer {
FreeAddrInfoW(pResult)
}
if let pResult = pResult, let addressBytes = UnsafeRawPointer(pResult.pointee.ai_addr) {
switch pResult.pointee.ai_family {
case AF_INET:
return .v4(IPv4Address(address: addressBytes.load(as: sockaddr_in.self), host: host))
case AF_INET6:
return .v6(IPv6Address(address: addressBytes.load(as: sockaddr_in6.self), host: host))
default:
break
}
}
throw SocketAddressError.unsupported
}
}
#else
var info: UnsafeMutablePointer<addrinfo>?
/* FIXME: this is blocking! */
if getaddrinfo(host, String(port), nil, &info) != 0 {
throw SocketAddressError.unknown(host: host, port: port)
}
defer {
if info != nil {
freeaddrinfo(info)
}
}
if let info = info, let addrPointer = info.pointee.ai_addr {
let addressBytes = UnsafeRawPointer(addrPointer)
switch NIOBSDSocket.AddressFamily(rawValue: info.pointee.ai_family) {
case .inet:
return .v4(.init(address: addressBytes.load(as: sockaddr_in.self), host: host))
case .inet6:
return .v6(.init(address: addressBytes.load(as: sockaddr_in6.self), host: host))
default:
throw SocketAddressError.unsupported
}
} else {
/* this is odd, getaddrinfo returned NULL */
throw SocketAddressError.unsupported
}
#endif
}
}
/// We define an extension on `SocketAddress` that gives it an elementwise equatable conformance, using
/// only the elements defined on the structure in their man pages (excluding lengths).
extension SocketAddress: Equatable {
public static func ==(lhs: SocketAddress, rhs: SocketAddress) -> Bool {
switch (lhs, rhs) {
case (.v4(let addr1), .v4(let addr2)):
#if os(Windows)
return addr1.address.sin_family == addr2.address.sin_family &&
addr1.address.sin_port == addr2.address.sin_port &&
addr1.address.sin_addr.S_un.S_addr == addr2.address.sin_addr.S_un.S_addr
#else
return addr1.address.sin_family == addr2.address.sin_family &&
addr1.address.sin_port == addr2.address.sin_port &&
addr1.address.sin_addr.s_addr == addr2.address.sin_addr.s_addr
#endif
case (.v6(let addr1), .v6(let addr2)):
guard addr1.address.sin6_family == addr2.address.sin6_family &&
addr1.address.sin6_port == addr2.address.sin6_port &&
addr1.address.sin6_flowinfo == addr2.address.sin6_flowinfo &&
addr1.address.sin6_scope_id == addr2.address.sin6_scope_id else {
return false
}
var s6addr1 = addr1.address.sin6_addr
var s6addr2 = addr2.address.sin6_addr
return memcmp(&s6addr1, &s6addr2, MemoryLayout.size(ofValue: s6addr1)) == 0
case (.unixDomainSocket(let addr1), .unixDomainSocket(let addr2)):
guard addr1.address.sun_family == addr2.address.sun_family else {
return false
}
let bufferSize = MemoryLayout.size(ofValue: addr1.address.sun_path)
// Swift implicitly binds the memory for homogeneous tuples to both the tuple type and the element type.
// This allows us to use assumingMemoryBound(to:) for managing the types. However, we add a static assertion here to validate
// that the element type _really is_ what we're assuming it to be.
assert(Swift.type(of: addr1.address.sun_path.0) == CChar.self)
assert(Swift.type(of: addr2.address.sun_path.0) == CChar.self)
return withUnsafePointer(to: addr1.address.sun_path) { sunpath1 in
return withUnsafePointer(to: addr2.address.sun_path) { sunpath2 in
let typedSunpath1 = UnsafeRawPointer(sunpath1).assumingMemoryBound(to: CChar.self)
let typedSunpath2 = UnsafeRawPointer(sunpath2).assumingMemoryBound(to: CChar.self)
return strncmp(typedSunpath1, typedSunpath2, bufferSize) == 0
}
}
case (.v4, _), (.v6, _), (.unixDomainSocket, _):
return false
}
}
}
extension SocketAddress.IPv4Address: Sendable {}
extension SocketAddress.IPv6Address: Sendable {}
/// We define an extension on `SocketAddress` that gives it an elementwise hashable conformance, using
/// only the elements defined on the structure in their man pages (excluding lengths).
extension SocketAddress: Hashable {
public func hash(into hasher: inout Hasher) {
switch self {
case .unixDomainSocket(let uds):
hasher.combine(0)
hasher.combine(uds.address.sun_family)
let pathSize = MemoryLayout.size(ofValue: uds.address.sun_path)
// Swift implicitly binds the memory of homogeneous tuples to both the tuple type and the element type.
// We can therefore use assumingMemoryBound(to:) for pointer type conversion. We add a static assert just to
// validate that we are actually right about the element type.
assert(Swift.type(of: uds.address.sun_path.0) == CChar.self)
withUnsafePointer(to: uds.address.sun_path) { pathPtr in
let typedPathPointer = UnsafeRawPointer(pathPtr).assumingMemoryBound(to: CChar.self)
let length = strnlen(typedPathPointer, pathSize)
let bytes = UnsafeRawBufferPointer(start: UnsafeRawPointer(typedPathPointer), count: length)
hasher.combine(bytes: bytes)
}
case .v4(let v4Addr):
hasher.combine(1)
hasher.combine(v4Addr.address.sin_family)
hasher.combine(v4Addr.address.sin_port)
#if os(Windows)
hasher.combine(v4Addr.address.sin_addr.S_un.S_addr)
#else
hasher.combine(v4Addr.address.sin_addr.s_addr)
#endif
case .v6(let v6Addr):
hasher.combine(2)
hasher.combine(v6Addr.address.sin6_family)
hasher.combine(v6Addr.address.sin6_port)
hasher.combine(v6Addr.address.sin6_flowinfo)
hasher.combine(v6Addr.address.sin6_scope_id)
withUnsafeBytes(of: v6Addr.address.sin6_addr) {
hasher.combine(bytes: $0)
}
}
}
}
extension SocketAddress {
/// Whether this `SocketAddress` corresponds to a multicast address.
public var isMulticast: Bool {
switch self {
case .unixDomainSocket:
// No multicast on unix sockets.
return false
case .v4(let v4Addr):
// For IPv4 a multicast address is in the range 224.0.0.0/4.
// The easy way to check if this is the case is to just mask off
// the address.
#if os(Windows)
let v4WireAddress = v4Addr.address.sin_addr.S_un.S_addr
let mask = UInt32(0xF000_0000).bigEndian
let subnet = UInt32(0xE000_0000).bigEndian
#else
let v4WireAddress = v4Addr.address.sin_addr.s_addr
let mask = in_addr_t(0xF000_0000 as UInt32).bigEndian
let subnet = in_addr_t(0xE000_0000 as UInt32).bigEndian
#endif
return v4WireAddress & mask == subnet
case .v6(let v6Addr):
// For IPv6 a multicast address is in the range ff00::/8.
// Here we don't need a bitmask, as all the top bits are set,
// so we can just ask for equality on the top byte.
var v6WireAddress = v6Addr.address.sin6_addr
return withUnsafeBytes(of: &v6WireAddress) { $0[0] == 0xff }
}
}
}
protocol SockAddrProtocol {
func withSockAddr<R>(_ body: (UnsafePointer<sockaddr>, Int) throws -> R) rethrows -> R
}
/// Returns a description for the given address.
internal func descriptionForAddress(family: NIOBSDSocket.AddressFamily, bytes: UnsafeRawPointer, length byteCount: Int) throws -> String {
var addressBytes: [Int8] = Array(repeating: 0, count: byteCount)
return try addressBytes.withUnsafeMutableBufferPointer { (addressBytesPtr: inout UnsafeMutableBufferPointer<Int8>) -> String in
try NIOBSDSocket.inet_ntop(addressFamily: family, addressBytes: bytes,
addressDescription: addressBytesPtr.baseAddress!,
addressDescriptionLength: socklen_t(byteCount))
return addressBytesPtr.baseAddress!.withMemoryRebound(to: UInt8.self, capacity: byteCount) { addressBytesPtr -> String in
String(cString: addressBytesPtr)
}
}
}
extension sockaddr_in: SockAddrProtocol {
func withSockAddr<R>(_ body: (UnsafePointer<sockaddr>, Int) throws -> R) rethrows -> R {
return try withUnsafeBytes(of: self) { p in
try body(p.baseAddress!.assumingMemoryBound(to: sockaddr.self), p.count)
}
}
/// Returns a description of the `sockaddr_in`.
func addressDescription() -> String {
return withUnsafePointer(to: self.sin_addr) { addrPtr in
// this uses inet_ntop which is documented to only fail if family is not AF_INET or AF_INET6 (or ENOSPC)
try! descriptionForAddress(family: .inet, bytes: addrPtr, length: Int(INET_ADDRSTRLEN))
}
}
}
extension sockaddr_in6: SockAddrProtocol {
func withSockAddr<R>(_ body: (UnsafePointer<sockaddr>, Int) throws -> R) rethrows -> R {
return try withUnsafeBytes(of: self) { p in
try body(p.baseAddress!.assumingMemoryBound(to: sockaddr.self), p.count)
}
}
/// Returns a description of the `sockaddr_in6`.
func addressDescription() -> String {
return withUnsafePointer(to: self.sin6_addr) { addrPtr in
// this uses inet_ntop which is documented to only fail if family is not AF_INET or AF_INET6 (or ENOSPC)
try! descriptionForAddress(family: .inet6, bytes: addrPtr, length: Int(INET6_ADDRSTRLEN))
}
}
}
extension sockaddr_un: SockAddrProtocol {
func withSockAddr<R>(_ body: (UnsafePointer<sockaddr>, Int) throws -> R) rethrows -> R {
return try withUnsafeBytes(of: self) { p in
try body(p.baseAddress!.assumingMemoryBound(to: sockaddr.self), p.count)
}
}
}
extension sockaddr_storage: SockAddrProtocol {
func withSockAddr<R>(_ body: (UnsafePointer<sockaddr>, Int) throws -> R) rethrows -> R {
return try withUnsafeBytes(of: self) { p in
try body(p.baseAddress!.assumingMemoryBound(to: sockaddr.self), p.count)
}
}
}
// MARK: Workarounds for SR-14268
// We need these free functions to expose our extension methods, because otherwise
// the compiler falls over when we try to access them from test code. As these functions
// exist purely to make the behaviours accessible from test code, we name them truly awfully.
func __testOnly_addressDescription(_ addr: sockaddr_in) -> String {
return addr.addressDescription()
}
func __testOnly_addressDescription(_ addr: sockaddr_in6) -> String {
return addr.addressDescription()
}
func __testOnly_withSockAddr<ReturnType>(
_ addr: sockaddr_in, _ body: (UnsafePointer<sockaddr>, Int) throws -> ReturnType
) rethrows -> ReturnType {
return try addr.withSockAddr(body)
}
func __testOnly_withSockAddr<ReturnType>(
_ addr: sockaddr_in6, _ body: (UnsafePointer<sockaddr>, Int) throws -> ReturnType
) rethrows -> ReturnType {
return try addr.withSockAddr(body)
}
| apache-2.0 | d5f111d9daceab784f247e81b7f6f6d6 | 40.68956 | 166 | 0.617364 | 4.154689 | false | false | false | false |
networklocum/sqweaks | Sqweaks/Sqweaks.swift | 1 | 2109 | /// A value type describing the value which is switched.
public protocol SwitchableType {
var id: String { get }
var description: String { get }
var defaultValue: Bool { get }
}
public final class Suite {
public let switches: [SwitchableType]
private var observers: [String : [(Bool) -> ()]]
private var currentSettings: [String:Bool] {
didSet {
self.dataSource?.sections = self.sections
}
}
public init(switches: [SwitchableType]) {
self.switches = switches
currentSettings = switches.map { sw -> (String, Bool) in
return (sw.id, sw.defaultValue)
}
.reduce([:]) { (var dict, tuple) in
dict[tuple.0] = tuple.1
return dict
}
self.observers = switches.map { sw in
return (sw.id, Array<Bool -> ()>())
}.reduce([:]) { (var dict, tuple) in
dict[tuple.0] = tuple.1
return dict
}
}
/// Add the observer and synchronously call it with the current value.
public func addObserverForSwitchID(id: String, observer: Bool -> ()) {
self.observers[id]!.append(observer)
observer(self.currentSettings[id]!)
}
internal func toggleSwitch(name: String) {
currentSettings[name] = !(currentSettings[name]!)
observers[name]!.forEach(apply(currentSettings[name]!))
}
internal var dataSource: DataSource? {
didSet {
dataSource?.sections = sections
}
}
}
private extension Suite {
var sections: [Section] {
return [Section(rows: self.switches.map { sw in
let on = self.currentSettings[sw.id]!
return Row(text: sw.description, accessory: on ? .Checkmark : .None, selection: {
self.toggleSwitch(sw.id)
})
})]
}
}
public struct Switch: SwitchableType {
public let id: String
public let defaultValue: Bool
public let description: String
public init(id: String, defaultValue: Bool, description: String) {
self.id = id
self.defaultValue = defaultValue
self.description = description
}
}
private func apply<T>(val: T) -> (closure: T -> ()) -> () {
return { closure in
closure(val)
}
}
import Static
| mit | 77ac826ac3f39eb594359dc0e9f73a5b | 26.75 | 87 | 0.638217 | 3.949438 | false | false | false | false |
WildDogTeam/demo-ios-officemover | OfficeMover5000/ViewController.swift | 1 | 3660 | //
// ViewController.swift
// OfficeMover500
//
// Created by Garin on 11/2/15.
// Copyright (c) 2015 Wilddog. All rights reserved.
//
import UIKit
import WilddogSync
//let OfficeMoverWilddogUrl = "https://<your-wilddog>.wilddogio.com"
let OfficeMoverWilddogUrl = "https://myofficemover.wilddogio.com"
let WilddogAppID = "myofficemover"
class ViewController: RoomViewController {
var ref : WDGSyncReference!
var furnitureRef : WDGSyncReference!
var backgroundRef : WDGSyncReference!
override func viewDidLoad() {
super.viewDidLoad()
ref = WDGSync.sync().reference()
furnitureRef = ref.child("furniture")
backgroundRef = ref.child("background")
// Load the furniture items from Wilddog
furnitureRef.observeEventType(.ChildAdded, withBlock: { [unowned self] snapshot in
self.refLocations += ["furniture/\(snapshot.key)"]
let furniture = Furniture(snap: snapshot)
self.createFurnitureView(furniture)
})
// Observe bacakground changes
backgroundRef.observeEventType(.Value, withBlock: { [unowned self] snapshot in
if let background = snapshot.value as? String {
self.setBackgroundLocally(background)
}
})
}
// This should take in a Furniture Model whatever that is.
// This creates a view as a button, and makes it draggable.
func createFurnitureView(furniture: Furniture) {
let view = FurnitureView(furniture: furniture)
let currentFurnitureRef = furnitureRef.childByAppendingPath(furniture.key)
// move the view from a remote update
currentFurnitureRef.observeEventType(.Value, withBlock: { snapshot in
if snapshot.exists() {
//TODO:
let furniture = Furniture(snap: snapshot)
view.setViewState(furniture)
} else {
view.delete()
}
})
// When the furniture moves, update the Wilddog
view.moveHandler = { top, left in
currentFurnitureRef.updateChildValues([
"top": top,
"left": left
])
}
// When the furniture rotates, update the Wilddog
view.rotateHandler = { top, left, rotation in
currentFurnitureRef.updateChildValues([
"top": top,
"left": left,
"rotation": rotation
])
}
// When the furniture is deleted, update the Wilddog
view.deleteHandler = {
view.delete()
currentFurnitureRef.removeValue()
}
// For desks, when we edit the name on the desk, update the Wilddog
view.editHandler = { name in
currentFurnitureRef.updateChildValues([
"name": name
])
}
// When furniture is moved, it should jump to the top
view.moveToTopHandler = {
currentFurnitureRef.updateChildValues([
"z-index": ++maxZIndex
])
}
roomView.addSubview(view)
}
// Handling adding a new item from the popover menu
func addNewItem(type: String) {
let itemRef = furnitureRef.childByAutoId()
let furniture = Furniture(key: itemRef.key, type: type)
itemRef.setValue(furniture.toJson())
}
// Handling changing the background from the popover menu
func setBackground(type: String) {
backgroundRef.setValue(type)
}
} | mit | a82ba4bef448e0f033f7ece1e43aa36d | 30.834783 | 90 | 0.58388 | 4.37799 | false | false | false | false |
xivol/MCS-V3-Mobile | assignments/task1/BattleShip.playground/Sources/Game/Ship.swift | 1 | 656 | import Foundation
//type of Ship
public typealias ShipLocation = [(xPos: Int, yPos: Int)]
public protocol Ship {
var alive: Bool { get }
func isHit(_ xPos: Int, yPos: Int) -> Bool
}
public class CombatShip: Ship {
var location: ShipLocation
var holeCount: Int
public var alive: Bool {
get {
return holeCount < location.count
}
}
public func isHit(_ xPos: Int, yPos: Int) -> Bool {
if location.index(where: { $0.xPos == xPos && $0.yPos == yPos }) != nil{
holeCount += 1
return true
}
return false
}
public init(_ location: ShipLocation) {
self.location = location
holeCount = 0
}
}
| mit | 025e8f18ecd662616f888796696100e6 | 19.5 | 76 | 0.615854 | 3.624309 | false | false | false | false |
XLabKC/Badger | Badger/Badger/TeamProfileViewController.swift | 1 | 6401 | import UIKit
class TeamProfileViewController: RevealableTableViewController {
private let cellHeights: [CGFloat] = [225.0, 100.0, 112.0]
private let memberAltBackground = Color.colorize(0xF6F6F6, alpha: 1.0)
private var team: Team?
private var members = [User]()
private var isLoadingMembers = true
private var headerCell: TeamHeaderCell?
private var controlCell: TeamProfileControlCell?
private var teamObserver: FirebaseObserver<Team>?
private var membersObserver: FirebaseListObserver<User>?
@IBOutlet weak var menuButton: UIBarButtonItem!
deinit {
self.teamObserver?.dispose()
self.membersObserver?.dispose()
}
override func viewDidLoad() {
super.viewDidLoad()
// Register loading cell.
let loadingCellNib = UINib(nibName: "LoadingCell", bundle: nil)
self.tableView.registerNib(loadingCellNib, forCellReuseIdentifier: "LoadingCell")
// Set up navigation bar.
let label = Helpers.createTitleLabel("Team Profile")
self.navigationItem.titleView = label
}
func setTeamId(id: String) {
// Create member list observer.
let usersRef = Firebase(url: Global.FirebaseUsersUrl)
self.membersObserver = FirebaseListObserver<User>(ref: usersRef, onChanged: self.membersUpdated)
self.membersObserver!.comparisonFunc = { (a, b) -> Bool in
return a.fullName < b.fullName
}
// Create user observer.
let teamRef = Team.createRef(id)
self.teamObserver = FirebaseObserver<Team>(query: teamRef, withBlock: { team in
self.team = team
if let membersObserver = self.membersObserver {
membersObserver.setKeys(team.memberIds.keys.array)
}
if self.isViewLoaded() {
let indexPath = NSIndexPath(forRow: 0, inSection: 0)
if let cell = self.tableView.cellForRowAtIndexPath(indexPath) as? TeamHeaderCell {
cell.setTeam(team)
}
}
// if !self.isViewLoaded() {
// self.tableView.cellForRowAtIndexPath(NSIndexPath(forRow: 2, inSection: 0))
// self.tableView.cellForRowAtIndexPath(NSIndexPath(forRow: 1, inSection: 2))
// }
})
}
private func membersUpdated(members: [User]) {
let oldMembers = self.members
self.members = members
self.isLoadingMembers = false
if !self.isViewLoaded() {
return
}
if oldMembers.isEmpty {
self.tableView.reloadSections(NSIndexSet(index: 1), withRowAnimation: .Left)
} else {
var updates = Helpers.diffArrays(oldMembers, end: members, section: 1, compare: { (a, b) -> Bool in
return a.uid == b.uid
})
if !updates.inserts.isEmpty || !updates.deletes.isEmpty {
self.tableView.beginUpdates()
self.tableView.deleteRowsAtIndexPaths(updates.deletes, withRowAnimation: .Left)
self.tableView.insertRowsAtIndexPaths(updates.inserts, withRowAnimation: .Left)
self.tableView.endUpdates()
}
// Loop through and update the users for each cell.
for (index, member) in enumerate(members) {
let indexPath = NSIndexPath(forRow: index, inSection: 1)
if let cell = self.tableView.cellForRowAtIndexPath(indexPath) as? TeamMemberCell {
cell.setUser(member)
}
}
}
}
// TableViewController Overrides
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 2
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
switch section {
case 0:
return 2
default:
return self.members.isEmpty ? 1 : self.members.count
}
}
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
switch indexPath.section {
case 0:
return self.cellHeights[indexPath.row]
default:
return self.cellHeights.last!
}
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
switch indexPath.section {
case 0:
if indexPath.row == 0 {
if self.headerCell == nil {
self.headerCell = (tableView.dequeueReusableCellWithIdentifier("TeamHeaderCell") as! TeamHeaderCell)
if let team = self.team {
self.headerCell!.setTeam(team)
}
}
return self.headerCell!
}
if self.controlCell == nil {
self.controlCell = (tableView.dequeueReusableCellWithIdentifier("TeamProfileControlCell") as! TeamProfileControlCell)
}
return self.controlCell!
default:
if self.isLoadingMembers {
return tableView.dequeueReusableCellWithIdentifier("LoadingCell") as! UITableViewCell
} else if self.members.count == 0 {
return tableView.dequeueReusableCellWithIdentifier("NoMembersCell") as! UITableViewCell
}
let cell = (tableView.dequeueReusableCellWithIdentifier("TeamMemberCell") as! TeamMemberCell)
cell.setUser(self.members[indexPath.row])
cell.backgroundColor = indexPath.row % 2 == 0 ? self.memberAltBackground : UIColor.whiteColor()
return cell
}
}
override func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 0
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "TeamProfileUser" {
let memberCell = sender as! TeamMemberCell
let vc = segue.destinationViewController as! ProfileViewController
vc.setUid(memberCell.getUser()!.uid)
} else if segue.identifier == "TeamProfileNewTask" {
let vc = segue.destinationViewController as! TaskEditViewController
if let team = self.team {
vc.setTeam(team)
}
}
}
}
| gpl-2.0 | 20800fa0d152de35f58ec6d4d25d51ed | 37.793939 | 133 | 0.61381 | 5.170436 | false | false | false | false |
ezefranca/Rocket.Chat.iOS | Rocket.Chat.iOS/User.swift | 1 | 2471 | //
// User.swift
// Rocket.Chat.iOS
//
// Created by Mobile Apps on 8/5/15.
// Copyright © 2015 Rocket.Chat. All rights reserved.
//
import Foundation
import CoreData
class User : NSManagedObject {
/// Status of the `User`
/// This uses raw values, in order to facilitate CoreData
enum Status : Int16{
case ONLINE = 0
case AWAY = 1
case BUSY = 2
case INVISIBLE = 3
}
@NSManaged dynamic var id : String
@NSManaged dynamic var username : String
@NSManaged dynamic var password : String? //Password is only for the local user, not remote
/// Avatar url or image name.
/// In case this is not a url the code calling must know how to construct the url
@NSManaged dynamic var avatar : String
/// This is to make CoreData work, since it doesn't support enums
/// We store this private int to CoreData and use `status` for public usage
@NSManaged dynamic private var statusVal : NSNumber
var status : Status {
get {
return Status(rawValue: statusVal.shortValue) ?? .ONLINE
}
set {
//self.statusVal = NSNumber(short: newValue.rawValue)
setValue(NSNumber(short: newValue.rawValue), forKey: "statusVal")
}
}
@NSManaged dynamic var statusMessage : String?
@NSManaged dynamic private var timezoneVal : String
var timezone : NSTimeZone {
get {
return NSTimeZone(name: timezoneVal) ?? NSTimeZone.systemTimeZone()
}
set {
self.timezoneVal = newValue.name
}
}
convenience init(context: NSManagedObjectContext, id:String, username:String, avatar:String, status : Status, timezone : NSTimeZone){
let entity = NSEntityDescription.entityForName("User", inManagedObjectContext: context)!
self.init(entity: entity, insertIntoManagedObjectContext: context)
self.id = id
self.username = username
self.avatar = avatar
//TODO: Setting status hear will cause an exception, come back later and check why (probably swift/compiler bug)
//self.status = status
setValue(NSNumber(short: status.rawValue), forKey: "statusVal")
self.timezoneVal = timezone.name
}
//For Hashable
override var hashValue : Int {
return id.hashValue
}
}
//For Equalable (part of Hashable)
func == (left : User, right: User) -> Bool {
return left.id == right.id
}
| mit | 4347543de587fcefd520a3f49c9f01c6 | 32.378378 | 137 | 0.642105 | 4.540441 | false | false | false | false |
jphacks/KB_01 | jphacks/ViewController/SearchViewController/SearchHeaderView.swift | 1 | 1266 | //
// SearchHeaderView.swift
// jphacks
//
// Created by SakuragiYoshimasa on 2015/11/28.
// Copyright © 2015年 at. All rights reserved.
//
import Foundation
import UIKit
class SearchHeaderView : UIView {
var labelImage: UIImageView!
var settingButton: UIButton!
func setup(frame: CGRect){
self.bounds = frame
self.frame = frame
self.backgroundColor = UIColor.colorFromRGB("4caf50", alpha: 1.0)
if labelImage == nil {
labelImage = UIImageView()
labelImage.image = UIImage(named: "logo_search")
labelImage.frame = CGRectMake(self.frame.maxX / 2 - 70, self.bounds.minY + 6, 140, self.bounds.height - 12)
labelImage.contentMode = UIViewContentMode.Center
self.addSubview(labelImage)
}
if settingButton == nil {
settingButton = UIButton()
settingButton.frame = CGRectMake(self.frame.maxX - 50, self.bounds.minY + 10, self.bounds.height - 16, self.bounds.height - 16)
settingButton.setBackgroundImage(UIImage(named: "setting"), forState: .Normal)
settingButton.contentMode = UIViewContentMode.ScaleAspectFill
//self.addSubview(settingButton)
}
}
} | mit | 18082370d39c47ec3e1437af53f748fc | 33.162162 | 140 | 0.631829 | 4.281356 | false | false | false | false |
slavapestov/swift | test/Reflection/Inputs/GenericTypes.swift | 1 | 4399 | public class C1<T> {
public typealias Function = C1<T> -> S1<T> -> E1<T> -> Int
public typealias Tuple = (C1<T>, S1<T>, E1<T>, Int)
public let aClass: C1<T>
public let aStruct: S1<T>
public let anEnum: E1<T>
public let function: Function
public let tuple: Tuple
public let dependentMember: T
public init(aClass: C1<T>, aStruct: S1<T>, anEnum: E1<T>, function: Function, tuple: Tuple, dependentMember: T) {
self.aClass = aClass
self.aStruct = aStruct
self.anEnum = anEnum
self.function = function
self.tuple = tuple
self.dependentMember = dependentMember
}
}
public class C2<T: P1> {
public typealias Function = C1<T> -> S1<T> -> E1<T> -> Int
public typealias Tuple = (C2<T>, S2<T>, E2<T>, Int)
public let aClass: C1<T>
public let aStruct: S1<T>
public let anEnum: E1<T>
public let function: Function
public let tuple: Tuple
public let primaryArchetype: T
public let dependentMember1: T.Inner
public init(aClass: C1<T>, aStruct: S1<T>, anEnum: E1<T>, function: Function, tuple: Tuple, primaryArchetype: T, dependentMember1: T.Inner) {
self.aClass = aClass
self.aStruct = aStruct
self.anEnum = anEnum
self.function = function
self.tuple = tuple
self.primaryArchetype = primaryArchetype
self.dependentMember1 = dependentMember1
}
}
public class C3<T: P2> {
public typealias Function = C3<T> -> S3<T> -> E3<T> -> Int
public typealias Tuple = (C3<T>, S3<T>, E3<T>, Int)
public let aClass: C3<T>
public let aStruct: S3<T>
public let anEnum: E3<T>
public let function: C3<T> -> S3<T> -> E3<T> -> Int
public let tuple: (C3<T>, S3<T>, E3<T>, Int)
public let primaryArchetype: T
public let dependentMember1: T.Outer
public let dependentMember2: T.Outer.Inner
public init(aClass: C3<T>, aStruct: S3<T>, anEnum: E3<T>, function: Function, tuple: Tuple, primaryArchetype: T, dependentMember1: T.Outer, dependentMember2: T.Outer.Inner) {
self.aClass = aClass
self.aStruct = aStruct
self.anEnum = anEnum
self.function = function
self.tuple = tuple
self.primaryArchetype = primaryArchetype
self.dependentMember1 = dependentMember1
self.dependentMember2 = dependentMember2
}
}
public struct S1<T> {
public let aClass: C1<T>
public let aStruct: Box<S1<T>>
public let anEnum: Box<E1<T>>
public let function: C1<T> -> S1<T> -> E1<T> -> Int
public let tuple: (C1<T>, Box<S1<T>>, Box<E1<T>>, Int)
public let primaryArchetype: T
}
public struct S2<T: P1> {
public let aClass: C2<T>
public let aStruct: Box<S2<T>>
public let anEnum: Box<E2<T>>
public let function: C2<T> -> S2<T> -> E2<T> -> Int
public let tuple: (C2<T>, Box<S2<T>>, Box<E2<T>>, Int)
public let primaryArchetype: T
public let dependentMember1: T.Inner
}
public struct S3<T: P2> {
public typealias Function = C3<T> -> S3<T> -> E3<T> -> Int
public typealias Tuple = (C3<T>, Box<S3<T>>, Box<E3<T>>, Int)
public let aClass: C3<T>
public let aStruct: Box<S3<T>>
public let anEnum: Box<E3<T>>
public let function: Function
public let tuple: Tuple
public let primaryArchetype: T
public let dependentMember1: T.Outer
public let dependentMember2: T.Outer.Inner
public init(aClass: C3<T>, aStruct: Box<S3<T>>, anEnum: Box<E3<T>>, function: Function, tuple: Tuple, primaryArchetype: T, dependentMember1: T.Outer, dependentMember2: T.Outer.Inner) {
self.aClass = aClass
self.aStruct = aStruct
self.anEnum = anEnum
self.function = function
self.tuple = tuple
self.primaryArchetype = primaryArchetype
self.dependentMember1 = dependentMember1
self.dependentMember2 = dependentMember2
}
}
public enum E1<T> {
case Class(C1<T>)
case Struct(S1<T>)
indirect case Enum(E1<T>)
case Int(Swift.Int)
case Function((T) -> E1<T>)
case Tuple(C1<T>, S1<T>, Swift.Int)
case Primary(T)
case Metatype(T.Type)
}
public enum E2<T: P1> {
case Class(C2<T>)
case Struct(S2<T>)
indirect case Enum(E2<T>)
case Function((T.Type) -> E1<T>)
case Tuple(C2<T>, S2<T>, Int)
case Primary(T)
case DependentMemberInner(T.Inner)
case ExistentialMetatype(T.Type)
}
public enum E3<T: P2> {
case Class(C3<T>)
case Struct(S3<T>)
indirect case Enum(E3<T>)
case Function((T.Type.Type) -> E1<T>)
case Tuple(C3<T>, S3<T>, Int)
case Primary(T)
case DependentMemberOuter(T.Outer)
case DependentMemberInner(T.Outer.Inner)
}
| apache-2.0 | 87d3283e8266eb61fb94f8ec37925566 | 30.421429 | 186 | 0.674926 | 3.04851 | false | false | false | false |
ioscreator/ioscreator | IOSSpriteKitActionsTutorial/IOSSpriteKitActionsTutorial/GameScene.swift | 1 | 1138 | //
// GameScene.swift
// IOSSpriteKitActionsTutorial
//
// Created by Arthur Knopper on 19/02/2019.
// Copyright © 2019 Arthur Knopper. All rights reserved.
//
import SpriteKit
import GameplayKit
class GameScene: SKScene {
override func didMove(to view: SKView) {
let apple = SKSpriteNode(imageNamed: "Apple.png")
apple.position = CGPoint(x: size.width/2, y: size.height/2)
addChild(apple)
//let moveBottomLeft = SKAction.move(to: CGPoint(x: 100,y: 100), duration:2.0)
//apple.run(moveBottomLeft)
let moveRight = SKAction.moveBy(x: 50, y:0, duration:1.0)
//apple.run(moveRight)
let moveBottom = SKAction.moveBy(x: 0, y:-100, duration:3.0)
//let sequence = SKAction.sequence([moveRight, moveBottom])
let reversedMoveBottom = moveBottom.reversed()
let sequence = SKAction.sequence([moveRight, moveBottom, reversedMoveBottom])
//apple.run(sequence)
let endlessAction = SKAction.repeatForever(sequence)
apple.run(endlessAction)
}
}
| mit | 8c2d4010e65e323988c75971129485a7 | 27.425 | 86 | 0.619173 | 4.104693 | false | false | false | false |
bitboylabs/selluv-ios | selluv-ios/selluv-ios/Classes/Controller/UI/Tabs/Tab3Sell/views/SLVAdditionalColorCell.swift | 1 | 1117 | //
// SLVAdditionalColorCell.swift
// selluv-ios
//
// Created by 조백근 on 2017. 1. 5..
// Copyright © 2017년 BitBoy Labs. All rights reserved.
//
import UIKit
class SLVAdditionalColorCell: UICollectionViewCell {
@IBOutlet weak var colorView: UIImageView!
@IBOutlet weak var nameLabel: UILabel!
var colorCode: Code?
override init(frame: CGRect) {
super.init(frame: frame)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override open func awakeFromNib() {
super.awakeFromNib()
}
override func layoutSubviews() {
super.layoutSubviews()
}
//MARK: Setup
func setup(code: Code, image: UIImage) {
self.colorCode = code
self.colorView.image = image
self.nameLabel.text = colorCode?.value
if code.value == "화이트" {
self.colorView.layer.borderColor = UIColor.lightGray.cgColor
self.colorView.layer.borderWidth = 1
} else {
self.colorView.layer.borderWidth = 0
}
}
}
| mit | 25267bc4d21a727f11d7a3d5bd069ecf | 22.446809 | 72 | 0.600726 | 4.338583 | false | false | false | false |
Kushki/kushki-ios | Example/Pods/Kushki/Kushki/Classes/Kushki.swift | 1 | 8601 | import Foundation
import Sift
public class Kushki {
private let publicMerchantId: String
private let currency: String
private let kushkiClient: KushkiClient
public init(publicMerchantId: String, currency: String, environment: KushkiEnvironment, regional: Bool = false) {
self.publicMerchantId = publicMerchantId
self.currency = currency
self.kushkiClient = KushkiClient(environment: environment, regional: regional)
}
public func requestToken(card: Card,
totalAmount: Double, isTest: Bool,
completion: @escaping (Transaction) -> ()) {
self.getMerchantSettings(){
merchantSettings in
let siftScienceResponse = self.kushkiClient.createSiftScienceSession(withMerchantId: self.publicMerchantId, card: card, isTest: true, merchantSettings: merchantSettings)
self.kushkiClient.initSiftScience(merchantSettings: merchantSettings, userId: siftScienceResponse.userId)
let requestMessage = self.kushkiClient.buildParameters(withCard: card, withCurrency: self.currency, withAmount: totalAmount, withSiftScienceResponse: siftScienceResponse)
self.kushkiClient.post(withMerchantId: self.publicMerchantId, endpoint: EndPoint.token.rawValue, requestMessage: requestMessage, withCompletion: completion)
}
}
public func requestSubscriptionToken(card: Card, isTest: Bool,
completion: @escaping (Transaction)->()){
self.getMerchantSettings(){
merchantSettings in
let siftScienceResponse = self.kushkiClient.createSiftScienceSession(withMerchantId: self.publicMerchantId, card: card, isTest: isTest, merchantSettings: merchantSettings)
self.kushkiClient.initSiftScience(merchantSettings: merchantSettings, userId: siftScienceResponse.userId)
let requestMessage = self.kushkiClient.buildParameters(withCard: card, withCurrency: self.currency)
self.kushkiClient.post(withMerchantId: self.publicMerchantId, endpoint: EndPoint.subscriptionToken.rawValue, requestMessage: requestMessage, withCompletion: completion)
}
}
public func requestTransferToken(amount: Amount, callbackUrl:String,userType:String,documentType:String,
documentNumber:String, email:String,
completion: @escaping (Transaction)->()){
let requestMessage = kushkiClient.buildParameters(withAmount: amount, withCallbackUrl: callbackUrl,
withUserType: userType,withDocumentType: documentType,
withDocumentNumber: documentNumber, withEmail: email,
withCurrency: self.currency)
self.kushkiClient.post(withMerchantId: self.publicMerchantId, endpoint: EndPoint.transferToken.rawValue, requestMessage: requestMessage, withCompletion: completion)
}
public func requestTransferToken(amount: Amount, callbackUrl:String,userType:String,documentType:String,
documentNumber:String, email:String,paymentDescription:String,
completion: @escaping (Transaction)->()){
let requestMessage = kushkiClient.buildParameters(withAmount: amount, withCallbackUrl: callbackUrl,
withUserType: userType,withDocumentType: documentType,
withDocumentNumber: documentNumber, withEmail: email,
withCurrency: self.currency,withPaymentDescription: paymentDescription)
self.kushkiClient.post(withMerchantId: self.publicMerchantId, endpoint: EndPoint.transferToken.rawValue, requestMessage: requestMessage, withCompletion: completion)
}
public func getBankList(
completion: @escaping ([Bank]) -> ()){
self.kushkiClient.get(withMerchantId: self.publicMerchantId, endpoint: EndPoint.transferSubscriptionBankList.rawValue, withCompletion: completion)
}
public func requestTransferSubscriptionToken( accountNumber: String, accountType: String, bankCode: String, documentNumber: String, documentType: String, email: String, lastname: String, name: String, totalAmount: Double, completion: @escaping (Transaction)->()){
let requestMessage = kushkiClient.buildParameters( withAccountNumber: accountNumber, withAccountType: accountType, withBankCode: bankCode, withCurrency: self.currency, withDocumentNumber: documentNumber, withDocumentType: documentType, withEmail: email, withLastName: lastname, withName: name, withTotalAmount: totalAmount)
self.kushkiClient.post(withMerchantId: self.publicMerchantId, endpoint: EndPoint.transferSubcriptionToken.rawValue, requestMessage: requestMessage, withCompletion: completion)
}
public func requestSecureValidation( cityCode: String,expeditionDate: String, phone: String,secureService: String, secureServiceId: String, stateCode: String , completion: @escaping (ConfrontaResponse)->()){
let requestMessage = kushkiClient.buildParameters(withCityCode: cityCode, withExpeditionDate : expeditionDate, withPhone: phone, withSecureService: secureService, withSecureServiceId: secureServiceId, withStateCode : stateCode)
self.kushkiClient.post(withMerchantId: self.publicMerchantId, endpoint: EndPoint.transferSubscriptionSecureValidation.rawValue, requestMessage: requestMessage, withCompletion: completion)
}
public func requestSecureValidation(answers: [[String: String]], questionnarieCode: String, secureService: String, secureServiceId: String, completion: @escaping (ConfrontaResponse)->()){
let requestMessage = kushkiClient.buildParameters(withAnswers: answers, withQuestionnarieCode: questionnarieCode, withSecureService: secureService, withSecureServiceId: secureServiceId)
self.kushkiClient.post(withMerchantId: publicMerchantId, endpoint:EndPoint.transferSubscriptionSecureValidation.rawValue, requestMessage: requestMessage, withCompletion: completion)
}
public func requestCashToken(name : String, lastName: String, identification: String, totalAmount: Double, email: String , completion: @escaping (Transaction)->()){
let requestMessage = kushkiClient.buildParameters(withName: name, withLastName: lastName, withIdentification: identification, withTotalAmount: totalAmount, withCurrency: self.currency, withEmail: email)
self.kushkiClient.post(withMerchantId: publicMerchantId, endpoint: EndPoint.cashToken.rawValue, requestMessage: requestMessage, withCompletion: completion)
}
public func requestCardAsyncToken(description: String = "", email: String = "", returnUrl: String, totalAmount: Double, completion: @escaping (Transaction)->()){
let requestMessage = kushkiClient.buildParameters(withCurrency: self.currency, withDescription: description, withEmail: email, withReturnUrl: returnUrl, withTotalAmount: totalAmount)
self.kushkiClient.post(withMerchantId: publicMerchantId, endpoint: EndPoint.cardAsyncToken.rawValue, requestMessage: requestMessage, withCompletion: completion)
}
public func getCardInfo(cardNumber: String,
completion: @escaping (CardInfo) -> ()){
let bin = String(cardNumber[..<cardNumber.index(cardNumber.startIndex, offsetBy: 6)])
self.kushkiClient.get(withMerchantId: self.publicMerchantId, endpoint: EndPoint.cardInfo.rawValue, withParam: bin , withCompletion: completion)
}
public func requestSubscriptionCardAsyncToken(email: String, callbackUrl: String, cardNumber: String = "", completion: @escaping (Transaction)->()){
let requestMessage = kushkiClient.buildParameters(withCurrency: self.currency, withEmail: email, withCallbackUrl: callbackUrl, withCardNumber: cardNumber)
self.kushkiClient.post(withMerchantId: publicMerchantId, endpoint: EndPoint.subscriptionCardAsyncToken.rawValue, requestMessage: requestMessage, withCompletion: completion)
}
func getMerchantSettings(completion: @escaping (MerchantSettings) -> ()) {
self.kushkiClient.get(withMerchantId: self.publicMerchantId, endpoint: EndPoint.merchantSettings.rawValue, withCompletion: completion)
}
}
| mit | b38372cec196b260124f01e0a46523d3 | 75.115044 | 331 | 0.714219 | 5.273452 | false | false | false | false |
cezarywojcik/Operations | Sources/Core/Shared/FunctionalOperations.swift | 1 | 7259 | //
// FunctionalOperations.swift
// Operations
//
// Created by Daniel Thorpe on 21/12/2015.
//
//
import Foundation
/**
# Result Operation
Abstract but a concrete class for a ResultOperationType.
*/
open class ResultOperation<Result>: AdvancedOperation, ResultOperationType {
/// - returns: the Result
open var result: Result? = nil
public init(result: Result? = nil) {
self.result = result
super.init()
name = "Result"
}
open override func execute() {
// no-op
finish()
}
}
/**
# Map Operation
An `Operation` subclass which accepts a map transform closure. Because it
conforms to both `ResultOperationType` and `AutomaticInjectionOperationType`
it can be used to create an array of operations which transform state.
- discussion: Note that the closure is invoked as the operation's *work* on
an operation queue. So it should perform synchronous computation, although
it will be executed asynshronously.
*/
open class MapOperation<T, U>: ResultOperation<U>, AutomaticInjectionOperationType {
/// - returns: the requirement an optional type T
open var requirement: T? = nil
let transform: (T) -> U
/**
Initializes an instance with an optional starting requirement, and an
transform block.
- parameter x: the value to the transformed. Note this is optional, as it
can be injected after initialization, but before execution.
- parameter transform: a closure which maps a non-optional T to U!. Note
that this closure will only be run if the requirement is non-nil.
*/
public init(input: T! = .none, transform: @escaping (T) -> U) {
self.requirement = input
self.transform = transform
super.init(result: nil)
name = "Map"
}
open override func execute() {
guard let requirement = requirement else {
finish(AutomaticInjectionError.requirementNotSatisfied)
return
}
result = transform(requirement)
finish()
}
}
extension ResultOperationType where Self: AdvancedOperation {
/**
Map the result of an `Operation` which conforms to `ResultOperationType`.
```swift
let getLocation = UserLocationOperation()
let toString = getLocation.mapResult { $0.map { "\($0)" } ?? "No location received" }
queue.addOperations(getLocation, toString)
```
*/
public func mapOperation<U>(_ transform: @escaping (Result) -> U) -> MapOperation<Result, U> {
let map: MapOperation<Result, U> = MapOperation(transform: transform)
map.injectResultFromDependency(self) { operation, dependency, errors in
if errors.isEmpty {
operation.requirement = dependency.result
}
else {
operation.cancelWithError(AutomaticInjectionError.dependencyFinishedWithErrors(errors))
}
}
return map
}
}
/**
# Filter Operation
An `Operation` subclass which accepts an include element closure. Because it
conforms to both `ResultOperationType` and `AutomaticInjectionOperationType`
it can be used to create an array of operations which transform state.
- discussion: Note that the closure is invoked as the operation's *work* on
an operation queue. So it should perform synchronous computation, although
it will be executed asynshronously.
*/
open class FilterOperation<Element>: ResultOperation<Array<Element>>, AutomaticInjectionOperationType {
/// - returns: the requirement an optional type T
open var requirement: Array<Element> = []
let filter: (Element) -> Bool
public init(source: Array<Element> = [], includeElement: @escaping (Element) -> Bool) {
self.requirement = source
self.filter = includeElement
super.init(result: [])
name = "Filter"
}
public final override func execute() {
result = requirement.filter(filter)
finish()
}
}
extension ResultOperationType where Self: AdvancedOperation, Result: Sequence {
/**
Filter the result of the receiver `Operation` which conforms to `ResultOperationType` where
the Result is a SequenceType.
```swift
let getLocation = UserLocationOperation()
let toString = getLocation.mapResult { $0.map { "\($0)" } ?? "No location received" }
queue.addOperations(getLocation, toString)
```
*/
public func filterOperation(_ includeElement: @escaping (Result.Iterator.Element) -> Bool) -> FilterOperation<Result.Iterator.Element> {
let filter: FilterOperation<Result.Iterator.Element> = FilterOperation(includeElement: includeElement)
filter.injectResultFromDependency(self) { operation, dependency, errors in
if errors.isEmpty {
operation.requirement = Array(dependency.result)
}
else {
operation.cancelWithError(AutomaticInjectionError.dependencyFinishedWithErrors(errors))
}
}
return filter
}
}
/**
# Reduce Operation
An `Operation` subclass which accepts an initial value, and a combine closure. Because it
conforms to both `ResultOperationType` and `AutomaticInjectionOperationType`
it can be used to create an array of operations which transform state.
- discussion: Note that the closure is invoked as the operation's *work* on
an operation queue. So it should perform synchronous computation, although
it will be executed asynshronously.
*/
open class ReduceOperation<Element, U>: ResultOperation<U>, AutomaticInjectionOperationType {
/// - returns: the requirement an optional type T
open var requirement: Array<Element> = []
let initial: U
let combine: (U, Element) -> U
public init(source: Array<Element> = [], initial: U, combine: @escaping (U, Element) -> U) {
self.requirement = source
self.initial = initial
self.combine = combine
super.init()
name = "Reduce"
}
public final override func execute() {
result = requirement.reduce(initial, combine)
finish()
}
}
extension ResultOperationType where Self: AdvancedOperation, Result: Sequence {
/**
Reduce the result of the receiver `Operation` which conforms to `ResultOperationType` where
the Result is a SequenceType.
```swift
let getStrings = GetStringsOperation()
let createParagraph = getStrings.reduceOperation("") { (accumulator: String, str: String) in
return "\(accumulator) \(str)"
}
queue.addOperations(getStrings, createParagraph)
```
*/
public func reduceOperation<U>(_ initial: U, combine: @escaping (U, Result.Iterator.Element) -> U) -> ReduceOperation<Result.Iterator.Element, U> {
let reduce: ReduceOperation<Result.Iterator.Element, U> = ReduceOperation(initial: initial, combine: combine)
reduce.injectResultFromDependency(self) { operation, dependency, errors in
if errors.isEmpty {
operation.requirement = Array(dependency.result)
}
else {
operation.cancelWithError(AutomaticInjectionError.dependencyFinishedWithErrors(errors))
}
}
return reduce
}
}
| mit | 39b4e47bdeb298dbd43b1018f6d5f42c | 31.55157 | 151 | 0.671442 | 4.683226 | false | false | false | false |
mightydeveloper/swift | stdlib/public/core/Reflection.swift | 8 | 14439 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
/// Customizes the result of `_reflect(x)`, where `x` is a conforming
/// type.
public protocol _Reflectable {
// The runtime has inappropriate knowledge of this protocol and how its
// witness tables are laid out. Changing this protocol requires a
// corresponding change to Reflection.cpp.
/// Returns a mirror that reflects `self`.
@warn_unused_result
func _getMirror() -> _MirrorType
}
/// A unique identifier for a class instance or metatype. This can be used by
/// reflection clients to recognize cycles in the object graph.
///
/// In Swift, only class instances and metatypes have unique identities. There
/// is no notion of identity for structs, enums, functions, or tuples.
public struct ObjectIdentifier : Hashable, Comparable {
let value: Builtin.RawPointer
/// Convert to a `UInt` that captures the full value of `self`.
///
/// Axiom: `a.uintValue == b.uintValue` iff `a == b`.
public var uintValue: UInt {
return UInt(Builtin.ptrtoint_Word(value))
}
// FIXME: Better hashing algorithm
/// The hash value.
///
/// **Axiom:** `x == y` implies `x.hashValue == y.hashValue`.
///
/// - Note: The hash value is not guaranteed to be stable across
/// different invocations of the same program. Do not persist the
/// hash value across program runs.
public var hashValue: Int {
return Int(Builtin.ptrtoint_Word(value))
}
/// Construct an instance that uniquely identifies the class instance `x`.
public init(_ x: AnyObject) {
self.value = Builtin.bridgeToRawPointer(x)
}
/// Construct an instance that uniquely identifies the metatype `x`.
public init(_ x: Any.Type) {
self.value = unsafeBitCast(x, Builtin.RawPointer.self)
}
}
@warn_unused_result
public func <(lhs: ObjectIdentifier, rhs: ObjectIdentifier) -> Bool {
return lhs.uintValue < rhs.uintValue
}
@warn_unused_result
public func ==(x: ObjectIdentifier, y: ObjectIdentifier) -> Bool {
return Bool(Builtin.cmp_eq_RawPointer(x.value, y.value))
}
/// How children of this value should be presented in the IDE.
public enum _MirrorDisposition {
/// As a struct.
case Struct
/// As a class.
case Class
/// As an enum.
case Enum
/// As a tuple.
case Tuple
/// As a miscellaneous aggregate with a fixed set of children.
case Aggregate
/// As a container that is accessed by index.
case IndexContainer
/// As a container that is accessed by key.
case KeyContainer
/// As a container that represents membership of its values.
case MembershipContainer
/// As a miscellaneous container with a variable number of children.
case Container
/// An Optional which can have either zero or one children.
case Optional
/// An Objective-C object imported in Swift.
case ObjCObject
}
/// The type returned by `_reflect(x)`; supplies an API for runtime
/// reflection on `x`.
public protocol _MirrorType {
/// The instance being reflected.
var value: Any { get }
/// Identical to `value.dynamicType`.
var valueType: Any.Type { get }
/// A unique identifier for `value` if it is a class instance; `nil`
/// otherwise.
var objectIdentifier: ObjectIdentifier? { get }
/// The count of `value`'s logical children.
var count: Int { get }
/// Get a name and mirror for the `i`th logical child.
subscript(i: Int) -> (String, _MirrorType) { get }
/// A string description of `value`.
var summary: String { get }
/// A rich representation of `value` for an IDE, or `nil` if none is supplied.
var quickLookObject: PlaygroundQuickLook? { get }
/// How `value` should be presented in an IDE.
var disposition: _MirrorDisposition { get }
}
/// An entry point that can be called from C++ code to get the summary string
/// for an arbitrary object. The memory pointed to by "out" is initialized with
/// the summary string.
@warn_unused_result
@_silgen_name("swift_getSummary")
public // COMPILER_INTRINSIC
func _getSummary<T>(out: UnsafeMutablePointer<String>, x: T) {
out.initialize(_reflect(x).summary)
}
/// Produce a mirror for any value. If the value's type conforms to
/// `_Reflectable`, invoke its `_getMirror()` method; otherwise, fall back
/// to an implementation in the runtime that structurally reflects values
/// of any type.
@warn_unused_result
@_silgen_name("swift_reflectAny")
public func _reflect<T>(x: T) -> _MirrorType
/// Dump an object's contents using its mirror to the specified output stream.
public func dump<T, TargetStream : OutputStreamType>(
x: T, inout _ targetStream: TargetStream,
name: String? = nil, indent: Int = 0,
maxDepth: Int = .max, maxItems: Int = .max
) -> T {
var maxItemCounter = maxItems
var visitedItems = [ObjectIdentifier : Int]()
_dumpWithMirror(
_reflect(x), name, indent, maxDepth, &maxItemCounter, &visitedItems,
&targetStream)
return x
}
/// Dump an object's contents using its mirror to standard output.
public func dump<T>(x: T, name: String? = nil, indent: Int = 0,
maxDepth: Int = .max, maxItems: Int = .max) -> T {
var stdoutStream = _Stdout()
return dump(
x, &stdoutStream, name: name, indent: indent, maxDepth: maxDepth,
maxItems: maxItems)
}
/// Dump an object's contents using a mirror. User code should use dump().
func _dumpWithMirror<TargetStream : OutputStreamType>(
mirror: _MirrorType, _ name: String?, _ indent: Int, _ maxDepth: Int,
inout _ maxItemCounter: Int,
inout _ visitedItems: [ObjectIdentifier : Int],
inout _ targetStream: TargetStream
) {
if maxItemCounter <= 0 { return }
--maxItemCounter
for _ in 0..<indent { print(" ", terminator: "", toStream: &targetStream) }
let count = mirror.count
let bullet = count == 0 ? "-"
: maxDepth <= 0 ? "▹" : "▿"
print("\(bullet) ", terminator: "", toStream: &targetStream)
if let nam = name {
print("\(nam): ", terminator: "", toStream: &targetStream)
}
print(mirror.summary, terminator: "", toStream: &targetStream)
if let id = mirror.objectIdentifier {
if let previous = visitedItems[id] {
print(" #\(previous)", toStream: &targetStream)
return
}
let identifier = visitedItems.count
visitedItems[id] = identifier
print(" #\(identifier)", terminator: "", toStream: &targetStream)
}
print("", toStream: &targetStream)
if maxDepth <= 0 { return }
for i in 0..<count {
if maxItemCounter <= 0 {
for _ in 0..<(indent+4) {
print(" ", terminator: "", toStream: &targetStream)
}
let remainder = count - i
print("(\(remainder)", terminator: "", toStream: &targetStream)
if i > 0 { print(" more", terminator: "", toStream: &targetStream) }
if remainder == 1 {
print(" child)", toStream: &targetStream)
} else {
print(" children)", toStream: &targetStream)
}
return
}
let (name, child) = mirror[i]
_dumpWithMirror(child, name, indent + 2, maxDepth - 1,
&maxItemCounter, &visitedItems, &targetStream)
}
}
// -- _MirrorType implementations for basic data types
/// A mirror for a value that is represented as a simple value with no
/// children.
internal struct _LeafMirror<T>: _MirrorType {
let _value: T
let summaryFunction: T -> String
let quickLookFunction: T -> PlaygroundQuickLook?
init(_ value: T, _ summaryFunction: T -> String,
_ quickLookFunction: T -> PlaygroundQuickLook?) {
self._value = value
self.summaryFunction = summaryFunction
self.quickLookFunction = quickLookFunction
}
var value: Any { return _value }
var valueType: Any.Type { return value.dynamicType }
var objectIdentifier: ObjectIdentifier? { return nil }
var count: Int { return 0 }
subscript(i: Int) -> (String, _MirrorType) {
_preconditionFailure("no children")
}
var summary: String { return summaryFunction(_value) }
var quickLookObject: PlaygroundQuickLook? { return quickLookFunction(_value) }
var disposition: _MirrorDisposition { return .Aggregate }
}
// -- Implementation details for the runtime's _MirrorType implementation
@_silgen_name("swift_MagicMirrorData_summary")
func _swift_MagicMirrorData_summaryImpl(
metadata: Any.Type, _ result: UnsafeMutablePointer<String>
)
public struct _MagicMirrorData {
let owner: Builtin.NativeObject
let ptr: Builtin.RawPointer
let metadata: Any.Type
var value: Any {
@_silgen_name("swift_MagicMirrorData_value")get
}
var valueType: Any.Type {
@_silgen_name("swift_MagicMirrorData_valueType")get
}
public var objcValue: Any {
@_silgen_name("swift_MagicMirrorData_objcValue")get
}
public var objcValueType: Any.Type {
@_silgen_name("swift_MagicMirrorData_objcValueType")get
}
var summary: String {
let (_, result) = _withUninitializedString {
_swift_MagicMirrorData_summaryImpl(self.metadata, $0)
}
return result
}
public func _loadValue<T>() -> T {
return Builtin.load(ptr) as T
}
}
struct _OpaqueMirror : _MirrorType {
let data: _MagicMirrorData
var value: Any { return data.value }
var valueType: Any.Type { return data.valueType }
var objectIdentifier: ObjectIdentifier? { return nil }
var count: Int { return 0 }
subscript(i: Int) -> (String, _MirrorType) {
_preconditionFailure("no children")
}
var summary: String { return data.summary }
var quickLookObject: PlaygroundQuickLook? { return nil }
var disposition: _MirrorDisposition { return .Aggregate }
}
internal struct _TupleMirror : _MirrorType {
let data: _MagicMirrorData
var value: Any { return data.value }
var valueType: Any.Type { return data.valueType }
var objectIdentifier: ObjectIdentifier? { return nil }
var count: Int {
@_silgen_name("swift_TupleMirror_count")get
}
subscript(i: Int) -> (String, _MirrorType) {
@_silgen_name("swift_TupleMirror_subscript")get
}
var summary: String { return "(\(count) elements)" }
var quickLookObject: PlaygroundQuickLook? { return nil }
var disposition: _MirrorDisposition { return .Tuple }
}
struct _StructMirror : _MirrorType {
let data: _MagicMirrorData
var value: Any { return data.value }
var valueType: Any.Type { return data.valueType }
var objectIdentifier: ObjectIdentifier? { return nil }
var count: Int {
@_silgen_name("swift_StructMirror_count")get
}
subscript(i: Int) -> (String, _MirrorType) {
@_silgen_name("swift_StructMirror_subscript")get
}
var summary: String {
return _typeName(valueType)
}
var quickLookObject: PlaygroundQuickLook? { return nil }
var disposition: _MirrorDisposition { return .Struct }
}
struct _EnumMirror : _MirrorType {
let data: _MagicMirrorData
var value: Any { return data.value }
var valueType: Any.Type { return data.valueType }
var objectIdentifier: ObjectIdentifier? { return nil }
var count: Int {
@_silgen_name("swift_EnumMirror_count")get
}
var caseName: UnsafePointer<CChar> {
@_silgen_name("swift_EnumMirror_caseName")get
}
subscript(i: Int) -> (String, _MirrorType) {
@_silgen_name("swift_EnumMirror_subscript")get
}
var summary: String {
let maybeCaseName = String.fromCString(self.caseName)
let typeName = _typeName(valueType)
if let caseName = maybeCaseName {
return typeName + "." + caseName
}
return typeName
}
var quickLookObject: PlaygroundQuickLook? { return nil }
var disposition: _MirrorDisposition { return .Enum }
}
@warn_unused_result
@_silgen_name("swift_ClassMirror_count")
func _getClassCount(_: _MagicMirrorData) -> Int
@warn_unused_result
@_silgen_name("swift_ClassMirror_subscript")
func _getClassChild(_: Int, _: _MagicMirrorData) -> (String, _MirrorType)
#if _runtime(_ObjC)
@warn_unused_result
@_silgen_name("swift_ClassMirror_quickLookObject")
public func _getClassPlaygroundQuickLook(
data: _MagicMirrorData
) -> PlaygroundQuickLook?
#endif
struct _ClassMirror : _MirrorType {
let data: _MagicMirrorData
var value: Any { return data.value }
var valueType: Any.Type { return data.valueType }
var objectIdentifier: ObjectIdentifier? {
return data._loadValue() as ObjectIdentifier
}
var count: Int {
return _getClassCount(data)
}
subscript(i: Int) -> (String, _MirrorType) {
return _getClassChild(i, data)
}
var summary: String {
return _typeName(valueType)
}
var quickLookObject: PlaygroundQuickLook? {
#if _runtime(_ObjC)
return _getClassPlaygroundQuickLook(data)
#else
return .None
#endif
}
var disposition: _MirrorDisposition { return .Class }
}
struct _ClassSuperMirror : _MirrorType {
let data: _MagicMirrorData
var value: Any { return data.value }
var valueType: Any.Type { return data.valueType }
// Suppress the value identifier for super mirrors.
var objectIdentifier: ObjectIdentifier? {
return nil
}
var count: Int {
return _getClassCount(data)
}
subscript(i: Int) -> (String, _MirrorType) {
return _getClassChild(i, data)
}
var summary: String {
return _typeName(data.metadata)
}
var quickLookObject: PlaygroundQuickLook? { return nil }
var disposition: _MirrorDisposition { return .Class }
}
struct _MetatypeMirror : _MirrorType {
let data: _MagicMirrorData
var value: Any { return data.value }
var valueType: Any.Type { return data.valueType }
var objectIdentifier: ObjectIdentifier? {
return data._loadValue() as ObjectIdentifier
}
var count: Int {
return 0
}
subscript(i: Int) -> (String, _MirrorType) {
_preconditionFailure("no children")
}
var summary: String {
return _typeName(data._loadValue() as Any.Type)
}
var quickLookObject: PlaygroundQuickLook? { return nil }
// Special disposition for types?
var disposition: _MirrorDisposition { return .Aggregate }
}
@available(*, unavailable, message="call the 'Mirror(reflecting:)' initializer")
public func reflect<T>(x: T) -> _MirrorType {
fatalError("unavailable function can't be called")
}
| apache-2.0 | 97e876af3bbec18124e9301adc275ab6 | 29.844017 | 80 | 0.681053 | 4.171965 | false | false | false | false |
atl009/WordPress-iOS | WordPress/Classes/Extensions/NSAttributedString+StyledHTML.swift | 1 | 5487 | import UIKit
extension NSAttributedString {
/// Creates an `NSAttributedString` with the styles defined in `attributes` applied.
/// - parameter htmlString: The string to be styled. This can contain HTML
/// tags to markup sections of the text to style, but should not be wrapped
/// with `<html>`, `<body>` or `<p>` tags. See `HTMLAttributeType` for supported tags.
/// - parameter attributes: A collection of style attributes to apply to `htmlString`.
/// See `HTMLAttributeType` for supported attributes. To set text alignment,
/// add an `NSParagraphStyle` to the `BodyAttribute` type, using the key
/// `NSParagraphStyleAttributeName`.
///
/// - note:
/// - Font sizes will be interpreted as pixel sizes, not points.
/// - Font family / name will be discarded (generated strings will always
/// use the system font), but font size and bold / italic information
/// will be applied.
///
class func attributedStringWithHTML(_ htmlString: String, attributes: StyledHTMLAttributes?) -> NSAttributedString {
let styles = styleTagTextForAttributes(attributes)
let styledString = styles + htmlString
guard let data = styledString.data(using: String.Encoding.utf8),
let attributedString = try? NSMutableAttributedString(
data: data,
options: [ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType, NSCharacterEncodingDocumentAttribute: NSNumber(value: String.Encoding.utf8.rawValue) ],
documentAttributes: nil) else {
// if creating the html-ed string fails (and it has, thus this change) we return the string without any styling
return NSAttributedString(string: htmlString)
}
// We can't apply text alignment through CSS, as we need to add a paragraph
// style to set paragraph spacing (which will override any text alignment
// set via CSS). So we'll look for a paragraph style specified for the
// body of the text, so we can copy it use its text alignment.
let paragraphStyle = NSMutableParagraphStyle()
if let attributes = attributes,
let bodyAttributes = attributes[.BodyAttribute],
let pStyle = bodyAttributes[NSParagraphStyleAttributeName] as? NSParagraphStyle {
paragraphStyle.setParagraphStyle(pStyle)
}
// Remove extra padding at the top and bottom of the text.
paragraphStyle.paragraphSpacing = 0
paragraphStyle.paragraphSpacingBefore = 0
attributedString.addAttribute(NSParagraphStyleAttributeName,
value: paragraphStyle,
range: NSMakeRange(0, attributedString.string.count - 1))
return NSAttributedString(attributedString: attributedString)
}
fileprivate class func styleTagTextForAttributes(_ attributes: StyledHTMLAttributes?) -> String {
let styles: [String]? = attributes?.map { attributeType, attributes in
var style = attributeType.tag + " { "
for (attributeName, attribute) in attributes {
if let attributeStyle = cssStyleForAttributeName(attributeName, attribute: attribute) {
style += attributeStyle
}
}
return style + " }"
}
let joinedStyles = styles?.joined(separator: "") ?? ""
return "<style>" + joinedStyles + "</style>"
}
/// Converts a limited set of `NSAttributedString` attribute types from their
/// raw objects (e.g. `UIColor`) into CSS text.
fileprivate class func cssStyleForAttributeName(_ attributeName: String, attribute: AnyObject) -> String? {
switch attributeName {
case NSFontAttributeName:
if let font = attribute as? UIFont {
let size = font.pointSize
let boldStyle = "font-weight: " + (font.isBold ? "bold;" : "normal;")
let italicStyle = "font-style: " + (font.isItalic ? "italic;" : "normal;")
return "font-family: -apple-system; font-size: \(size)px; " + boldStyle + italicStyle
}
case NSForegroundColorAttributeName:
if let color = attribute as? UIColor,
let colorHex = color.hexString() {
return "color: #\(colorHex);"
}
case NSUnderlineStyleAttributeName:
if let style = attribute as? Int {
if style == NSUnderlineStyle.styleNone.rawValue {
return "text-decoration: none;"
} else {
return "text-decoration: underline;"
}
}
default: break
}
return nil
}
}
public typealias StyledHTMLAttributes = [HTMLAttributeType: [String: AnyObject]]
public enum HTMLAttributeType: String {
case BodyAttribute
case ATagAttribute
case EmTagAttribute
case StrongTagAttribute
var tag: String {
switch self {
case .BodyAttribute: return "body"
case .ATagAttribute: return "a"
case .EmTagAttribute: return "em"
case .StrongTagAttribute: return "strong"
}
}
}
private extension UIFont {
var isBold: Bool {
return fontDescriptor.symbolicTraits.contains(.traitBold)
}
var isItalic: Bool {
return fontDescriptor.symbolicTraits.contains(.traitItalic)
}
}
| gpl-2.0 | f7462b7120da69c05371cc1d77bb683a | 42.547619 | 167 | 0.628941 | 5.270893 | false | false | false | false |
marekhac/WczasyNadBialym-iOS | WczasyNadBialym/WczasyNadBialym/Models/JSON/Service/ServiceCategoryModel.swift | 1 | 1140 | //
// ServiceCategoryModel.swift
// WczasyNadBialym
//
// Created by Marek Hać on 25.04.2017.
// Copyright © 2017 Marek Hać. All rights reserved.
//
import Foundation
struct ServiceCategoryModel : Codable {
let shortName: String
let longName: String
let id: Int
let type: String
// init made for local initialization of Services (not downloaded from the server)
init(shortName: String, longName: String) {
self.shortName = shortName
self.longName = longName
self.id = 0
self.type = ""
}
static func servicesFromResults(_ jsonData : Data) -> [ServiceCategoryModel]? {
let decoder = JSONDecoder()
var categories = [ServiceCategoryModel]()
do {
categories = try decoder.decode([ServiceCategoryModel].self, from: jsonData)
} catch let error {
if(!ErrorDescriptionModel.unwrapFrom(jsonData)) {
LogEventHandler.report(LogEventType.error, "Unable to parse Service Categories JSON", error.localizedDescription)
}
}
return categories
}
}
| gpl-3.0 | 1dd110f37826e332cdd6d65ba60093b1 | 26.731707 | 129 | 0.626209 | 4.717842 | false | false | false | false |
grpc/grpc-swift | Sources/GRPC/ClientCalls/ClientStreamingCall.swift | 1 | 4868 | /*
* Copyright 2019, gRPC Authors All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import Logging
import NIOCore
import NIOHPACK
import NIOHTTP2
/// A client-streaming gRPC call.
///
/// Messages should be sent via the ``sendMessage(_:compression:)`` and ``sendMessages(_:compression:)`` methods; the stream of messages
/// must be terminated by calling ``sendEnd()`` to indicate the final message has been sent.
///
/// Note: while this object is a `struct`, its implementation delegates to ``Call``. It therefore
/// has reference semantics.
public struct ClientStreamingCall<RequestPayload, ResponsePayload>: StreamingRequestClientCall,
UnaryResponseClientCall {
private let call: Call<RequestPayload, ResponsePayload>
private let responseParts: UnaryResponseParts<ResponsePayload>
/// The options used to make the RPC.
public var options: CallOptions {
return self.call.options
}
/// The path used to make the RPC.
public var path: String {
return self.call.path
}
/// The `Channel` used to transport messages for this RPC.
public var subchannel: EventLoopFuture<Channel> {
return self.call.channel
}
/// The `EventLoop` this call is running on.
public var eventLoop: EventLoop {
return self.call.eventLoop
}
/// Cancel this RPC if it hasn't already completed.
public func cancel(promise: EventLoopPromise<Void>?) {
self.call.cancel(promise: promise)
}
// MARK: - Response Parts
/// The initial metadata returned from the server.
public var initialMetadata: EventLoopFuture<HPACKHeaders> {
return self.responseParts.initialMetadata
}
/// The response returned by the server.
public var response: EventLoopFuture<ResponsePayload> {
return self.responseParts.response
}
/// The trailing metadata returned from the server.
public var trailingMetadata: EventLoopFuture<HPACKHeaders> {
return self.responseParts.trailingMetadata
}
/// The final status of the the RPC.
public var status: EventLoopFuture<GRPCStatus> {
return self.responseParts.status
}
internal init(call: Call<RequestPayload, ResponsePayload>) {
self.call = call
self.responseParts = UnaryResponseParts(on: call.eventLoop)
}
internal func invoke() {
self.call.invokeStreamingRequests(
onStart: {},
onError: self.responseParts.handleError(_:),
onResponsePart: self.responseParts.handle(_:)
)
}
// MARK: - Request
/// Sends a message to the service.
///
/// - Important: Callers must terminate the stream of messages by calling ``sendEnd()`` or
/// ``sendEnd(promise:)``.
///
/// - Parameters:
/// - message: The message to send.
/// - compression: Whether compression should be used for this message. Ignored if compression
/// was not enabled for the RPC.
/// - promise: A promise to fulfill with the outcome of the send operation.
public func sendMessage(
_ message: RequestPayload,
compression: Compression = .deferToCallDefault,
promise: EventLoopPromise<Void>?
) {
let compress = self.call.compress(compression)
self.call.send(.message(message, .init(compress: compress, flush: true)), promise: promise)
}
/// Sends a sequence of messages to the service.
///
/// - Important: Callers must terminate the stream of messages by calling ``sendEnd()`` or
/// ``sendEnd(promise:)``.
///
/// - Parameters:
/// - messages: The sequence of messages to send.
/// - compression: Whether compression should be used for this message. Ignored if compression
/// was not enabled for the RPC.
/// - promise: A promise to fulfill with the outcome of the send operation. It will only succeed
/// if all messages were written successfully.
public func sendMessages<S>(
_ messages: S,
compression: Compression = .deferToCallDefault,
promise: EventLoopPromise<Void>?
) where S: Sequence, S.Element == RequestPayload {
self.call.sendMessages(messages, compression: compression, promise: promise)
}
/// Terminates a stream of messages sent to the service.
///
/// - Important: This should only ever be called once.
/// - Parameter promise: A promise to be fulfilled when the end has been sent.
public func sendEnd(promise: EventLoopPromise<Void>?) {
self.call.send(.end, promise: promise)
}
}
| apache-2.0 | f06824a3d4286341d31aed50e3f03150 | 33.771429 | 136 | 0.70871 | 4.40543 | false | false | false | false |
sjtu-meow/iOS | Meow/ArticleDetailViewController.swift | 1 | 10631 | //
// ArticleDetailViewController.swift
// Meow
//
// Created by 林树子 on 2017/7/5.
// Copyright © 2017年 喵喵喵的伙伴. All rights reserved.
//
import Foundation
import UIKit
import WebKit
import RxSwift
import SwiftyJSON
import PKHUD
class ArticleDetailViewController: UIViewController {
class func show(_ item: ItemProtocol, from viewController: UIViewController) {
let vc = R.storyboard.articlePage.articleDetailViewController()!
vc.itemId = item.id
vc.itemType = item.type
viewController.navigationController?.pushViewController(vc, animated: true)
}
let disposeBag = DisposeBag()
@IBOutlet weak var scrollView: UIScrollView!
//@IBOutlet weak var webviewCell: UITableViewCell!
/* user profile info */
@IBOutlet weak var avatarImageView: AvatarImageView!
@IBOutlet weak var nicknameLabel: UILabel!
@IBOutlet weak var bioLabel: UILabel!
@IBOutlet weak var webViewContainer: UIView!
var webview: ArticleWebView!
var itemId: Int?
var itemType: ItemType?
var item: ItemProtocol?
var question: Question?
var bottomBar: UITabBar!
// FIXME
var isLiked = false, isFavorite = false
override func viewDidLoad() {
webview = ArticleWebView(fromSuperView: webViewContainer)
webview.heightChangingHandler = {
[weak self] height in
self?.scrollView.contentSize.height = height + 50
}
bottomBar = R.nib.itemDetailButtomBar.firstView(owner: self) as! UITabBar
view.addSubview(bottomBar)
bottomBar.translatesAutoresizingMaskIntoConstraints = false
bottomBar.bottomAnchor.constraint(equalTo: self.view.bottomAnchor).isActive = true
bottomBar.leftAnchor.constraint(equalTo: self.view.leftAnchor).isActive = true
bottomBar.rightAnchor.constraint(equalTo: self.view.rightAnchor).isActive = true
bottomBar.topAnchor.constraint(equalTo: scrollView.bottomAnchor).isActive = true
bottomBar.delegate = self
avatarImageView.delegate = self
initBottomBarStyle()
loadData()
}
var content: String?
var htmlString: String?
func configure(id: Int, type: ItemType) {
self.itemId = id
self.itemType = type
}
func loadData() {
guard let id = itemId else {
return
}
if (self.itemType == .article) {
MeowAPIProvider.shared.request(.article(id: id))
.mapTo(type: Article.self)
.subscribe(onNext: {
[weak self]
(item:ItemProtocol) -> Void in
self?.item = item
self?.updateView()
})
.addDisposableTo(disposeBag)
} else { // answer
MeowAPIProvider.shared.request(.answer(id: id))
.mapTo(type: Answer.self)
.flatMap {
[weak self]
(item:ItemProtocol) -> Observable<Any> in
self?.item = item
return MeowAPIProvider.shared.request(.question(id: (item as! Answer).questionId))
}
.mapTo(type: Question.self)
.subscribe(onNext: {
[weak self]
question in
self?.question = question
self?.updateView()
})
.addDisposableTo(disposeBag)
}
}
@IBAction func goBack(_ sender: Any) {
dismiss(animated: true, completion: nil)
}
func updateView() {
var content: String!
if itemType! == .article {
let article = item as! Article
content = article.content!
self.navigationItem.title = article.title
} else if itemType! == .answer {
let answer = item as! Answer
content = answer.content!
navigationItem.title = question?.title
}
webview.presentHTMLString(content)
let profile = item!.profile!
nicknameLabel.text = profile.nickname
bioLabel.text = profile.bio
avatarImageView.configure(model: profile)
}
func showCommentView() {
let vc = R.storyboard.main.commentViewController()!
guard let article = self.item else {
return
}
vc.configure(model: article)
navigationController?.pushViewController(vc, animated: true)
}
func showMoreMenu() {
var alert: UIAlertController!
alert = UIAlertController(title: "", message: "", preferredStyle: UIAlertControllerStyle.actionSheet)
let cancelAction = UIAlertAction(title: "取消", style: UIAlertActionStyle.cancel, handler: nil)
let reportAction = UIAlertAction(title: "举报", style: UIAlertActionStyle.default) {
_ in
self.report()
}
let shareAction = UIAlertAction(title: "分享", style: UIAlertActionStyle.default) {
_ in
self.share()
}
alert.addAction(cancelAction)
alert.addAction(reportAction)
alert.addAction(shareAction)
present(alert, animated: true, completion: nil)
}
func report() {
let alert = UIAlertController(title: "举报", message: "请输入举报内容", preferredStyle: .alert)
let ok = UIAlertAction(title: "好", style: .default) { (action) in
self.sendReport(message: alert.textFields![0].text!)
}
alert.addTextField(configurationHandler: nil)
ok.isEnabled = true
let cancel = UIAlertAction(title: "取消", style: .cancel, handler: nil)
alert.addAction(ok)
alert.addAction(cancel)
present(alert, animated: true, completion: nil)
}
func sendReport(message: String) {
MeowAPIProvider.shared
.request(.postReport(id: itemId!, type: .article, reason: message))
.subscribe(onNext: { _ in
HUD.flash(.labeledSuccess(title: "举报成功", subtitle: nil))
}).addDisposableTo(disposeBag)
}
func share() {
didTapShareButton()
}
func initBottomBarStyle() {
bottomBar.tintColor = UIColor.gray
MeowAPIProvider.shared
.request(.isFavoriteArticle(id: itemId!))
.subscribe(onNext: {
[weak self]
json in
self?.isFavorite = (json as! JSON)["favourite"].bool!
self?.updateFavoriteLabel()
})
.addDisposableTo(disposeBag)
MeowAPIProvider.shared
.request(.isLikedArticle(id: itemId!))
.subscribe(onNext: {
[weak self]
json in
self?.isLiked = (json as! JSON)["liked"].bool!
self?.updateLikeLabel()
})
.addDisposableTo(disposeBag)
}
func updateLikeLabel() {
bottomBar.items![0].title = isLiked ? "已赞" : "赞"
}
func updateFavoriteLabel() {
bottomBar.items![2].title = isFavorite ? "已收藏" : "收藏"
}
}
extension ArticleDetailViewController: UITabBarDelegate {
func tabBar(_ tabBar: UITabBar, didSelect item: UITabBarItem) {
switch tabBar.items!.index(of: item)! {
case 1:
self.showCommentView()
case 0:
toggleLike()
updateLikeLabel()
case 2:
toggleFavorite()
updateFavoriteLabel()
case 3:
showMoreMenu()
default: break
}
}
func toggleFavorite() {
let isFavorite = self.isFavorite
let request = itemType == .article ? (isFavorite ? MeowAPI.removeFavoriteArticle(id: itemId!) :MeowAPI.addFavoriteArticle(id: itemId!)) : (isFavorite ? MeowAPI.removeFavoriteAnswer(id: itemId!) : MeowAPI.addFavoriteAnswer(id: itemId!)
)
MeowAPIProvider.shared.request(request)
.subscribe(onNext: {
[weak self]
_ in
self?.isFavorite = !isFavorite
self?.updateFavoriteLabel()
})
.addDisposableTo(disposeBag)
}
func toggleLike() {
let isLiked = self.isLiked
let request = itemType == .article ? (isLiked ? MeowAPI.unlikeArticle(id: itemId!) : MeowAPI.likeArticle(id: itemId!)) :
(isLiked ? MeowAPI.unlikeAnswer(id: itemId!) : MeowAPI.likeAnswer(id: itemId!))
MeowAPIProvider.shared.request(request)
.subscribe(onNext: {
[weak self]
_ in
self?.isLiked = !isLiked
self?.updateLikeLabel()
})
.addDisposableTo(disposeBag)
}
func didTapShareButton() {
guard let item = self.item else { return }
let dict = NSMutableDictionary()
if item.type! == .article {
let article = item as! Article
let title = "来自喵喵喵的文章:\(article.title!)"
var images: [URL] = []
if let cover = article.cover {
images.append(cover)
}
dict.ssdkSetupShareParams(
byText: title,
images: images,
url: URL(string: "http://106.14.156.19"),
title: title,
type: SSDKContentType.text
)
} else { // .answer
let answer = item as! Answer
let title = "来自喵喵喵用户\(item.profile.nickname!)的回答:" + (question?.title ?? "")
dict.ssdkSetupShareParams(
byText: title,
images: [],
url: URL(string: "http://106.14.156.19"),
title: title,
type: SSDKContentType.text
)
}
ShareSDK.showShareActionSheet(nil, items: nil, shareParams: dict) { (state, _, _, _, _, _) in
print(state)
}
}
}
extension ArticleDetailViewController: AvatarCellDelegate {
func didTapAvatar(profile: Profile) {
if let userId = UserManager.shared.currentUser?.userId, userId == profile.userId {
MeViewController.show(from: navigationController!)
} else {
UserProfileViewController.show(profile, from: self)
}
}
}
| apache-2.0 | b615cc2ebceb91f0c6928a1a31f35519 | 31.04878 | 242 | 0.558885 | 4.951484 | false | false | false | false |
tlax/looper | looper/Model/Camera/More/MCameraMoreItemActions.swift | 1 | 1021 | import UIKit
class MCameraMoreItemActions:MCameraMoreItem
{
let options:[MCameraMoreItemActionsOption]
private let kCellHeight:CGFloat = 65
init()
{
let optionAdd:MCameraMoreItemActionsOptionAdd = MCameraMoreItemActionsOptionAdd()
let optionRotate:MCameraMoreItemActionsOptionRotate = MCameraMoreItemActionsOptionRotate()
let optionCrop:MCameraMoreItemActionsOptionCrop = MCameraMoreItemActionsOptionCrop()
let optionScale:MCameraMoreItemActionsOptionScale = MCameraMoreItemActionsOptionScale()
let optionTrash:MCameraMoreItemActionsOptionTrash = MCameraMoreItemActionsOptionTrash()
options = [
optionAdd,
optionRotate,
optionCrop,
optionScale,
optionTrash
]
let reusableIdentifier:String = VCameraMoreCellActions.reusableIdentifier
super.init(
reusableIdentifier:reusableIdentifier,
cellHeight:kCellHeight)
}
}
| mit | 16f76629a5e433f158fb9fc1e357c142 | 33.033333 | 98 | 0.697356 | 5.34555 | false | false | false | false |
PureSwift/Bluetooth | Sources/BluetoothGATT/GATTScanIntervalWindow.swift | 1 | 2481 | //
// GATTScanIntervalWindow.swift
// Bluetooth
//
// Created by Carlos Duclos on 7/11/18.
// Copyright © 2018 PureSwift. All rights reserved.
//
import Foundation
/**
Scan Interval Window
The Scan Interval Window characteristic is used to store the scan parameters of the GATT Client. Included in this characteristic are the Scan Interval and Scan Window of the GATT Client device.
The Scan Interval Window characteristic is used to store the scan parameters of the GATT Client. The GATT Server can use these values to optimize its own advertisement rate and to minimize the rate of its own advertisements while also minimizing the latency of reconnections.
- SeeAlso: [Scan Interval Window](https://www.bluetooth.com/specifications/gatt/viewer?attributeXmlFile=org.bluetooth.characteristic.scan_interval_window.xml)
*/
@frozen
public struct GATTScanIntervalWindow: GATTCharacteristic {
internal static let length = MemoryLayout<UInt16>.size * 2
public static var uuid: BluetoothUUID { return .scanIntervalWindow }
public var scanInterval: LowEnergyScanTimeInterval
public var scanWindow: LowEnergyScanTimeInterval
public init(scanInterval: LowEnergyScanTimeInterval,
scanWindow: LowEnergyScanTimeInterval) {
self.scanInterval = scanInterval
self.scanWindow = scanWindow
}
public init?(data: Data) {
guard data.count == type(of: self).length
else { return nil }
guard let scanInterval = LowEnergyScanTimeInterval(rawValue: UInt16(littleEndian: UInt16(bytes: (data[0], data[1]))))
else { return nil }
guard let scanWindow = LowEnergyScanTimeInterval(rawValue: UInt16(littleEndian: UInt16(bytes: (data[2], data[3]))))
else { return nil }
self.init(scanInterval: scanInterval, scanWindow: scanWindow)
}
public var data: Data {
let scanIntervalBytes = scanInterval.rawValue.littleEndian.bytes
let scanWindowBytes = scanWindow.rawValue.littleEndian.bytes
return Data([scanIntervalBytes.0, scanIntervalBytes.1, scanWindowBytes.0, scanWindowBytes.1])
}
}
extension GATTScanIntervalWindow: Equatable {
public static func == (lhs: GATTScanIntervalWindow, rhs: GATTScanIntervalWindow) -> Bool {
return lhs.scanInterval == rhs.scanInterval && lhs.scanWindow == rhs.scanWindow
}
}
| mit | 5e39ce85b4ace5cc6a60a332463139fe | 36.014925 | 276 | 0.701613 | 4.688091 | false | false | false | false |
PureSwift/Bluetooth | Sources/BluetoothGAP/GAPLEDeviceAddress.swift | 1 | 2083 | //
// GAPLEDeviceAddress.swift
// Bluetooth
//
// Created by Carlos Duclos on 6/14/18.
// Copyright © 2018 PureSwift. All rights reserved.
//
import Foundation
/// The LE Bluetooth Device Address data type defines the device address of the local device
/// and the address type on the LE transport.
///
/// Size: 7 octets.
/// The format of the 6 least significant Octets is the same as the Device Address
/// defined in [Vol. 6], Part B, Section 1.3.
/// The least significant bit of the most significant octet defines if the Device Address
/// is a Public Address or a Random Address.
/// - Note:
/// LSB = 1 Then Random Device Address. LSB = 0 Then Public Device Address.
/// Bits 1 to 7 in the most significant octet are reserved for future use.
@frozen
public struct GAPLEDeviceAddress: GAPData {
public static var dataType: GAPDataType { return .lowEnergyDeviceAddress }
public let address: BluetoothAddress
public let type: GAPLEDeviceAddressType
public init(address: BluetoothAddress,
type: GAPLEDeviceAddressType = .public) {
self.address = address
self.type = type
}
}
public extension GAPLEDeviceAddress {
internal static var length: Int { return 7 }
init?(data: Data) {
guard data.count == Swift.type(of: self).length,
let type = GAPLEDeviceAddressType(rawValue: data[6])
else { return nil }
let address = BluetoothAddress(littleEndian: BluetoothAddress(bytes: (data[0], data[1], data[2], data[3], data[4], data[5])))
self.init(address: address, type: type)
}
var dataLength: Int {
return Swift.type(of: self).length
}
func append(to data: inout Data) {
data += address.littleEndian
data += type.rawValue
}
}
// MARK: - Supporting Types
/// GAP LE Device Address Type.
public enum GAPLEDeviceAddressType: UInt8 {
/// Public Device Address
case `public` = 0x00
/// Random Device Address
case random = 0x01
}
| mit | f6f066d8ab7816699a64cf7f4fddadb2 | 27.135135 | 133 | 0.646974 | 4.240326 | false | false | false | false |
Za1006/TIY-Assignments | CarFinder/CarFinder/AppDelegate.swift | 1 | 6094 | //
// AppDelegate.swift
// CarFinder
//
// Created by Elizabeth Yeh on 12/5/15.
// Copyright © 2015 The Iron Yard. All rights reserved.
//
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
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:.
// Saves changes in the application's managed object context before the application terminates.
self.saveContext()
}
// MARK: - Core Data stack
lazy var applicationDocumentsDirectory: NSURL = {
// The directory the application uses to store the Core Data store file. This code uses a directory named "com.tiy.CarFinder" in the application's documents Application Support directory.
let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
return urls[urls.count-1]
}()
lazy var managedObjectModel: NSManagedObjectModel = {
// The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model.
let modelURL = NSBundle.mainBundle().URLForResource("CarFinder", withExtension: "momd")!
return NSManagedObjectModel(contentsOfURL: modelURL)!
}()
lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = {
// The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail.
// Create the coordinator and store
let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("SingleViewCoreData.sqlite")
var failureReason = "There was an error creating or loading the application's saved data."
do {
try coordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil)
} catch {
// Report any error we got.
var dict = [String: AnyObject]()
dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data"
dict[NSLocalizedFailureReasonErrorKey] = failureReason
dict[NSUnderlyingErrorKey] = error as NSError
let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
// Replace this with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(wrappedError), \(wrappedError.userInfo)")
abort()
}
return coordinator
}()
lazy var managedObjectContext: NSManagedObjectContext = {
// Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail.
let coordinator = self.persistentStoreCoordinator
var managedObjectContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType)
managedObjectContext.persistentStoreCoordinator = coordinator
return managedObjectContext
}()
// MARK: - Core Data Saving support
func saveContext () {
if managedObjectContext.hasChanges {
do {
try managedObjectContext.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nserror = error as NSError
NSLog("Unresolved error \(nserror), \(nserror.userInfo)")
abort()
}
}
}
}
| cc0-1.0 | 97c403705d514dba19fbd1523a680e59 | 53.891892 | 291 | 0.71935 | 5.869942 | false | false | false | false |
hejunbinlan/GRDB.swift | GRDB Tests/Public/Core/DatabaseValueConvertible/RawRepresentableTests.swift | 1 | 3753 | import XCTest
import GRDB
enum Color : Int {
case Red
case White
case Rose
}
enum Grape : String {
case Chardonnay
case Merlot
case Riesling
}
extension Color : DatabaseIntRepresentable { }
extension Grape : DatabaseStringRepresentable { }
class RawRepresentableTests: GRDBTestCase {
override func setUp() {
super.setUp()
var migrator = DatabaseMigrator()
migrator.registerMigration("createPersons") { db in
try db.execute("CREATE TABLE wines (grape TEXT, color INTEGER)")
}
assertNoError {
try migrator.migrate(dbQueue)
}
}
func testColor() {
assertNoError {
try dbQueue.inTransaction { db in
do {
for color in [Color.Red, Color.White, Color.Rose] {
try db.execute("INSERT INTO wines (color) VALUES (?)", arguments: [color])
}
try db.execute("INSERT INTO wines (color) VALUES (?)", arguments: [4])
try db.execute("INSERT INTO wines (color) VALUES (NULL)")
}
do {
let rows = Row.fetchAll(db, "SELECT color FROM wines ORDER BY color")
let colors = rows.map { $0.value(atIndex: 0) as Color? }
XCTAssertTrue(colors[0] == nil)
XCTAssertEqual(colors[1]!, Color.Red)
XCTAssertEqual(colors[2]!, Color.White)
XCTAssertEqual(colors[3]!, Color.Rose)
XCTAssertTrue(colors[4] == nil)
}
do {
let colors = Color.fetchAll(db, "SELECT color FROM wines ORDER BY color")
XCTAssertTrue(colors[0] == nil)
XCTAssertEqual(colors[1]!, Color.Red)
XCTAssertEqual(colors[2]!, Color.White)
XCTAssertEqual(colors[3]!, Color.Rose)
XCTAssertTrue(colors[4] == nil)
}
return .Rollback
}
}
}
func testGrape() {
assertNoError {
try dbQueue.inTransaction { db in
do {
for grape in [Grape.Chardonnay, Grape.Merlot, Grape.Riesling] {
try db.execute("INSERT INTO wines (grape) VALUES (?)", arguments: [grape])
}
try db.execute("INSERT INTO wines (grape) VALUES (?)", arguments: ["Syrah"])
try db.execute("INSERT INTO wines (grape) VALUES (NULL)")
}
do {
let rows = Row.fetchAll(db, "SELECT grape FROM wines ORDER BY grape")
let grapes = rows.map { $0.value(atIndex: 0) as Grape? }
XCTAssertTrue(grapes[0] == nil)
XCTAssertEqual(grapes[1]!, Grape.Chardonnay)
XCTAssertEqual(grapes[2]!, Grape.Merlot)
XCTAssertEqual(grapes[3]!, Grape.Riesling)
XCTAssertTrue(grapes[4] == nil)
}
do {
let grapes = Grape.fetchAll(db, "SELECT grape FROM wines ORDER BY grape")
XCTAssertTrue(grapes[0] == nil)
XCTAssertEqual(grapes[1]!, Grape.Chardonnay)
XCTAssertEqual(grapes[2]!, Grape.Merlot)
XCTAssertEqual(grapes[3]!, Grape.Riesling)
XCTAssertTrue(grapes[4] == nil)
}
return .Rollback
}
}
}
}
| mit | 260f45728ac9f8d76e594d5edc029828 | 35.086538 | 98 | 0.476152 | 4.957728 | false | false | false | false |
googlecodelabs/admob-native-advanced-feed | ios/final/NativeAdvancedTableViewExample/ViewController.swift | 1 | 4112 | //
// Copyright (C) 2017 Google, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import Firebase
import UIKit
class ViewController: UIViewController, GADUnifiedNativeAdLoaderDelegate {
// MARK: - Properties
/// The table view items.
var tableViewItems = [AnyObject]()
/// The ad unit ID from the AdMob UI.
let adUnitID = "ca-app-pub-3940256099942544/8407707713"
/// The number of native ads to load (must be less than 5).
let numAdsToLoad = 5
/// The native ads.
var nativeAds = [GADUnifiedNativeAd]()
/// The ad loader that loads the native ads.
var adLoader: GADAdLoader!
/// The spinner view.
@IBOutlet weak var spinnerView: UIActivityIndicatorView!
/// The show menu button.
@IBOutlet weak var showMenuButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
// Load the menu items.
addMenuItems()
let options = GADMultipleAdsAdLoaderOptions()
options.numberOfAds = numAdsToLoad
// Prepare the ad loader and start loading ads.
adLoader = GADAdLoader(adUnitID: adUnitID,
rootViewController: self,
adTypes: [.unifiedNative],
options: [options])
adLoader.delegate = self
adLoader.load(GADRequest())
}
@IBAction func showMenu(_ sender: Any) {
let tableVC = storyboard?.instantiateViewController(withIdentifier: "TableViewController")
as! TableViewController
tableVC.tableViewItems = tableViewItems
self.present(tableVC, animated: true, completion: nil)
}
func enableMenuButton() {
spinnerView.stopAnimating()
showMenuButton.isEnabled = true
}
/// Adds MenuItems to the tableViewItems list.
func addMenuItems() {
var JSONObject: Any
guard let path = Bundle.main.url(forResource: "menuItemsJSON", withExtension: "json") else {
print("Invalid filename for JSON menu item data.")
return
}
do {
let data = try Data(contentsOf: path)
JSONObject = try JSONSerialization.jsonObject(with: data,
options: JSONSerialization.ReadingOptions())
} catch {
print("Failed to load menu item JSON data: %s", error)
return
}
guard let JSONObjectArray = JSONObject as? [Any] else {
print("Failed to cast JSONObject to [AnyObject]")
return
}
for object in JSONObjectArray {
guard let dict = object as? [String: Any],
let menuIem = MenuItem(dictionary: dict) else {
print("Failed to load menu item JSON data.")
return
}
tableViewItems.append(menuIem)
}
}
/// Add native ads to the tableViewItems list.
func addNativeAds() {
if nativeAds.count <= 0 {
return
}
let adInterval = (tableViewItems.count / nativeAds.count) + 1
var index = 0
for nativeAd in nativeAds {
if index < tableViewItems.count {
tableViewItems.insert(nativeAd, at: index)
index += adInterval
} else {
break
}
}
}
// MARK: - GADAdLoaderDelegate
func adLoader(_ adLoader: GADAdLoader, didFailToReceiveAdWithError error: GADRequestError) {
print("\(adLoader) failed with error: \(error.localizedDescription)")
}
func adLoader(_ adLoader: GADAdLoader, didReceive nativeAd: GADUnifiedNativeAd) {
print("Received native ad: \(nativeAd)")
// Add the native ad to the list of native ads.
nativeAds.append(nativeAd)
}
func adLoaderDidFinishLoading(_ adLoader: GADAdLoader) {
addNativeAds()
enableMenuButton()
}
}
| apache-2.0 | 76ced94a7f5d7baeb4e38b7f098e5828 | 27.957746 | 96 | 0.661722 | 4.412017 | false | false | false | false |
danielsaidi/iExtra | iExtra/Date/Extensions/Date+Compare.swift | 1 | 493 | //
// Date+Compare.swift
// iExtra
//
// Created by Daniel Saidi on 2015-05-15.
// Copyright © 2015 Daniel Saidi. All rights reserved.
//
import Foundation
public extension Date {
func isAfter(_ date: Date) -> Bool {
return compare(date) == .orderedDescending
}
func isBefore(_ date: Date) -> Bool {
return compare(date) == .orderedAscending
}
func isSameAs(_ date: Date) -> Bool {
return compare(date) == .orderedSame
}
}
| mit | 46a939c7f17bcff9e53e95ade676c349 | 19.5 | 55 | 0.597561 | 3.967742 | false | false | false | false |
idea4good/GuiLiteSamples | HelloWave/BuildAppleWatch/HelloWave watchOS App Extension/GuiLiteImage.swift | 1 | 2057 | import UIKit
class GuiLiteImage {
let width, height, colorBytes : Int
let buffer: UnsafeMutableRawPointer
init(width: Int, height: Int, colorBytes: Int) {
self.width = width
self.height = height
self.colorBytes = colorBytes
self.buffer = malloc(width * height * 4)
}
func getUiImage() -> CGImage?{
let pixData = (colorBytes == 2) ? getPixelsFrom16bits() : getPixelsFrom32bits()
if(pixData == nil){
return nil
}
let providerRef = CGDataProvider(data: pixData!)
let bitmapInfo:CGBitmapInfo = [.byteOrder32Little, CGBitmapInfo(rawValue: CGImageAlphaInfo.noneSkipFirst.rawValue)]
return CGImage(width: Int(width), height: height, bitsPerComponent: 8, bitsPerPixel: 32, bytesPerRow: width * 4, space: CGColorSpaceCreateDeviceRGB(), bitmapInfo: bitmapInfo, provider: providerRef!, decode: nil, shouldInterpolate: true, intent: .defaultIntent)
}
func getPixelsFrom16bits()->CFData?{
let rawData = getUiOfHelloWave()
if rawData == nil{
return nil
}
for index in 0..<width * height {
let rgb16 = rawData?.load(fromByteOffset: index * 2, as: UInt16.self)
let rgb32 = UInt32(rgb16!)
let color = ((rgb32 & 0xF800) << 8 | ((rgb32 & 0x7E0) << 5) | ((rgb32 & 0x1F) << 3))
buffer.storeBytes(of: color, toByteOffset: index * 4, as: UInt32.self)
}
let rawPointer = UnsafeRawPointer(buffer)
let pixData: UnsafePointer = rawPointer.assumingMemoryBound(to: UInt8.self)
return CFDataCreate(nil, pixData, width * height * 4)
}
func getPixelsFrom32bits()->CFData?{
let rawData = getUiOfHelloWave()
if rawData == nil{
return nil
}
let rawPointer = UnsafeRawPointer(rawData)
let pixData: UnsafePointer = rawPointer!.assumingMemoryBound(to: UInt8.self)
return CFDataCreate(nil, pixData, width * height * 4)
}
}
| apache-2.0 | 929d537e9d70bf1e49e704196d3a05f1 | 37.811321 | 268 | 0.614001 | 4.385928 | false | false | false | false |
abertelrud/swift-package-manager | Sources/PackageCollectionsSigning/Signing/Signature.swift | 2 | 6408 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift open source project
//
// Copyright (c) 2021 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//===----------------------------------------------------------------------===//
//
// This source file is part of the Vapor open source project
//
// Copyright (c) 2017-2020 Vapor project authors
// Licensed under MIT
//
// See LICENSE for license information
//
// SPDX-License-Identifier: MIT
//
//===----------------------------------------------------------------------===//
import Foundation
// The logic in this source file loosely follows https://www.rfc-editor.org/rfc/rfc7515.html
// for JSON Web Signature (JWS).
struct Signature {
let header: Header
let payload: Data
let signature: Data
}
extension Signature {
enum Algorithm: String, Codable {
case RS256 // RSASSA-PKCS1-v1_5 using SHA-256
case ES256 // ECDSA using P-256 and SHA-256
static func from(keyType: KeyType) -> Algorithm {
switch keyType {
case .RSA:
return .RS256
case .EC:
return .ES256
}
}
}
struct Header: Equatable, Codable {
// https://www.rfc-editor.org/rfc/rfc7515.html#section-4.1.1
let algorithm: Algorithm
/// Base64 encoded certificate chain
let certChain: [String]
enum CodingKeys: String, CodingKey {
case algorithm = "alg"
case certChain = "x5c"
}
}
}
// Reference: https://github.com/vapor/jwt-kit/blob/master/Sources/JWTKit/JWTSerializer.swift
extension Signature {
static func generate<Payload>(for payload: Payload,
with header: Header,
using signer: MessageSigner,
jsonEncoder: JSONEncoder) throws -> Data where Payload: Encodable {
let headerData = try jsonEncoder.encode(header)
let encodedHeader = headerData.base64URLEncodedBytes()
let payloadData = try jsonEncoder.encode(payload)
let encodedPayload = payloadData.base64URLEncodedBytes()
// https://www.rfc-editor.org/rfc/rfc7515.html#section-5.1
// Signing input: BASE64URL(header) + '.' + BASE64URL(payload)
let signatureData = try signer.sign(message: encodedHeader + .period + encodedPayload)
let encodedSignature = signatureData.base64URLEncodedBytes()
// Result: header.payload.signature
let bytes = encodedHeader
+ .period
+ encodedPayload
+ .period
+ encodedSignature
return bytes
}
}
// Reference: https://github.com/vapor/jwt-kit/blob/master/Sources/JWTKit/JWTParser.swift
extension Signature {
typealias CertChainValidate = ([Data], @escaping (Result<[Certificate], Error>) -> Void) -> Void
static func parse(_ signature: String,
certChainValidate: CertChainValidate,
jsonDecoder: JSONDecoder,
callback: @escaping (Result<Signature, Error>) -> Void) {
let bytes = Array(signature.utf8)
Self.parse(bytes, certChainValidate: certChainValidate, jsonDecoder: jsonDecoder, callback: callback)
}
static func parse<SignatureData>(_ signature: SignatureData,
certChainValidate: CertChainValidate,
jsonDecoder: JSONDecoder,
callback: @escaping (Result<Signature, Error>) -> Void) where SignatureData: DataProtocol {
let parts = signature.copyBytes().split(separator: .period)
guard parts.count == 3 else {
return callback(.failure(SignatureError.malformedSignature))
}
let encodedHeader = parts[0]
let encodedPayload = parts[1]
let encodedSignature = parts[2]
guard let headerBytes = encodedHeader.base64URLDecodedBytes(),
let header = try? jsonDecoder.decode(Header.self, from: headerBytes) else {
return callback(.failure(SignatureError.malformedSignature))
}
// Signature header contains the certificate and public key for verification
let certChainData = header.certChain.compactMap { Data(base64Encoded: $0) }
// Make sure we restore all certs successfully
guard certChainData.count == header.certChain.count else {
return callback(.failure(SignatureError.malformedSignature))
}
certChainValidate(certChainData) { result in
switch result {
case .failure(let error):
callback(.failure(error))
case .success(let certChain):
do {
// Extract public key from the certificate
let certificate = certChain.first! // !-safe because certChain is not empty at this point
let publicKey = try certificate.publicKey()
guard let payload = encodedPayload.base64URLDecodedBytes() else {
return callback(.failure(SignatureError.malformedSignature))
}
guard let signature = encodedSignature.base64URLDecodedBytes() else {
return callback(.failure(SignatureError.malformedSignature))
}
// Verify the key was used to generate the signature
let message: Data = Data(encodedHeader) + .period + Data(encodedPayload)
guard try publicKey.isValidSignature(signature, for: message) else {
return callback(.failure(SignatureError.invalidSignature))
}
callback(.success(Signature(header: header, payload: payload, signature: signature)))
} catch {
callback(.failure(error))
}
}
}
}
}
enum SignatureError: Error {
case malformedSignature
case invalidSignature
}
| apache-2.0 | c1bf22b5218398e0fdebdb28b71fa2e8 | 38.073171 | 128 | 0.578496 | 5.142857 | false | false | false | false |
MModel/MetaModel | lib/metamodel/template/packing.swift | 1 | 1691 | //
// Packing.swift
// MetaModel
//
// Created by Draveness on 9/16/16.
// Copyright © 2016 metamodel. All rights reserved.
//
import Foundation
protocol Packing {
init(values: Array<Optional<Binding>>);
}
class MetaModels {
static func fromQuery<T>(_ query: String) -> [T] where T: Packing {
var models: [T] = []
guard let stmt = executeSQL(query) else { return models }
for values in stmt {
let association = T(values: values)
models.append(association)
}
return models
}
}
// MARK: - Model Packing
<% models.each do |model| %>
extension <%= model.name %>: Packing {
init(values: Array<Optional<Binding>>) {
<% model.properties.each_with_index do |property, index| %><%= """let #{property.name}: #{property.real_type} = values[#{index+1}] as! #{property.real_type}""" %>
<% end %>
self.init(<%= model.property_key_value_pairs true %>)
let privateId: Int64 = values[0] as! Int64
self.privateId = Int(privateId)
}
}
<% end %>
// MARK: - Association Packing
<% associations.each do |association| if association.is_active? %>
extension <%= association.class_name %>: Packing {
init(values: Array<Optional<Binding>>) {
let privateId: Int64 = values[0] as! Int64
let <%= association.major_model_id %>: Int64 = values[1] as! Int64
let <%= association.secondary_model_id %>: Int64 = values[2] as! Int64
self.init(privateId: Int(privateId), <%= association.major_model_id %>: Int(<%= association.major_model_id %>), <%= association.secondary_model_id %>: Int(<%= association.secondary_model_id %>))
}
}
<% end %><% end %>
| mit | 297eb91c6eb5b9ed6d6939a265669c1f | 31.5 | 202 | 0.610651 | 3.421053 | false | false | false | false |
grayunicorn/Quiz | Quiz/Core Data/Student+CoreDataProperties.swift | 1 | 2739 | //
// Student+CoreDataProperties.swift
// Quiz
//
// Created by Adam Eberbach on 11/9/17.
// Copyright © 2017 Adam Eberbach. All rights reserved.
//
//
import Foundation
import CoreData
extension Student {
@nonobjc public class func fetchRequest() -> NSFetchRequest<Student> {
return NSFetchRequest<Student>(entityName: "Student")
}
@NSManaged public var quizzes: NSOrderedSet?
@NSManaged public var teacher: Teacher?
}
// MARK: Generated accessors for quizzes
extension Student {
@objc(insertObject:inQuizzesAtIndex:)
@NSManaged public func insertIntoQuizzes(_ value: QuizCollection, at idx: Int)
@objc(removeObjectFromQuizzesAtIndex:)
@NSManaged public func removeFromQuizzes(at idx: Int)
@objc(insertQuizzes:atIndexes:)
@NSManaged public func insertIntoQuizzes(_ values: [QuizCollection], at indexes: NSIndexSet)
@objc(removeQuizzesAtIndexes:)
@NSManaged public func removeFromQuizzes(at indexes: NSIndexSet)
@objc(replaceObjectInQuizzesAtIndex:withObject:)
@NSManaged public func replaceQuizzes(at idx: Int, with value: QuizCollection)
@objc(replaceQuizzesAtIndexes:withQuizzes:)
@NSManaged public func replaceQuizzes(at indexes: NSIndexSet, with values: [QuizCollection])
@objc(addQuizzesObject:)
@NSManaged public func addToQuizzes(_ value: QuizCollection)
@objc(removeQuizzesObject:)
@NSManaged public func removeFromQuizzes(_ value: QuizCollection)
@objc(addQuizzes:)
@NSManaged public func addToQuizzes(_ values: NSOrderedSet)
@objc(removeQuizzes:)
@NSManaged public func removeFromQuizzes(_ values: NSOrderedSet)
}
// MARK:- convenience functions
extension Student {
// create and return a new QuizAnswer with its text and true or false status
class func createWithLogin(login: String, inContext: NSManagedObjectContext) -> Student {
let student = NSEntityDescription.insertNewObject(forEntityName: kManagedObjectIdentifier, into: inContext) as! Student
student.login = login
return student
}
func gradeableResults() -> [QuizCollection] {
var gradeable: [QuizCollection] = []
for quiz in quizzes! {
let thisQuiz = quiz as! QuizCollection
if thisQuiz.isGradeable() {
gradeable.append(thisQuiz)
}
}
return gradeable
}
// return all the QuizCollection objects owned by this student that can't be graded yet
func quizzesRequiringGrading() -> [QuizCollection] {
var needGrading: [QuizCollection] = []
for quiz in quizzes! {
let thisQuiz = quiz as! QuizCollection
if thisQuiz.isGradeable() == false {
needGrading.append(thisQuiz)
}
}
return needGrading
}
}
| bsd-3-clause | 1956f7b1689ac75eb5b98e4a0751526e | 26.656566 | 123 | 0.712199 | 4.192956 | false | false | false | false |
hooman/swift | test/IRGen/prespecialized-metadata/struct-extradata-field_offsets-no_trailing_flags.swift | 14 | 2954 | // RUN: %target-swift-frontend -emit-ir %s | %FileCheck %s -DINT=i%target-ptrsize -DALIGNMENT=%target-alignment
// REQUIRES: VENDOR=apple || OS=linux-gnu
// UNSUPPORTED: CPU=i386 && OS=ios
// UNSUPPORTED: CPU=armv7 && OS=ios
// UNSUPPORTED: CPU=armv7s && OS=ios
// CHECK: [[EXTRA_DATA_PATTERN:@[0-9]+]] = internal constant <{
// CHECK-SAME: i32
// CHECK-SAME: , i32
// CHECK-SAME: , i32
// : , [4 x i8]
// CHECK-SAME: }> <{
// CHECK-SAME: i32 0,
// CHECK-SAME: i32 8,
// CHECK-SAME: i32 16
// : , [4 x i8] zeroinitializer
// CHECK-SAME: }>, align [[ALIGNMENT]]
// CHECK: @"$s4main4PairVMP" = internal constant <{
// : i32,
// : i32,
// : i32,
// : i32,
// : i32,
// : i16,
// : i16
// : }> <{
// : i32 trunc (
// : i64 sub (
// : i64 ptrtoint (
// : %swift.type* (
// : %swift.type_descriptor*,
// : i8**,
// : i8*
// : )* @"$s4main4PairVMi" to i64
// : ),
// : i64 ptrtoint (
// : <{ i32, i32, i32, i32, i32, i16, i16 }>*
// : @"$s4main4PairVMP" to i64
// : )
// : ) to i32
// : ),
// : i32 0,
// : i32 1073741827,
// : i32 trunc (
// : i64 sub (
// : i64 ptrtoint (
// : %swift.vwtable* @"$s4main4PairVWV" to i64
// : ),
// : i64 ptrtoint (
// : i32* getelementptr inbounds (
// : <{ i32, i32, i32, i32, i32, i16, i16 }>,
// : <{ i32, i32, i32, i32, i32, i16, i16 }>* @"$s4main4PairVMP",
// : i32 0,
// : i32 3
// : ) to i64
// : )
// : ) to i32
// : ),
// : i32 trunc (
// CHECK-SAME: [[INT]] sub (
// CHECK-SAME: [[INT]] ptrtoint (
// CHECK-SAME: <{ i32
// CHECK-SAME: , i32
// CHECK-SAME: , i32
// : , [4 x i8]
// CHECK-SAME: }>* [[EXTRA_DATA_PATTERN]] to [[INT]]
// CHECK-SAME: ),
// CHECK-SAME: [[INT]] ptrtoint (
// CHECK-SAME: i32* getelementptr inbounds (
// CHECK-SAME: <{ i32, i32, i32, i32, i32, i16, i16 }>,
// CHECK-SAME: <{ i32, i32, i32, i32, i32, i16, i16 }>* @"$s4main4PairVMP",
// CHECK-SAME: i32 0,
// CHECK-SAME: i32 4
// CHECK-SAME: ) to [[INT]]
// CHECK-SAME: )
// CHECK-SAME: )
// : ),
// : i16 3,
// : i16 3
// : }>, align 8
struct Pair<First, Second, Third> {
let first: Int64
let second: Int64
let third: Int64
}
| apache-2.0 | e9cd1565800140d6c03f7da8bd84777a | 32.191011 | 111 | 0.375762 | 2.965863 | false | false | false | false |
jregnauld/SwiftyInstagram | SwiftyInstagram/Classes/Domain/Configuration.swift | 1 | 1465 | //
// Configuration.swift
// Pods
//
// Created by Julien Regnauld on 8/8/16.
//
//
import Foundation
fileprivate func < <T : Comparable>(lhs: T?, rhs: T?) -> Bool {
switch (lhs, rhs) {
case let (l?, r?):
return l < r
case (nil, _?):
return true
default:
return false
}
}
fileprivate func > <T : Comparable>(lhs: T?, rhs: T?) -> Bool {
switch (lhs, rhs) {
case let (l?, r?):
return l > r
default:
return rhs < lhs
}
}
public struct Configuration {
let client: Client
let parameters: [Scope]?
public init(client: Client){
self.init(client: client, parameters: nil)
}
public init(client: Client, parameters: [Scope]?) {
self.client = client
self.parameters = parameters
}
public func authorizationParameters() -> [String: String] {
guard let parameters = self.parameters , self.parameters?.count > 0 else {
return ["client_id": self.client.clientID,
"redirect_uri": self.client.redirectURL,
"response_type": "token"]
}
var scopeValues: String = ""
parameters.enumerated().map({ (index, element) in
if index == 0 {
scopeValues += element.rawValue
} else {
scopeValues += "+" + element.rawValue
}
})
return ["client_id": self.client.clientID,
"redirect_uri": self.client.redirectURL,
"response_type": "token",
"scope": scopeValues]
}
}
| mit | e59bdeb7d2a72922c482b42669d48bc5 | 23.416667 | 78 | 0.576792 | 3.795337 | false | false | false | false |
AndrewBennet/readinglist | ReadingList/Data/CSVParser.swift | 1 | 2770 | import Foundation
import CHCSVParser
public protocol CSVParserDelegate: AnyObject {
func headersRead(_ headers: [String]) -> Bool
func lineParseSuccess(_ values: [String: String])
func lineParseError()
func onFailure(_ error: CSVImportError)
func completion()
}
public enum CSVImportError: Error {
case invalidCsv
case missingHeaders
}
public class CSVParser: NSObject, CHCSVParserDelegate {
// CHCSVParserDelegate is informed of each read field. This wrapper is intended to create a simpler CSV Parser
// which can response to completed lines, by the header names.
private let parser: CHCSVParser!
public init(csvFileUrl: URL) {
parser = CHCSVParser(contentsOfCSVURL: csvFileUrl)
parser.sanitizesFields = true
parser.trimsWhitespace = true
parser.recognizesComments = true
super.init()
parser.delegate = self
}
public var delegate: CSVParserDelegate? //swiftlint:disable:this weak_delegate
// (weakness not required in pratice)
public func begin() { parser.parse() }
public func stop() { parser.cancelParsing() }
private var isFirstRow = true
private var currentRowIsErrored = false
private var currentRow = [String: String]()
private var headersByFieldIndex = [Int: String]()
public func parser(_ parser: CHCSVParser!, didBeginLine recordNumber: UInt) {
currentRow.removeAll(keepingCapacity: true)
currentRowIsErrored = false
}
public func parser(_ parser: CHCSVParser!, didReadField field: String!, at fieldIndex: Int) {
guard !isFirstRow else { headersByFieldIndex[fieldIndex] = field; return }
guard let currentHeader = headersByFieldIndex[fieldIndex] else { currentRowIsErrored = true; return }
if let fieldValue = field.trimming().nilIfWhitespace() {
currentRow[currentHeader] = fieldValue
}
}
public func parser(_ parser: CHCSVParser!, didFailWithError error: Error!) {
delegate?.onFailure(.invalidCsv)
}
public func parser(_ parser: CHCSVParser!, didEndLine recordNumber: UInt) {
if isFirstRow {
if delegate?.headersRead(headersByFieldIndex.map { $0.value }) == false {
stop()
delegate?.onFailure(.missingHeaders)
delegate = nil // Remove the delegate to stop any further callbacks
} else {
isFirstRow = false
}
return
}
guard !currentRowIsErrored else { delegate?.lineParseError(); return }
delegate?.lineParseSuccess(currentRow)
}
public func parserDidEndDocument(_ parser: CHCSVParser!) {
delegate?.completion()
}
}
| gpl-3.0 | c41e1e7a1bfc8eebc25a818a4c058e8c | 34.063291 | 114 | 0.658123 | 4.792388 | false | false | false | false |
skyfe79/SwiftImageProcessing | 06_SplitRGBColorSpace_2.playground/Sources/RGBAImage.swift | 1 | 5575 | import UIKit
public struct Pixel {
public var value: UInt32
//red
public var R: UInt8 {
get { return UInt8(value & 0xFF); }
set { value = UInt32(newValue) | (value & 0xFFFFFF00) }
}
//green
public var G: UInt8 {
get { return UInt8((value >> 8) & 0xFF) }
set { value = (UInt32(newValue) << 8) | (value & 0xFFFF00FF) }
}
//blue
public var B: UInt8 {
get { return UInt8((value >> 16) & 0xFF) }
set { value = (UInt32(newValue) << 16) | (value & 0xFF00FFFF) }
}
//alpha
public var A: UInt8 {
get { return UInt8((value >> 24) & 0xFF) }
set { value = (UInt32(newValue) << 24) | (value & 0x00FFFFFF) }
}
public var Rf: Double {
get { return Double(self.R) / 255.0 }
set { self.R = UInt8(newValue * 255.0) }
}
public var Gf: Double {
get { return Double(self.G) / 255.0 }
set { self.G = UInt8(newValue * 255.0) }
}
public var Bf: Double {
get { return Double(self.B) / 255.0 }
set { self.B = UInt8(newValue * 255.0) }
}
public var Af: Double {
get { return Double(self.A) / 255.0 }
set { self.A = UInt8(newValue * 255.0) }
}
}
public struct RGBAImage {
public var pixels: UnsafeMutableBufferPointer<Pixel>
public var width: Int
public var height: Int
public init?(image: UIImage) {
// CGImage로 변환이 가능해야 한다.
guard let cgImage = image.cgImage else {
return nil
}
// 주소 계산을 위해서 Float을 Int로 저장한다.
width = Int(image.size.width)
height = Int(image.size.height)
// 4 * width * height 크기의 버퍼를 생성한다.
let bytesPerRow = width * 4
let imageData = UnsafeMutablePointer<Pixel>.allocate(capacity: width * height)
// 색상공간은 Device의 것을 따른다
let colorSpace = CGColorSpaceCreateDeviceRGB()
// BGRA로 비트맵을 만든다
var bitmapInfo: UInt32 = CGBitmapInfo.byteOrder32Big.rawValue
bitmapInfo = bitmapInfo | CGImageAlphaInfo.premultipliedLast.rawValue & CGBitmapInfo.alphaInfoMask.rawValue
// 비트맵 생성
guard let imageContext = CGContext(data: imageData, width: width, height: height, bitsPerComponent: 8, bytesPerRow: bytesPerRow, space: colorSpace, bitmapInfo: bitmapInfo) else {
return nil
}
// cgImage를 imageData에 채운다.
imageContext.draw(cgImage, in: CGRect(origin: .zero, size: image.size))
pixels = UnsafeMutableBufferPointer<Pixel>(start: imageData, count: width * height)
}
public init(width: Int, height: Int) {
let image = RGBAImage.newUIImage(width: width, height: height)
self.init(image: image)!
}
public func clone() -> RGBAImage {
let cloneImage = RGBAImage(width: self.width, height: self.height)
for y in 0..<height {
for x in 0..<width {
let index = y * width + x
cloneImage.pixels[index] = self.pixels[index]
}
}
return cloneImage
}
public func toUIImage() -> UIImage? {
let colorSpace = CGColorSpaceCreateDeviceRGB()
var bitmapInfo: UInt32 = CGBitmapInfo.byteOrder32Big.rawValue
let bytesPerRow = width * 4
bitmapInfo |= CGImageAlphaInfo.premultipliedLast.rawValue & CGBitmapInfo.alphaInfoMask.rawValue
guard let imageContext = CGContext(data: pixels.baseAddress, width: width, height: height, bitsPerComponent: 8, bytesPerRow: bytesPerRow, space: colorSpace, bitmapInfo: bitmapInfo, releaseCallback: nil, releaseInfo: nil) else {
return nil
}
guard let cgImage = imageContext.makeImage() else {
return nil
}
let image = UIImage(cgImage: cgImage)
return image
}
public func pixel(x : Int, _ y : Int) -> Pixel? {
guard x >= 0 && x < width && y >= 0 && y < height else {
return nil
}
let address = y * width + x
return pixels[address]
}
public mutating func pixel(x : Int, _ y : Int, _ pixel: Pixel) {
guard x >= 0 && x < width && y >= 0 && y < height else {
return
}
let address = y * width + x
pixels[address] = pixel
}
public mutating func process( functor : ((Pixel) -> Pixel) ) {
for y in 0..<height {
for x in 0..<width {
let index = y * width + x
let outPixel = functor(pixels[index])
pixels[index] = outPixel
}
}
}
public func enumerate( functor : (Int, Pixel) -> Void) {
for y in 0..<height {
for x in 0..<width {
let index = y * width + x
functor(index, pixels[index])
}
}
}
private static func newUIImage(width: Int, height: Int) -> UIImage {
let size = CGSize(width: CGFloat(width), height: CGFloat(height));
UIGraphicsBeginImageContextWithOptions(size, true, 0);
UIColor.black.setFill()
UIRectFill(CGRect(x: 0, y: 0, width: size.width, height: size.height))
let image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image!
}
}
| mit | 30cd94d7c3dddd3e56e75c1aea64cdcb | 30.865497 | 235 | 0.552762 | 4.14688 | false | false | false | false |
ArchimboldiMao/remotex-iOS | remotex-iOS/Controller/JobWebViewController.swift | 1 | 6101 | //
// JobWebViewController.swift
// remotex-iOS
//
// Created by archimboldi on 17/05/2017.
// Copyright © 2017 me.archimboldi. All rights reserved.
//
import Foundation
import WebKit
class JobWebViewController: UIViewController, WKNavigationDelegate {
var url: URL!
var jobTitle: String!
var webView: WKWebView!
var progressView: UIProgressView!
convenience init() {
self.init(withURL: nil, withTitle: nil)
}
init(withURL url: URL!, withTitle jobTitle: String!) {
self.url = url
self.jobTitle = jobTitle
super.init(nibName: nil, bundle: nil)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
deinit {
webView.removeObserver(self, forKeyPath: #keyPath(WKWebView.estimatedProgress))
}
override func loadView() {
let webConfiguration = WKWebViewConfiguration.init()
webView = WKWebView.init(frame: CGRect.zero, configuration: webConfiguration)
webView.navigationDelegate = self
webView.backgroundColor = Constants.TableLayout.BackgroundColor
view = webView
}
override func viewDidLoad() {
super.viewDidLoad()
setupProgressView()
setupNavigation()
webView.load(URLRequest(url: url))
webView.allowsBackForwardNavigationGestures = true
webView.allowsLinkPreview = true
webView.addObserver(self, forKeyPath: #keyPath(WKWebView.estimatedProgress), options: .new, context: nil)
self.navigationController?.setNavigationBarHidden(false, animated: true)
}
override func viewWillDisappear(_ animated: Bool) {
progressView.removeFromSuperview()
super.viewWillDisappear(animated)
}
func setupProgressView() {
if self.progressView == nil {
let progressView = UIProgressView.init()
progressView.progressViewStyle = .bar
progressView.tintColor = Constants.AppLayout.LogoForegroundColor
progressView.progress = 0.2
progressView.layer.zPosition = 1.1
self.progressView = progressView
}
if ((self.navigationController != nil) && !self.navigationController!.navigationBar.isHidden) {
progressView.frame = CGRect.init(x: self.navigationController?.navigationBar.frame.origin.x ?? 0, y: (self.navigationController?.navigationBar.frame.size.height ?? 0) - progressView.frame.size.height, width: self.navigationController?.navigationBar.frame.size.width ?? UIScreen.main.bounds.size.width, height: 2)
if self.progressView.superview != self.navigationController?.navigationBar {
self.progressView.removeFromSuperview()
self.navigationController?.navigationBar.addSubview(self.progressView)
}
} else {
if (self.webView.superview != nil) {
if UIDevice.current.orientation.isPortrait {
progressView.frame = CGRect.init(x: self.webView.frame.origin.x, y: self.webView.frame.origin.y + 20 - progressView.frame.size.height, width: self.webView.frame.size.width, height: 2)
} else {
progressView.frame = CGRect.init(x: self.webView.frame.origin.x, y: 0, width: self.webView.frame.size.width, height: 2)
}
if self.progressView.superview != self.webView.superview {
self.progressView.removeFromSuperview()
self.webView.superview?.addSubview(self.progressView)
}
}
}
}
func dismissProgressView() {
UIView.animate(withDuration: 0.2, delay: 0.1, options: .curveEaseOut, animations: {
self.progressView.removeFromSuperview()
}, completion: nil)
}
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
if keyPath == "estimatedProgress" {
let progress = Float(webView.estimatedProgress)
if progress < 0.2 {
progressView.progress = 0.2 + progress / 10
} else if progress >= 1.0 {
progressView.progress = 1.0
} else {
progressView.progress = progress
}
}
}
func setupNavigation() {
self.navigationItem.rightBarButtonItem = UIBarButtonItem.init(barButtonSystemItem: UIBarButtonSystemItem.action, target: self, action: #selector(shareAction))
}
func shareAction() {
let image = Constants.ShareContext.LogoImage
let shareTitle: String! = self.jobTitle
let shareURL: URL! = self.url
var shareObject = [Any]()
shareObject = [image, shareURL, shareTitle] as [Any]
let activityViewController = UIActivityViewController(activityItems: shareObject, applicationActivities: nil)
activityViewController.popoverPresentationController?.sourceView = self.view // so that iPads won't crash
self.present(activityViewController, animated: true, completion: nil)
}
func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
setupProgressView()
}
func webView(_ webView: WKWebView, didReceiveServerRedirectForProvisionalNavigation navigation: WKNavigation!) {
setupProgressView()
}
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
dismissProgressView()
}
func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) {
dismissProgressView()
PromptMessageWrap.show(withMessage: Constants.MessageDescription.NoInternetConnection)
}
func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
dismissProgressView()
PromptMessageWrap.show(withMessage: Constants.MessageDescription.NoInternetConnection)
}
}
| apache-2.0 | 5c2d831d7b680dfc5418a577de5e08ee | 39.397351 | 324 | 0.654262 | 5.254091 | false | false | false | false |
DenHeadless/DTModelStorage | Sources/Tests/Specs/MemoryStorage/MemoryStorageAddTestCase.swift | 1 | 1270 | //
// MemoryStorageAddSpec.swift
// DTModelStorageTests
//
// Created by Denys Telezhkin on 11.07.15.
// Copyright (c) 2015 Denys Telezhkin. All rights reserved.
//
import UIKit
import XCTest
import DTModelStorage
@MainActor
class MemoryStorageAddSpec: XCTestCase {
var storage = MemoryStorage()
var delegate = StorageUpdatesObserver()
@MainActor override func setUp() {
super.setUp()
storage.delegate = delegate
}
func testShouldReceiveCorrectUpdateCallWhenAddingItem() {
let update = StorageUpdate()
update.sectionChanges.append((.insert, [0]))
update.objectChanges.append((.insert, [indexPath(0, 0)]))
storage.addItem("")
delegate.applyUpdates()
XCTAssertEqual(delegate.lastUpdate, update)
}
func testShouldReceiveCorrectUpdateCallWhenAddingItems()
{
let foo = [1, 2, 3]
storage.addItems(foo, toSection: 1)
delegate.applyUpdates()
delegate.verifyObjectChanges([
(.insert, [indexPath(0, 1)]),
(.insert, [indexPath(1, 1)]),
(.insert, [indexPath(2, 1)])
])
delegate.verifySectionChanges([
(.insert, [0]),
(.insert, [1])
])
}
}
| mit | 6101b115b3ebb4c299d65c5fc4ffc3ce | 24.918367 | 65 | 0.608661 | 4.45614 | false | true | false | false |
onevcat/CotEditor | CotEditor/Sources/SnippetKeyBindingManager.swift | 1 | 4322 | //
// SnippetKeyBindingManager.swift
//
// CotEditor
// https://coteditor.com
//
// Created by 1024jp on 2016-06-22.
//
// ---------------------------------------------------------------------------
//
// © 2004-2007 nakamuxu
// © 2014-2022 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 Cocoa
final class SnippetKeyBindingManager: KeyBindingManager {
// MARK: Public Properties
static let shared = SnippetKeyBindingManager()
let defaultSnippets: [String]
// MARK: Private Properties
private let _defaultKeyBindings: Set<KeyBinding>
// MARK: -
// MARK: Lifecycle
override private init() {
_defaultKeyBindings = []
self.defaultSnippets = UserDefaults.standard.registeredValue(for: .insertCustomTextArray)
super.init()
}
// MARK: Key Binding Manager Methods
/// name of file to save custom key bindings in the plist file form (without extension)
override var settingFileName: String {
return "SnippetKeyBindings"
}
/// default key bindings
override var defaultKeyBindings: Set<KeyBinding> {
return _defaultKeyBindings
}
/// create a KVO-compatible collection for outlineView in preferences from the key binding setting
///
/// - Parameter usesDefaults: `true` for default setting and `false` for the current setting.
override func outlineTree(defaults usesDefaults: Bool) -> [NSTreeNode] {
let keyBindings = usesDefaults ? self.defaultKeyBindings : self.keyBindings
let count = (usesDefaults ? self.defaultSnippets : self.snippets).count
return (0..<count).map { index in
let title = String(format: "Insert Text %li".localized, locale: .current, index)
let action = self.action(index: index)
let keyBinding = keyBindings.first { $0.action == action }
let item = KeyBindingItem(name: title, action: action, shortcut: keyBinding?.shortcut, defaultShortcut: .none)
return NamedTreeNode(name: title, representedObject: item)
}
}
/// whether key bindings are not customized
override var usesDefaultKeyBindings: Bool {
return (self.snippets == self.defaultSnippets) && super.usesDefaultKeyBindings
}
// MARK: Public Methods
/// return snippet string for key binding if exists
func snippet(shortcut: Shortcut) -> Snippet? {
guard
let keyBinding = self.keyBindings.first(where: { $0.shortcut == shortcut }),
let index = self.snippetIndex(for: keyBinding.action),
let snippetString = self.snippets[safe: index]
else { return nil }
return Snippet(snippetString)
}
/// snippet texts to insert with key binding
var snippets: [String] {
get { UserDefaults.standard[.insertCustomTextArray] }
set { UserDefaults.standard[.insertCustomTextArray] = newValue }
}
// MARK: Private Methods
/// build selector name for index
private func action(index: Int) -> Selector {
return Selector(String(format: "insertCustomText_%02li:", index))
}
/// extract index number of snippet from selector name
private func snippetIndex(for action: Selector) -> Int? {
let selector = NSStringFromSelector(action)
guard
let range = selector.range(of: "(?<=^insertCustomText_)[0-9]{2}(?=:$)", options: .regularExpression)
else { return nil }
return Int(selector[range])
}
}
| apache-2.0 | 95f5e9f30baed47aa35613e1ab18af54 | 28.589041 | 122 | 0.609491 | 4.848485 | false | false | false | false |
PureSwift/LittleCMS | Sources/LittleCMS/Context.swift | 1 | 4222 | //
// Context.swift
// LittleCMS
//
// Created by Alsey Coleman Miller on 6/3/17.
//
//
import CLCMS
/// Keeps track of all plug-ins and static data.
///
/// There are situations where several instances of Little CMS engine have to coexist but on different conditions.
/// For example, when the library is used as a DLL or a shared object, diverse applications may want to use
/// different plug-ins. Another example is when multiple threads are being used in same task and the
/// user wants to pass thread-dependent information to the memory allocators or the logging system.
/// For all this use, Little CMS 2.6 and above implements context handling functions.
public final class Context {
public typealias ErrorLog = (String, LittleCMSError?) -> ()
// MARK: - Properties
internal private(set) var internalPointer: cmsContext!
// MARK: - Initialization
deinit {
if let internalPointer = self.internalPointer {
cmsDeleteContext(internalPointer)
}
}
/// Dummy initializer to satisfy Swift
private init() { }
//// Creates a new context with optional associated plug-ins.
/// that will be forwarded to plug-ins and logger.
public convenience init?(plugin: UnsafeMutableRawPointer? = nil) {
self.init()
let userData = cmsCreateContextUserData(self)
guard let internalPointer = cmsCreateContext(plugin, userData)
else { return nil }
self.internalPointer = internalPointer
}
// MARK: - Accessors
/// Duplicates a context with all associated plug-ins.
/// Caller may specify an optional pointer to user-defined data
/// that will be forwarded to plug-ins and logger.
public var copy: Context? {
let new = Context()
let userData = cmsCreateContextUserData(new)
guard let internalPointer = cmsDupContext(self.internalPointer, userData)
else { return nil }
new.internalPointer = internalPointer
new.errorLog = errorLog
return new
}
/// The handler for error logs.
public var errorLog: ErrorLog? {
didSet {
let log: cmsLogErrorHandlerFunction?
if errorLog != nil {
log = logErrorHandler
} else {
log = nil
}
// set new error handler
cmsSetLogErrorHandlerTHR(internalPointer, log)
}
}
}
// MARK: - Protocol Conformance
extension Context: Copyable { }
// MARK: - Private Functions
/// Creates the user data pointer for use with Little CMS functions.
@_silgen_name("_cmsCreateContextUserDataFromSwiftContext")
private func cmsCreateContextUserData(_ context: Context) -> UnsafeMutableRawPointer {
let unmanaged = Unmanaged.passUnretained(context)
let objectPointer = unmanaged.toOpaque()
return objectPointer
}
/// Gets the Swift `Context` object from the Little CMS opaque type's associated user data.
/// This function will crash if the context was not originally created in Swift.
@_silgen_name("_cmsGetSwiftContext")
internal func cmsGetSwiftContext(_ contextID: cmsContext) -> Context? {
guard let userData = cmsGetContextUserData(contextID)
else { return nil }
let unmanaged = Unmanaged<Context>.fromOpaque(userData)
let context = unmanaged.takeUnretainedValue()
return context
}
/// Function for logging
@_silgen_name("_cmsSwiftLogErrorHandler")
private func logErrorHandler(_ internalPointer: cmsContext?, _ error: cmsUInt32Number, _ messageBuffer: UnsafePointer<Int8>?) {
// get swift context object
let context = cmsGetSwiftContext(internalPointer!)!
let error = LittleCMSError(rawValue: error)
let message: String
if let cString = messageBuffer {
message = String(cString: cString)
} else {
message = ""
}
context.errorLog?(message, error)
}
| mit | c173b5b4c655ce14df0ff6a78bcb1e73 | 27.33557 | 127 | 0.626954 | 5.074519 | false | false | false | false |
CoderYLiu/30DaysOfSwift | Project 11 - ClearTableViewCell/ClearTableViewCell/ClearTableViewController.swift | 1 | 2702 | //
// ClearTableViewController.swift
// ClearTableViewCell <https://github.com/DeveloperLY/30DaysOfSwift>
//
// Created by Liu Y on 16/4/17.
// Copyright © 2016年 DeveloperLY. All rights reserved.
//
// This source code is licensed under the MIT-style license found in the
// LICENSE file in the root directory of this source tree.
//
import UIKit
private let ID = "ClearCell"
class ClearTableViewController: UITableViewController {
var tableData = ["当誓言再次复苏", "吞噬暗夜中舞动的黑翅", "是永不停息的黑洞", "亦是未曾沉睡的赤夜", "永无止尽的锁链只是在宣示", "缠绕里不曾见缔的血眸", "是虚幻中无形的鬼魅", "冷艳犹存的心墙不曾有过融化", "得不到救赎的蓝颜", "独自在罪恶的边缘徘徊", "最后一丝晨光被掠夺", "坠入无边黑夜的灵魂", "祈求地上帝并出现", "让灵魂再一次消逝", "燃放烟火的蔷薇", "黑暗中泯灭的心灵", "阳光下消逝的希望", "墨色洗礼的暗色赤魔", "蓝颜中冰冷的血眸独自叹息", "是因为无法因悲伤", "而选择哭泣"]
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor.black
self.tableView.separatorStyle = UITableViewCellSeparatorStyle.none
self.tableView.rowHeight = 60
self.tableView.tableFooterView = UIView(frame: CGRect.zero)
self.tableView.register(TableViewCell.self, forCellReuseIdentifier: ID)
}
override var prefersStatusBarHidden : Bool {
return true
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return tableData.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: ID, for: indexPath)
cell.textLabel?.text = tableData[indexPath.row]
cell.textLabel?.textColor = UIColor.white
cell.textLabel?.backgroundColor = UIColor.clear
cell.textLabel?.font = UIFont(name: "Avenir Next", size: 18.0)
cell.selectionStyle = UITableViewCellSelectionStyle.none
return cell
}
override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
cell.backgroundColor = colorforIndex(indexPath.row)
}
func colorforIndex(_ index: Int) -> UIColor {
let itemCount = tableData.count - 1
let color = (CGFloat(index) / CGFloat(itemCount)) * 0.6
return UIColor(red: 1.0, green: color, blue: 0.0, alpha: 1.0)
}
}
| mit | e8282031bbd3dad6e4ddcd2c2cfca37b | 37.75 | 291 | 0.682151 | 3.242678 | false | false | false | false |
achimk/Cars | CarsApp/Features/Cars/Details/CarDetailsFlow.swift | 1 | 1247 | //
// CarDetailsFlow.swift
// CarsApp
//
// Created by Joachim Kret on 29/07/2017.
// Copyright © 2017 Joachim Kret. All rights reserved.
//
import Foundation
import UIKit
struct CarDetailsFlow: FlowPresentable {
private let identity: CarIdentityModel
private let detailsService: CarDetailsServiceType
private let errorPresenter: ErrorPresenterType?
init(identity: CarIdentityModel,
detailsService: CarDetailsServiceType,
errorPresenter: ErrorPresenterType?) {
self.identity = identity
self.detailsService = detailsService
self.errorPresenter = errorPresenter
}
func present(using presenter: ViewControllerNavigationType) {
let errorPresenter = ProxyErrorPresenter(self.errorPresenter)
let viewController = CarDetailsViewController(
identity: identity,
service: detailsService,
errorPresenter: errorPresenter
)
if errorPresenter.proxy == nil {
errorPresenter.proxy = RetryErrorPresenter.create(using: viewController)
}
viewController.title = NSLocalizedString("Details", comment: "Details of the car title")
presenter.present(viewController)
}
}
| mit | 36b69f18b25f39e24c358b690ca12b36 | 27.318182 | 96 | 0.689406 | 5.488987 | false | false | false | false |
saeta/penguin | Tests/PenguinPipelineTests/PrefetchBufferTests.swift | 1 | 4035 | // Copyright 2020 Penguin Authors
//
// 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
@testable import PenguinPipeline
final class PrefetchBufferTests: XCTestCase {
func testSynchronousExecution() {
var buffer = PrefetchBuffer<Int>(PrefetchBufferConfiguration())
XCTAssert(buffer.push(.success(1)))
assertSuccess(1, buffer.pop())
XCTAssertFalse(buffer.isEmpty)
XCTAssert(buffer.push(.success(2)))
assertSuccess(2, buffer.pop())
XCTAssertFalse(buffer.isEmpty)
buffer.close()
XCTAssert(buffer.isEmpty)
}
func testClosingWhileFull() {
var buffer = PrefetchBuffer<Int>(PrefetchBufferConfiguration(initialCapacity: 4))
XCTAssert(buffer.push(.success(1)))
XCTAssert(buffer.push(.success(2)))
XCTAssert(buffer.push(.success(3)))
XCTAssertFalse(buffer.isEmpty)
buffer.close()
XCTAssertFalse(buffer.isEmpty)
assertSuccess(1, buffer.pop())
XCTAssertFalse(buffer.isEmpty)
assertSuccess(2, buffer.pop())
XCTAssertFalse(buffer.isEmpty)
assertSuccess(3, buffer.pop())
XCTAssert(buffer.isEmpty)
}
func testCloseWhilePopping() {
if #available(OSX 10.12, *) {
let s1 = DispatchSemaphore(value: 0)
let s2 = DispatchSemaphore(value: 0)
var hasCompleted = false
var buffer = PrefetchBuffer<Int>(PrefetchBufferConfiguration(initialCapacity: 3))
Thread.detachNewThread {
s1.signal() // Popping commenced!
let res = buffer.pop() // This call should block.
XCTAssert(res == nil)
hasCompleted = true
s2.signal()
}
s1.wait()
Thread.sleep(forTimeInterval: 0.0001) // Ensure the other thread wins the race.
XCTAssertFalse(hasCompleted)
buffer.close() // Close the buffer
s2.wait()
XCTAssert(hasCompleted)
}
}
func testCloseWhilePushing() {
if #available(OSX 10.12, *) {
let s1 = DispatchSemaphore(value: 0)
let s2 = DispatchSemaphore(value: 0)
var buffer = PrefetchBuffer<Int>(PrefetchBufferConfiguration(initialCapacity: 3))
var hasCompleted = false
XCTAssert(buffer.push(.success(1)))
XCTAssert(buffer.push(.success(1)))
Thread.detachNewThread {
s1.signal() // Popping commenced!
XCTAssertFalse(buffer.push(.success(1))) // This call should block.
hasCompleted = true
s2.signal()
}
s1.wait()
Thread.sleep(forTimeInterval: 0.0001) // Ensure the other thread wins the race.
XCTAssertFalse(hasCompleted)
buffer.close() // Close the buffer
s2.wait()
XCTAssert(hasCompleted)
XCTAssertFalse(buffer.isEmpty)
assertSuccess(1, buffer.pop())
assertSuccess(1, buffer.pop())
XCTAssertNil(buffer.pop())
}
}
// TODO(saeta): test where consumer wants to stop consuming while producer blocked trying to push.
static var allTests = [
("testSynchronousExecution", testSynchronousExecution),
("testClosingWhileFull", testClosingWhileFull),
("testCloseWhilePopping", testCloseWhilePopping),
("testCloseWhilePushing", testCloseWhilePushing),
]
}
fileprivate func assertSuccess<T: Equatable>(
_ expected: T, _ other: Result<T, Error>?, file: StaticString = #file, line: Int = #line
) {
guard let other = other else {
XCTFail("Got nil when expected \(expected).")
return
}
switch other {
case let .success(other):
XCTAssertEqual(expected, other)
default:
XCTFail("Failure (\(file):\(line)): \(expected) != \(other)")
}
}
| apache-2.0 | e3067027cbb831bc5da8d5206bdd3a14 | 32.347107 | 100 | 0.681784 | 4.207508 | false | true | false | false |
octo-technology/IQKeyboardManager | IQKeyboardManagerSwift/IQToolbar/IQToolbar.swift | 12 | 3382 | //
// IQToolbar.swift
// https://github.com/hackiftekhar/IQKeyboardManager
// Copyright (c) 2013-15 Iftekhar Qurashi.
//
// 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
/** @abstract IQToolbar for IQKeyboardManager. */
public class IQToolbar: UIToolbar , UIInputViewAudioFeedback {
override public class func initialize() {
superclass()?.initialize()
self.appearance().barTintColor = nil
self.appearance().backgroundColor = nil
}
public var titleFont : UIFont? {
didSet {
if let newItems = items {
for item in newItems {
if item is IQTitleBarButtonItem == true {
(item as! IQTitleBarButtonItem).font = titleFont
}
}
}
}
}
public var title : String? {
didSet {
if let newItems = items {
for item in newItems {
if item is IQTitleBarButtonItem == true {
(item as! IQTitleBarButtonItem).title = title
}
}
}
}
}
override init(frame: CGRect) {
super.init(frame: frame)
sizeToFit()
autoresizingMask = UIViewAutoresizing.FlexibleWidth
tintColor = UIColor .blackColor()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
sizeToFit()
autoresizingMask = [UIViewAutoresizing.FlexibleWidth, UIViewAutoresizing.FlexibleHeight]
tintColor = UIColor .blackColor()
}
override public func sizeThatFits(size: CGSize) -> CGSize {
var sizeThatFit = super.sizeThatFits(size)
sizeThatFit.height = 44
return sizeThatFit
}
override public var tintColor: UIColor! {
didSet {
if let unwrappedItems = items {
for item in unwrappedItems {
if item is IQTitleBarButtonItem {
item.tintColor = tintColor
}
}
}
}
}
public var enableInputClicksWhenVisible: Bool {
return true
}
}
| mit | a7876fd980b7583b9c15e7782efcf39b | 30.607477 | 96 | 0.590183 | 5.5625 | false | false | false | false |
OpsLabJPL/MarsImagesIOS | Pods/SwiftMessages/SwiftMessages/Presenter.swift | 3 | 17804 | //
// MessagePresenter.swift
// SwiftMessages
//
// Created by Timothy Moose on 7/30/16.
// Copyright © 2016 SwiftKick Mobile LLC. All rights reserved.
//
import UIKit
protocol PresenterDelegate: AnimationDelegate {
func hide(presenter: Presenter)
}
class Presenter: NSObject {
enum PresentationContext {
case viewController(_: Weak<UIViewController>)
case view(_: Weak<UIView>)
func viewControllerValue() -> UIViewController? {
switch self {
case .viewController(let weak):
return weak.value
case .view:
return nil
}
}
func viewValue() -> UIView? {
switch self {
case .viewController(let weak):
return weak.value?.view
case .view(let weak):
return weak.value
}
}
}
var config: SwiftMessages.Config
let view: UIView
weak var delegate: PresenterDelegate?
let maskingView = MaskingView()
var presentationContext = PresentationContext.viewController(Weak<UIViewController>(value: nil))
let animator: Animator
init(config: SwiftMessages.Config, view: UIView, delegate: PresenterDelegate) {
self.config = config
self.view = view
self.delegate = delegate
self.animator = Presenter.animator(forPresentationStyle: config.presentationStyle, delegate: delegate)
if let identifiable = view as? Identifiable {
id = identifiable.id
} else {
var mutableView = view
id = withUnsafePointer(to: &mutableView) { "\($0)" }
}
super.init()
}
private static func animator(forPresentationStyle style: SwiftMessages.PresentationStyle, delegate: AnimationDelegate) -> Animator {
switch style {
case .top:
return TopBottomAnimation(style: .top, delegate: delegate)
case .bottom:
return TopBottomAnimation(style: .bottom, delegate: delegate)
case .center:
return PhysicsAnimation(delegate: delegate)
case .custom(let animator):
animator.delegate = delegate
return animator
}
}
var id: String
var pauseDuration: TimeInterval? {
let duration: TimeInterval?
switch self.config.duration {
case .automatic:
duration = 2
case .seconds(let seconds):
duration = seconds
case .forever, .indefinite:
duration = nil
}
return duration
}
var showDate: CFTimeInterval?
private var interactivelyHidden = false;
var delayShow: TimeInterval? {
if case .indefinite(let opts) = config.duration { return opts.delay }
return nil
}
/// Returns the required delay for hiding based on time shown
var delayHide: TimeInterval? {
if interactivelyHidden { return 0 }
if case .indefinite(let opts) = config.duration, let showDate = showDate {
let timeIntervalShown = CACurrentMediaTime() - showDate
return max(0, opts.minimum - timeIntervalShown)
}
return nil
}
/*
MARK: - Showing and hiding
*/
func show(completion: @escaping AnimationCompletion) throws {
try presentationContext = getPresentationContext()
install()
self.config.eventListeners.forEach { $0(.willShow) }
showAnimation() { completed in
completion(completed)
if completed {
if self.config.dimMode.modal {
self.showAccessibilityFocus()
} else {
self.showAccessibilityAnnouncement()
}
self.config.eventListeners.forEach { $0(.didShow) }
}
}
}
private func showAnimation(completion: @escaping AnimationCompletion) {
func dim(_ color: UIColor) {
self.maskingView.backgroundColor = UIColor.clear
UIView.animate(withDuration: 0.2, animations: {
self.maskingView.backgroundColor = color
})
}
func blur(style: UIBlurEffect.Style, alpha: CGFloat) {
let blurView = UIVisualEffectView(effect: nil)
blurView.alpha = alpha
maskingView.backgroundView = blurView
UIView.animate(withDuration: 0.3) {
blurView.effect = UIBlurEffect(style: style)
}
}
let context = animationContext()
animator.show(context: context) { (completed) in
completion(completed)
}
switch config.dimMode {
case .none:
break
case .gray:
dim(UIColor(white: 0, alpha: 0.3))
case .color(let color, _):
dim(color)
case .blur(let style, let alpha, _):
blur(style: style, alpha: alpha)
}
}
private func showAccessibilityAnnouncement() {
guard let accessibleMessage = view as? AccessibleMessage,
let message = accessibleMessage.accessibilityMessage else { return }
UIAccessibility.post(notification: UIAccessibility.Notification.announcement, argument: message)
}
private func showAccessibilityFocus() {
guard let accessibleMessage = view as? AccessibleMessage,
let focus = accessibleMessage.accessibilityElement ?? accessibleMessage.additonalAccessibilityElements?.first else { return }
UIAccessibility.post(notification: UIAccessibility.Notification.layoutChanged, argument: focus)
}
var isHiding = false
func hide(animated: Bool, completion: @escaping AnimationCompletion) {
isHiding = true
self.config.eventListeners.forEach { $0(.willHide) }
let context = animationContext()
let action = {
if let viewController = self.presentationContext.viewControllerValue() as? WindowViewController {
viewController.uninstall()
}
self.maskingView.removeFromSuperview()
completion(true)
self.config.eventListeners.forEach { $0(.didHide) }
}
guard animated else {
action()
return
}
animator.hide(context: context) { (completed) in
action()
}
func undim() {
UIView.animate(withDuration: 0.2, delay: 0, options: .beginFromCurrentState, animations: {
self.maskingView.backgroundColor = UIColor.clear
}, completion: nil)
}
func unblur() {
guard let view = maskingView.backgroundView as? UIVisualEffectView else { return }
UIView.animate(withDuration: 0.2, delay: 0, options: .beginFromCurrentState, animations: {
view.effect = nil
}, completion: nil)
}
switch config.dimMode {
case .none:
break
case .gray:
undim()
case .color:
undim()
case .blur:
unblur()
}
}
private func animationContext() -> AnimationContext {
return AnimationContext(messageView: view, containerView: maskingView, safeZoneConflicts: safeZoneConflicts(), interactiveHide: config.interactiveHide)
}
private func safeZoneConflicts() -> SafeZoneConflicts {
guard let window = maskingView.window else { return [] }
let windowLevel: UIWindow.Level = {
if let vc = presentationContext.viewControllerValue() as? WindowViewController {
return vc.windowLevel
}
return UIWindow.Level.normal
}()
// TODO `underNavigationBar` and `underTabBar` should look up the presentation context's hierarchy
// TODO for cases where both should be true (probably not an issue for typical height messages, though).
let underNavigationBar: Bool = {
if let vc = presentationContext.viewControllerValue() as? UINavigationController { return vc.sm_isVisible(view: vc.navigationBar) }
return false
}()
let underTabBar: Bool = {
if let vc = presentationContext.viewControllerValue() as? UITabBarController { return vc.sm_isVisible(view: vc.tabBar) }
return false
}()
if #available(iOS 11, *) {
if windowLevel > UIWindow.Level.normal {
// TODO seeing `maskingView.safeAreaInsets.top` value of 20 on
// iPhone 8 with status bar window level. This seems like an iOS bug since
// the message view's window is above the status bar. Applying a special rule
// to allow the animator to revove this amount from the layout margins if needed.
// This may need to be reworked if any future device has a legitimate 20pt top safe area,
// such as with a potentially smaller notch.
if maskingView.safeAreaInsets.top == 20 {
return [.overStatusBar]
} else {
var conflicts: SafeZoneConflicts = []
if maskingView.safeAreaInsets.top > 0 {
conflicts.formUnion(.sensorNotch)
}
if maskingView.safeAreaInsets.bottom > 0 {
conflicts.formUnion(.homeIndicator)
}
return conflicts
}
}
var conflicts: SafeZoneConflicts = []
if !underNavigationBar {
conflicts.formUnion(.sensorNotch)
}
if !underTabBar {
conflicts.formUnion(.homeIndicator)
}
return conflicts
} else {
#if SWIFTMESSAGES_APP_EXTENSIONS
return []
#else
if UIApplication.shared.isStatusBarHidden { return [] }
if (windowLevel > UIWindow.Level.normal) || underNavigationBar { return [] }
let statusBarFrame = UIApplication.shared.statusBarFrame
let statusBarWindowFrame = window.convert(statusBarFrame, from: nil)
let statusBarViewFrame = maskingView.convert(statusBarWindowFrame, from: nil)
return statusBarViewFrame.intersects(maskingView.bounds) ? SafeZoneConflicts.statusBar : []
#endif
}
}
private func getPresentationContext() throws -> PresentationContext {
func newWindowViewController(_ windowLevel: UIWindow.Level) -> UIViewController {
let viewController = WindowViewController.newInstance(windowLevel: windowLevel, config: config)
return viewController
}
switch config.presentationContext {
case .automatic:
#if SWIFTMESSAGES_APP_EXTENSIONS
throw SwiftMessagesError.noRootViewController
#else
if let rootViewController = UIApplication.shared.keyWindow?.rootViewController {
let viewController = rootViewController.sm_selectPresentationContextTopDown(config)
return .viewController(Weak(value: viewController))
} else {
throw SwiftMessagesError.noRootViewController
}
#endif
case .window(let level):
let viewController = newWindowViewController(level)
return .viewController(Weak(value: viewController))
case .viewController(let viewController):
let viewController = viewController.sm_selectPresentationContextBottomUp(config)
return .viewController(Weak(value: viewController))
case .view(let view):
return .view(Weak(value: view))
}
}
/*
MARK: - Installation
*/
func install() {
func topLayoutConstraint(view: UIView, containerView: UIView, viewController: UIViewController?) -> NSLayoutConstraint {
if case .top = config.presentationStyle, let nav = viewController as? UINavigationController, nav.sm_isVisible(view: nav.navigationBar) {
return NSLayoutConstraint(item: view, attribute: .top, relatedBy: .equal, toItem: nav.navigationBar, attribute: .bottom, multiplier: 1.00, constant: 0.0)
}
return NSLayoutConstraint(item: view, attribute: .top, relatedBy: .equal, toItem: containerView, attribute: .top, multiplier: 1.00, constant: 0.0)
}
func bottomLayoutConstraint(view: UIView, containerView: UIView, viewController: UIViewController?) -> NSLayoutConstraint {
if case .bottom = config.presentationStyle, let tab = viewController as? UITabBarController, tab.sm_isVisible(view: tab.tabBar) {
return NSLayoutConstraint(item: view, attribute: .bottom, relatedBy: .equal, toItem: tab.tabBar, attribute: .top, multiplier: 1.00, constant: 0.0)
}
return NSLayoutConstraint(item: view, attribute: .bottom, relatedBy: .equal, toItem: containerView, attribute: .bottom, multiplier: 1.00, constant: 0.0)
}
func installMaskingView(containerView: UIView) {
maskingView.translatesAutoresizingMaskIntoConstraints = false
if let nav = presentationContext.viewControllerValue() as? UINavigationController {
containerView.insertSubview(maskingView, belowSubview: nav.navigationBar)
} else if let tab = presentationContext.viewControllerValue() as? UITabBarController {
containerView.insertSubview(maskingView, belowSubview: tab.tabBar)
} else {
containerView.addSubview(maskingView)
}
maskingView.leadingAnchor.constraint(equalTo: containerView.leadingAnchor).isActive = true
maskingView.trailingAnchor.constraint(equalTo: containerView.trailingAnchor).isActive = true
topLayoutConstraint(view: maskingView, containerView: containerView, viewController: presentationContext.viewControllerValue()).isActive = true
bottomLayoutConstraint(view: maskingView, containerView: containerView, viewController: presentationContext.viewControllerValue()).isActive = true
if let keyboardTrackingView = config.keyboardTrackingView {
maskingView.install(keyboardTrackingView: keyboardTrackingView)
}
// Update the container view's layout in order to know the masking view's frame
containerView.layoutIfNeeded()
}
func installInteractive() {
guard config.dimMode.modal else { return }
if config.dimMode.interactive {
maskingView.tappedHander = { [weak self] in
guard let strongSelf = self else { return }
strongSelf.interactivelyHidden = true
strongSelf.delegate?.hide(presenter: strongSelf)
}
} else {
// There's no action to take, but the presence of
// a tap handler prevents interaction with underlying views.
maskingView.tappedHander = { }
}
}
func installAccessibility() {
var elements: [NSObject] = []
if let accessibleMessage = view as? AccessibleMessage {
if let message = accessibleMessage.accessibilityMessage {
let element = accessibleMessage.accessibilityElement ?? view
element.isAccessibilityElement = true
if element.accessibilityLabel == nil {
element.accessibilityLabel = message
}
elements.append(element)
}
if let additional = accessibleMessage.additonalAccessibilityElements {
elements += additional
}
}
if config.dimMode.interactive {
let dismissView = UIView(frame: maskingView.bounds)
dismissView.translatesAutoresizingMaskIntoConstraints = true
dismissView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
maskingView.addSubview(dismissView)
maskingView.sendSubviewToBack(dismissView)
dismissView.isUserInteractionEnabled = false
dismissView.isAccessibilityElement = true
dismissView.accessibilityLabel = config.dimModeAccessibilityLabel
dismissView.accessibilityTraits = UIAccessibilityTraits.button
elements.append(dismissView)
}
if config.dimMode.modal {
maskingView.accessibilityViewIsModal = true
}
maskingView.accessibleElements = elements
}
guard let containerView = presentationContext.viewValue() else { return }
if let windowViewController = presentationContext.viewControllerValue() as? WindowViewController {
if #available(iOS 13, *) {
let scene = UIApplication.shared.keyWindow?.windowScene
windowViewController.install(becomeKey: becomeKeyWindow, scene: scene)
} else {
windowViewController.install(becomeKey: becomeKeyWindow)
}
}
installMaskingView(containerView: containerView)
installInteractive()
installAccessibility()
}
private var becomeKeyWindow: Bool {
if config.becomeKeyWindow == .some(true) { return true }
switch config.dimMode {
case .gray, .color, .blur:
// Should become key window in modal presentation style
// for proper VoiceOver handling.
return true
case .none:
return false
}
}
}
| apache-2.0 | c9797bb8b9869c0cc3f1da55e28c1c69 | 40.020737 | 169 | 0.609223 | 5.539203 | false | true | false | false |
lstn-ltd/lstn-sdk-ios | Lstn/Classes/Remote/SystemRemoteControl.swift | 1 | 4307 | //
// SystemRemoteControl.swift
// Pods
//
// Created by Dan Halliday on 10/11/2016.
//
//
import UIKit
import MediaPlayer
class SystemRemoteControl: NSObject, RemoteControl {
var item: RemoteControlItem? = nil
var playing: Bool = false
var position: Double = 0
var artwork: MPMediaItemArtwork? = nil
weak var delegate: RemoteControlDelegate? = nil
override init() {
super.init()
self.registerForCommands()
}
func itemDidChange(item: RemoteControlItem?) {
self.item = item
self.updateNowPlayingInfo()
self.updateImage(image: item?.image)
}
func playbackDidStart(position: Double) {
self.playing = true
self.position = position
self.updateNowPlayingInfo()
}
func playbackDidStop(position: Double) {
self.playing = false
self.position = position
self.updateNowPlayingInfo()
}
func nowPlayingInfo(item: RemoteControlItem) -> [String:Any] {
var info: [String:Any] = [
MPMediaItemPropertyTitle: item.title,
MPMediaItemPropertyArtist: item.author,
MPMediaItemPropertyAlbumTitle: item.publisher,
MPMediaItemPropertyPodcastTitle: item.publisher,
MPMediaItemPropertyGenre: "podcast",
MPMediaItemPropertyAssetURL: item.url.absoluteString,
MPMediaItemPropertyPlaybackDuration: item.duration,
MPNowPlayingInfoPropertyPlaybackRate: self.playing ? 1 : 0,
MPNowPlayingInfoPropertyElapsedPlaybackTime: self.position
]
if let artwork = self.artwork {
info[MPMediaItemPropertyArtwork] = artwork
}
return info
}
func updateNowPlayingInfo() {
guard let item = self.item else {
return
}
MPNowPlayingInfoCenter.default().nowPlayingInfo = self.nowPlayingInfo(item: item)
}
func registerForCommands() {
let center = MPRemoteCommandCenter.shared()
center.playCommand.addTarget(self, action: #selector(self.playCommandDidFire))
center.pauseCommand.addTarget(self, action: #selector(self.pauseCommandDidFire))
center.togglePlayPauseCommand.addTarget(self, action: #selector(self.toggleCommandDidFire))
center.stopCommand.addTarget(self, action: #selector(self.stopCommandDidFire))
center.nextTrackCommand.addTarget(self, action: #selector(self.nextCommandDidFire))
center.previousTrackCommand.addTarget(self, action: #selector(self.previousCommandDidFire))
}
private func updateImage(image: URL?) {
guard let image = image else { return }
DispatchQueue.global(qos: .background).async {
let data: Data
do { data = try Data(contentsOf: image) } catch {
return
}
guard let image = UIImage(data: data) else {
return
}
let artwork = MPMediaItemArtwork(boundsSize: CGSize(width: 120, height: 120)) { size in
return image
}
self.artwork = artwork
self.updateNowPlayingInfo()
}
}
deinit {
let center = MPRemoteCommandCenter.shared()
center.playCommand.removeTarget(self)
center.pauseCommand.removeTarget(self)
center.togglePlayPauseCommand.removeTarget(self)
center.stopCommand.removeTarget(self)
center.nextTrackCommand.removeTarget(self)
center.previousTrackCommand.removeTarget(self)
}
}
// MARK: - Remote Command Handlers
extension SystemRemoteControl {
@objc func playCommandDidFire() {
self.delegate?.playCommandDidFire()
}
@objc func pauseCommandDidFire() {
self.delegate?.pauseCommandDidFire()
}
@objc func toggleCommandDidFire() {
self.delegate?.toggleCommandDidFire()
}
@objc func stopCommandDidFire() {
self.delegate?.pauseCommandDidFire()
}
@objc func previousCommandDidFire() {
self.delegate?.previousCommandDidFire()
}
@objc func nextCommandDidFire() {
self.delegate?.nextCommandDidFire()
}
@objc func changePlaybackRateCommandDidFire() {
// TODO: Implement rate change logic
}
}
| mit | 554ebbaacc8e55618f32ba237b0d7e8d | 23.752874 | 99 | 0.642675 | 5.019814 | false | false | false | false |
mownier/photostream | Photostream/UI/User Post/UserPostViewDataSource.swift | 1 | 2121 | //
// UserPostViewDataSource.swift
// Photostream
//
// Created by Mounir Ybanez on 09/12/2016.
// Copyright © 2016 Mounir Ybanez. All rights reserved.
//
import UIKit
extension UserPostViewController {
override func numberOfSections(in collectionView: UICollectionView) -> Int {
switch sceneType {
case .grid:
return 1
case .list:
return presenter.postCount
}
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
switch sceneType {
case .grid:
return presenter.postCount
case .list:
return 1
}
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
switch sceneType {
case .grid:
let cell = PostGridCollectionCell.dequeue(from: collectionView, for: indexPath)!
let item = presenter.post(at: indexPath.row) as? PostGridCollectionCellItem
cell.configure(with: item)
return cell
case .list:
let cell = PostListCollectionCell.dequeue(from: collectionView, for: indexPath)!
let item = presenter.post(at: indexPath.section) as? PostListCollectionCellItem
cell.configure(with: item)
cell.delegate = self
return cell
}
}
override func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
switch kind {
case UICollectionElementKindSectionHeader where sceneType == .list:
let header = PostListCollectionHeader.dequeue(from: collectionView, for: indexPath)!
let item = presenter.post(at: indexPath.section) as? PostListCollectionHeaderItem
header.configure(with: item)
return header
default:
return UICollectionReusableView()
}
}
}
| mit | ea6c94fcdc469ec28e3416d31a635bef | 32.650794 | 171 | 0.626415 | 5.76087 | false | false | false | false |
B-Lach/PocketCastsKit | SharedSource/API/NetworkManager/Protocol/NetworkManagerProtocol.swift | 1 | 1307 | //
// NetworkManagerProtocol.swift
// PocketCastsKit
//
// Created by Benny Lach on 17.08.17.
// Copyright © 2017 Benny Lach. All rights reserved.
//
import Foundation
/// HTTP Method Types
///
/// - GET: Get Reguest
/// - POST: Post Reguest
enum MethodType: String {
case GET = "GET"
case POST = "POST"
}
extension MethodType: Equatable {
static func ==(lhs: MethodType, rhs: MethodType) -> Bool {
return lhs.rawValue == rhs.rawValue
}
}
/// Possible options for a network request
///
/// - headerField]: Array of header fields to set
/// - bodyData: Body of the request
/// - urlParameter: URL Parameters
enum RequestOption {
case headerField([(key: String, value: String)])
case bodyData(data: Data)
case urlParameter([String: Any])
}
internal typealias completion<T> = ((Result<T>) -> Void)
protocol NetworkManagerProtocol {
/// Method to make a network request
///
/// - Parameters:
/// - url: the URL of the request
/// - options: Options to use for the request
/// - method: The HTTP Method to use
/// - completion: The CompletionHandler called after the request finished
func makeRequest(url: URL, options: [RequestOption], method: MethodType, completion: @escaping completion<(Data, HTTPURLResponse)>)
}
| mit | fc6c1352cd5dbd668d0b12643a9820a7 | 24.607843 | 135 | 0.660796 | 4.068536 | false | false | false | false |
seandavidmcgee/HumanKontactBeta | src/keyboardTest/DNVAvatarView.swift | 1 | 6110 | //
// DNVAvatarView.swift
// DNVAvatar
//
// Created by Alexey Demin on 18/11/14.
// Copyright (c) 2014 Alexey Demin. All rights reserved.
//
import UIKit
struct DNVAvatar {
var image: UIImage?
var initials: NSString
var color = UIColor.whiteColor()
var backgroundColor: UIColor
init(initials: NSString, backgroundColor: UIColor) {
self.initials = initials
self.backgroundColor = backgroundColor
}
}
class DNVAvatarView: UIView {
var avatar: DNVAvatar?
var avatars: (DNVAvatar, DNVAvatar)?
class func imageWithInitials(initials: NSString, color: UIColor, backgroundColor: UIColor, size: CGSize) -> UIImage {
UIGraphicsBeginImageContextWithOptions(CGSizeMake(size.width, size.height), true, 0)
let context = UIGraphicsGetCurrentContext()
backgroundColor.setFill()
CGContextFillRect(context, CGRectMake(0, 0, size.width, size.height))
let font = UIFont(name: "Helvetica Bold", size: size.height / CGFloat(initials.length + 1))!
let style = NSParagraphStyle.defaultParagraphStyle().mutableCopy() as! NSMutableParagraphStyle
style.alignment = NSTextAlignment.Center
let attributes = [NSFontAttributeName: font, NSForegroundColorAttributeName: color, NSParagraphStyleAttributeName: style]
let height = initials.sizeWithAttributes(attributes).height
initials.drawInRect(CGRectMake(0, (size.height - height) / 2.0, size.width, height), withAttributes: attributes)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
/*
class func resizeImage(image: UIImage, width: CGFloat, height: CGFloat) -> UIImage {
let scale = max(width / image.size.width, height / image.size.height)
UIGraphicsBeginImageContextWithOptions(CGSizeMake(width, height), true, 0)
image.drawInRect(CGRectMake(-(image.size.width * scale - width) / 2, -(image.size.height * scale - height) / 2, image.size.width * scale, image.size.height * scale))
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
*/
class func resizeImage(image: UIImage, size: CGSize, offset: CGPoint) -> UIImage {
let scale = max((size.width + abs(offset.x)) / image.size.width, (size.height + abs(offset.y)) / image.size.height)
UIGraphicsBeginImageContextWithOptions(CGSizeMake(size.width, size.height), true, 0)
image.drawInRect(CGRectMake(-(image.size.width * scale - size.width) / 2.0 + offset.x / 2.0, -(image.size.height * scale - size.height) / 2.0 + offset.y / 2.0, image.size.width * scale, image.size.height * scale))
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
class func roundAvatarWithImages(images: (UIImage, (UIImage, UIImage)?), diameter: CGFloat) -> UIImage {
var avatar : UIImage
if let multipleImages = images.1 {
let spacing = diameter / 60.0
let image1 = resizeImage(images.0, size: CGSizeMake(diameter / 2 - spacing / 2, diameter), offset: CGPointMake(diameter / 30, 0))
let image2 = resizeImage(multipleImages.0, size: CGSizeMake(diameter / 2 - spacing / 2, diameter / 2 - spacing / 2), offset: CGPointMake(-diameter / 20, diameter / 20))
let image3 = resizeImage(multipleImages.1, size: CGSizeMake(diameter / 2 - spacing / 2, diameter / 2 - spacing / 2), offset: CGPointMake(-diameter / 20, -diameter / 20))
UIGraphicsBeginImageContextWithOptions(CGSizeMake(diameter, diameter), false, 0)
image1.drawAtPoint(CGPointMake(0, 0))
image2.drawAtPoint(CGPointMake(diameter / 2 + spacing / 2, 0))
image3.drawAtPoint(CGPointMake(diameter / 2 + spacing / 2, diameter / 2 + spacing / 2))
avatar = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
}
else {
avatar = resizeImage(images.0, size: CGSizeMake(diameter, diameter), offset: CGPointZero)
}
UIGraphicsBeginImageContextWithOptions(CGSizeMake(diameter, diameter), false, 0)
let path = UIBezierPath(ovalInRect: CGRectMake(0, 0, diameter, diameter))
path.addClip()
avatar.drawAtPoint(CGPointZero)
avatar = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return avatar
}
/*
class func roundAvatarWithImage(image: UIImage) -> UIImage {
let side = min(image.size.width, image.size.height)
UIGraphicsBeginImageContext(CGSizeMake(side, side))
let path = UIBezierPath(ovalInRect: CGRectMake(0, 0, side, side))
path.addClip()
image.drawAtPoint(CGPointMake(-(image.size.width - side) / 2, -(image.size.height - side) / 2))
let avatar = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return avatar
}
*/
override func drawRect(rect: CGRect) {
var image: UIImage
var images: (UIImage, UIImage)?
if let avatar = self.avatar {
image = avatar.image ?? DNVAvatarView.imageWithInitials(avatar.initials, color: avatar.color, backgroundColor: avatar.backgroundColor, size: rect.size)
}
else {
return
}
if let avatars = self.avatars {
images = (avatars.0.image ?? DNVAvatarView.imageWithInitials(avatars.0.initials, color: avatars.0.color, backgroundColor: avatars.0.backgroundColor, size: rect.size),
avatars.1.image ?? DNVAvatarView.imageWithInitials(avatars.1.initials, color: avatars.1.color, backgroundColor: avatars.1.backgroundColor, size: rect.size))
}
let avatar = DNVAvatarView.roundAvatarWithImages((image, images), diameter: max(rect.size.width, rect.size.height))
avatar.drawInRect(rect)
}
}
| mit | 4e7969361a1f8c58e76ff3e8dbeaed57 | 46 | 221 | 0.659083 | 4.736434 | false | false | false | false |
jinxiansen/jinxiansen.github.io | core/EFResume/Extension/String+.swift | 2 | 3611 | //
// String+.swift
// EyreFree
//
// Created by EyreFree on 2017/9/13.
//
// Copyright (c) 2017 EyreFree <[email protected]>
//
// This file is part of EFResume.
//
// EFResume is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// EFResume is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
import Foundation
extension String {
// [] 操作符重载
subscript(index: Int) -> Character {
return self[self.index(self.startIndex, offsetBy: index)]
}
// 字符数量
func count() -> Int {
return self.characters.count
}
// 是否符合输入的正则表达式
func conform(regex: String) -> Bool {
return NSPredicate(format: "SELF MATCHES %@", regex).evaluate(with: self)
}
// 子串数量
func occurrencesOf(subString: String) -> Int {
return self.components(separatedBy: subString).count - 1
}
// 替换某个子字符串为另一字符串
func replace(_ string: String, with: String, options: CompareOptions? = nil) -> String {
if let options = options {
return self.replacingOccurrences(of: string, with: with, options: options, range: nil)
}
return self.replacingOccurrences(of: string, with: with)
}
// 替换前缀
func replacePrefix(string: String, with: String) -> String {
if self.hasPrefix(string) {
return with + String(self.characters.dropFirst(string.count()))
}
return self
}
// 替换尾缀
func replaceSuffix(string: String, with: String) -> String {
if self.hasSuffix(string) {
return String(self.characters.dropLast(string.count())) + with
}
return self
}
// 移除某个子串
func remove(string: String) -> String {
return self.replace(string, with: "")
}
// 移除某个前缀
func removePrefix(string: String) -> String {
return self.replacePrefix(string: string, with: "")
}
// 移除某个尾缀
func removeSuffix(string: String) -> String {
return self.replaceSuffix(string: string, with: "")
}
// 将多个连续重复字符变为一个
func toOne() -> String {
var outString = self
let length = self.characters.count
for index in (1 ..< length).reversed() {
if outString[index] == outString[index - 1] {
outString.remove(at: outString.index(outString.startIndex, offsetBy: index))
}
}
return outString
}
// 清除字符串左右空格和换行
func clean() -> String {
return self.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
}
// MARK:- HTML
// 添加超链接
func a(link: String) -> String {
return "<a href='\(link)'>\(self)</a>"
}
// 添加 Strong
func strong() -> String {
return "<strong>\(self)</strong>"
}
// 添加 P
func p() -> String {
return "<p>\(self)</p>"
}
// 添加 Div
func div() -> String {
return "<div>\(self)</div>"
}
}
| mit | e5aab5132ff576ec6ed4afc61c7e02d9 | 26.491935 | 98 | 0.604869 | 3.95935 | false | false | false | false |
mojio/mojio-ios-sdk | MojioSDK/Models/Address.swift | 1 | 1323 | //
// Address.swift
// MojioSDK
//
// Created by Ashish Agarwal on 2016-02-11.
// Copyright © 2016 Mojio. All rights reserved.
//
import UIKit
import ObjectMapper
public class Address: Mappable {
public dynamic var HouseNumber : String? = nil
public dynamic var Road : String? = nil
public dynamic var Neighbourhood : String? = nil
public dynamic var Suburb : String? = nil
public dynamic var City : String? = nil
public dynamic var County : String? = nil
public dynamic var State : String? = nil
public dynamic var PostCode : String? = nil
public dynamic var Country : String? = nil
public dynamic var CountryCode : String? = nil
public dynamic var FormattedAddress : String? = nil
public required convenience init?(_ map: Map) {
self.init()
}
public required init() {
}
public func mapping(map: Map) {
HouseNumber <- map["HouseNumber"]
Road <- map["Road"]
Neighbourhood <- map["Neighbourhood"]
Suburb <- map["Suburb"]
City <- map["City"]
County <- map["County"]
State <- map["State"]
PostCode <- map["PostCode"]
Country <- map["Country"]
CountryCode <- map["CountryCode"]
FormattedAddress <- map["FormattedAddress"]
}
}
| mit | edf1f118fc5822791192ce96b5dd009e | 26.541667 | 55 | 0.610439 | 4.250804 | false | false | false | false |
appsquickly/backdrop | source/CommandLine/Option.swift | 3 | 7018 | /*
* Option.swift
* Copyright (c) 2014 Ben Gollmer.
*
* 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.
*/
/**
* The base class for a command-line option.
*/
public class Option {
public let shortFlag: String?
public let longFlag: String?
public let required: Bool
public let helpMessage: String
/** True if the option was set when parsing command-line arguments */
public var wasSet: Bool {
return false
}
public var flagDescription: String {
switch (shortFlag, longFlag) {
case (let sf, let lf) where sf != nil && lf != nil:
return "\(ShortOptionPrefix)\(sf!), \(LongOptionPrefix)\(lf!)"
case (_, let lf) where lf != nil:
return "\(LongOptionPrefix)\(lf!)"
default:
return "\(ShortOptionPrefix)\(shortFlag!)"
}
}
private init(_ shortFlag: String?, _ longFlag: String?, _ required: Bool, _ helpMessage: String) {
if let sf = shortFlag {
assert(sf.characters.count == 1, "Short flag must be a single character")
assert(Int(sf) == nil && sf.toDouble() == nil, "Short flag cannot be a numeric value")
}
if let lf = longFlag {
assert(Int(lf) == nil && lf.toDouble() == nil, "Long flag cannot be a numeric value")
}
self.shortFlag = shortFlag
self.longFlag = longFlag
self.helpMessage = helpMessage
self.required = required
}
/* The optional casts in these initalizers force them to call the private initializer. Without
* the casts, they recursively call themselves.
*/
/** Initializes a new Option that has both long and short flags. */
public convenience init(shortFlag: String, longFlag: String, required: Bool = false, helpMessage: String) {
self.init(shortFlag as String?, longFlag, required, helpMessage)
}
/** Initializes a new Option that has only a short flag. */
public convenience init(shortFlag: String, required: Bool = false, helpMessage: String) {
self.init(shortFlag as String?, nil, required, helpMessage)
}
/** Initializes a new Option that has only a long flag. */
public convenience init(longFlag: String, required: Bool = false, helpMessage: String) {
self.init(nil, longFlag as String?, required, helpMessage)
}
func flagMatch(flag: String) -> Bool {
return flag == shortFlag || flag == longFlag
}
func setValue(values: [String]) -> Bool {
return false
}
}
/**
* A boolean option. The presence of either the short or long flag will set the value to true;
* absence of the flag(s) is equivalent to false.
*/
public class BoolOption: Option {
private var _value: Bool = false
public var value: Bool {
return _value
}
override public var wasSet: Bool {
return _value
}
override func setValue(values: [String]) -> Bool {
_value = true
return true
}
}
/** An option that accepts a positive or negative integer value. */
public class IntOption: Option {
private var _value: Int?
public var value: Int? {
return _value
}
override public var wasSet: Bool {
return _value != nil
}
override func setValue(values: [String]) -> Bool {
if values.count == 0 {
return false
}
if let val = Int(values[0]) {
_value = val
return true
}
return false
}
}
/**
* An option that represents an integer counter. Each time the short or long flag is found
* on the command-line, the counter will be incremented.
*/
public class CounterOption: Option {
private var _value: Int = 0
public var value: Int {
return _value
}
override public var wasSet: Bool {
return _value > 0
}
override func setValue(values: [String]) -> Bool {
_value += 1
return true
}
}
/** An option that accepts a positive or negative floating-point value. */
public class DoubleOption: Option {
private var _value: Double?
public var value: Double? {
return _value
}
override public var wasSet: Bool {
return _value != nil
}
override func setValue(values: [String]) -> Bool {
if values.count == 0 {
return false
}
if let val = values[0].toDouble() {
_value = val
return true
}
return false
}
}
/** An option that accepts a string value. */
public class StringOption: Option {
private var _value: String? = nil
public var value: String? {
return _value
}
override public var wasSet: Bool {
return _value != nil
}
override func setValue(values: [String]) -> Bool {
if values.count == 0 {
return false
}
_value = values[0]
return true
}
}
/** An option that accepts one or more string values. */
public class MultiStringOption: Option {
private var _value: [String]?
public var value: [String]? {
return _value
}
override public var wasSet: Bool {
return _value != nil
}
override func setValue(values: [String]) -> Bool {
if values.count == 0 {
return false
}
_value = values
return true
}
}
/** An option that represents an enum value. */
public class EnumOption<T:RawRepresentable where T.RawValue == String>: Option {
private var _value: T?
public var value: T? {
return _value
}
override public var wasSet: Bool {
return _value != nil
}
/* Re-defining the intializers is necessary to make the Swift 2 compiler happy, as
* of Xcode 7 beta 2.
*/
private override init(_ shortFlag: String?, _ longFlag: String?, _ required: Bool, _ helpMessage: String) {
super.init(shortFlag, longFlag, required, helpMessage)
}
/** Initializes a new Option that has both long and short flags. */
public convenience init(shortFlag: String, longFlag: String, required: Bool = false, helpMessage: String) {
self.init(shortFlag as String?, longFlag, required, helpMessage)
}
/** Initializes a new Option that has only a short flag. */
public convenience init(shortFlag: String, required: Bool = false, helpMessage: String) {
self.init(shortFlag as String?, nil, required, helpMessage)
}
/** Initializes a new Option that has only a long flag. */
public convenience init(longFlag: String, required: Bool = false, helpMessage: String) {
self.init(nil, longFlag as String?, required, helpMessage)
}
override func setValue(values: [String]) -> Bool {
if values.count == 0 {
return false
}
if let v = T(rawValue: values[0]) {
_value = v
return true
}
return false
}
}
| apache-2.0 | 91eac782875118b45654678f0482c535 | 24.896679 | 109 | 0.648903 | 4.167458 | false | false | false | false |
lennet/proNotes | app/proNotes/Document/PageView/PageView.swift | 1 | 8933 | //
// PageView.swift
// proNotes
//
// Created by Leo Thomas on 29/11/15.
// Copyright © 2015 leonardthomas. All rights reserved.
//
import UIKit
class PageView: UIView, UIGestureRecognizerDelegate {
var panGestureRecognizer: UIPanGestureRecognizer?
var tapGestureRecognizer: UITapGestureRecognizer?
weak var page: DocumentPage?
weak var selectedSubView: PageSubView? {
didSet {
oldValue?.setDeselected?()
selectedSubView?.setSelected?()
if selectedSubView == nil {
SettingsViewController.sharedInstance?.currentType = .pageInfo
}
PagesTableViewController.sharedInstance?.twoTouchesForScrollingRequired = selectedSubView != nil
}
}
subscript(subViewIndex: Int) -> PageSubView? {
get {
if subViewIndex < subviews.count {
return subviews[subViewIndex] as? PageSubView
}
return nil
}
}
/**
- parameter page: DocumentPage to display
- parameter renderMode: Optional Bool var which disables GestureRecognizers and AutoLayout for better render Perfomance
*/
init(page: DocumentPage, renderMode: Bool = false) {
super.init(frame: CGRect(origin: .zero, size: page.size))
self.page = page
commonInit(renderMode)
setUpLayer(renderMode)
setNeedsDisplay()
}
override init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
func commonInit(_ renderMode: Bool = false) {
if !renderMode {
setUpTouchRecognizer()
}
clearsContextBeforeDrawing = true
backgroundColor = UIColor.white
}
func setUpTouchRecognizer() {
panGestureRecognizer = UIPanGestureRecognizer(target: self, action: #selector(PageView.handlePan(_:)))
panGestureRecognizer?.cancelsTouchesInView = true
panGestureRecognizer?.delegate = self
panGestureRecognizer?.maximumNumberOfTouches = 1
addGestureRecognizer(panGestureRecognizer!)
tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(PageView.handleTap(_:)))
tapGestureRecognizer?.cancelsTouchesInView = true
tapGestureRecognizer?.delegate = self
addGestureRecognizer(tapGestureRecognizer!)
}
func setUpLayer(_ renderMode: Bool = false) {
removeAllSubViews()
guard let page = page else {
return
}
frame.size = page.size
for layer in page.layers {
addSubView(for: layer, renderMode: renderMode)
}
}
func addSubView(for layer: DocumentLayer, renderMode: Bool = false) {
switch layer {
case let pdfLayer as PDFLayer:
addPDFView(pdfLayer)
break
case let sketchLayer as SketchLayer:
addSketchView(sketchLayer)
break
case let imageLayer as ImageLayer:
addImageView(imageLayer, renderMode: renderMode)
break
case let textLayer as TextLayer:
addTextView(textLayer, renderMode: renderMode)
break
default:
break
}
}
func addPDFView(_ pdfLayer: PDFLayer) {
let view = PDFView(pdfData: pdfLayer.pdfData!, frame: bounds)
view.backgroundColor = UIColor.clear
view.isHidden = pdfLayer.hidden
addSubview(view)
}
func addSketchView(_ sketchLayer: SketchLayer) {
let view = SketchView(sketchLayer: sketchLayer, frame: bounds)
view.backgroundColor = UIColor.clear
view.isHidden = sketchLayer.hidden
addSubview(view)
}
func addImageView(_ imageLayer: ImageLayer, renderMode: Bool = false) {
let frame = CGRect(origin: imageLayer.origin, size: imageLayer.size)
let view = MovableImageView(frame: frame, movableLayer: imageLayer, renderMode: renderMode)
view.isHidden = imageLayer.hidden
addSubview(view)
view.setUpImageView()
}
func addTextView(_ textLayer: TextLayer, renderMode: Bool = false) {
let frame = CGRect(origin: textLayer.origin, size: textLayer.size)
let view = MovableTextView(frame: frame, movableLayer: textLayer, renderMode: renderMode)
view.isHidden = textLayer.hidden
addSubview(view)
view.setUpTextView()
}
func getSketchViews() -> [SketchView] {
var result = [SketchView]()
for case let sketchView as SketchView in subviews {
result.append(sketchView)
}
return result
}
func handleSketchButtonPressed() {
guard subviews.count > 0,
let subview = subviews.last as? SketchView else {
addSketchLayer()
return
}
selectedSubView = subview
selectedSubView?.setSelected?()
}
func addSketchLayer() {
if let sketchLayer = page?.addSketchLayer(nil) {
addSketchView(sketchLayer)
handleSketchButtonPressed()
}
}
func setLayerSelected(_ index: Int) {
selectedSubView?.setSelected?()
selectedSubView = nil
if let subview = self[index] {
subview.setSelected?()
selectedSubView = subview
setSubviewsAlpha(index + 1, alphaValue: 0.5)
} else {
print("Selecting Layer failed with index:\(index) and subviewsCount \(subviews.count)")
}
}
func deselectSelectedSubview() {
selectedSubView?.setDeselected?()
selectedSubView = nil
setSubviewsAlpha(0, alphaValue: 1)
}
func swapLayerPositions(_ firstIndex: Int, secondIndex: Int) {
if firstIndex != secondIndex && firstIndex >= 0 && secondIndex >= 0 && firstIndex < subviews.count && secondIndex < subviews.count {
exchangeSubview(at: firstIndex, withSubviewAt: secondIndex)
} else {
print("Swap Layerpositions failed with firstIndex:\(firstIndex) and secondIndex\(secondIndex) and subviewsCount \(subviews.count)")
}
}
func changeLayerVisibility(_ docLayer: DocumentLayer) {
let isHidden = !docLayer.hidden
if let subview = self[docLayer.index] as? UIView {
subview.isHidden = isHidden
}
page?.changeLayerVisibility(isHidden, layer: docLayer)
}
func removeLayer(_ docLayer: DocumentLayer) {
if let subview = self[docLayer.index] as? UIView {
subview.removeFromSuperview()
}
docLayer.removeFromPage()
}
// MARK: - UIGestureRecognizer
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
(selectedSubView as? SketchView)?.touchesBegan(touches, with: event)
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
(selectedSubView as? SketchView)?.touchesMoved(touches, with: event)
}
override func touchesEnded(_ touches: Set<UITouch>,
with event: UIEvent?) {
(selectedSubView as? SketchView)?.touchesEnded(touches, with: event)
}
override func touchesCancelled(_ touches: Set<UITouch>,
with event: UIEvent?) {
(selectedSubView as? SketchView)?.touchesCancelled(touches, with: event)
}
func handlePan(_ panGestureRecognizer: UIPanGestureRecognizer) {
selectedSubView?.handlePan?(panGestureRecognizer)
}
func handleTap(_ tapGestureRecognizer: UITapGestureRecognizer) {
if selectedSubView != nil {
deselectSelectedSubview()
} else {
let location = tapGestureRecognizer.location(in: self)
for case let subview as MovableView in subviews.reversed() {
let pageSubview = subview as PageSubView
if !subview.isHidden && subview.frame.contains(location) {
selectedSubView = pageSubview
return
}
}
}
}
// MARK: - UIGestureRecognizerDelegate
func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool {
return !(selectedSubView is SketchView)
}
func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
// check if the user is currently selecting text
if otherGestureRecognizer.view is UITextView {
return false
}
return true
}
func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldBeRequiredToFailBy otherGestureRecognizer: UIGestureRecognizer) -> Bool {
return false
}
}
| mit | b3793c74fd5342b6c9d5d66613badd16 | 31.95941 | 157 | 0.628079 | 5.288336 | false | false | false | false |
ashikahmad/AKAttributeKit | Example/AKAttributeKit/ViewController.swift | 1 | 2340 | //
// ViewController.swift
// AKAttributeKit
//
// Created by Ashik uddin Ahmad on 09/24/2015.
// Copyright (c) 2015 Ashik uddin Ahmad. All rights reserved.
//
import UIKit
import AKAttributeKit
class ViewController: UIViewController, UITextViewDelegate {
@IBOutlet weak var textArea: UITextView!
@IBOutlet weak var previewText: UITextView!
@IBOutlet weak var hideKeyboard: UIButton!
var demoString:String!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let str = ["This is a <fg #f00>demo</fg> \nwhere ",
"<bg 0xaabbccdd><fg #ff0)> you </fg></bg> can see ",
"<u \(NSUnderlineStyle.styleDouble.rawValue|NSUnderlineStyle.patternDot.rawValue)>",
"how <font HelveticaNeue-ultralight|28>Easy</font> it is</u>.",
"\n<font Arial|12>Edit text above and see it attributed below ",
"</font><font Arial|22>immediately!</font>\n",
"By the way, it supports <a http://google.com>link</a> too"].reduce("", +)
demoString = str
self.resetToDemoText(self)
self.textArea.layer.cornerRadius = 5
self.textArea.layer.masksToBounds = true
self.hideKeyboard.isHidden = true
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func doHideKeyboard(_ sender: AnyObject) {
self.view.endEditing(false)
}
func textViewDidChange(_ textView: UITextView) {
self.previewText.attributedText = AKAttributeKit.parseString(textView.text)
self.previewText.textAlignment = NSTextAlignment.center
}
func textViewDidBeginEditing(_ textView: UITextView) {
// Show cancel button
self.hideKeyboard.isHidden = false
}
func textViewDidEndEditing(_ textView: UITextView) {
// Hide cancel button
self.hideKeyboard.isHidden = true
}
@IBAction func resetToDemoText(_ sender: AnyObject) {
self.textArea.text = demoString
self.previewText.attributedText = AKAttributeKit.parseString(demoString)
self.previewText.textAlignment = NSTextAlignment.center
}
}
| mit | 9fe0f963525468620c8612b9236f8015 | 32.913043 | 96 | 0.65 | 4.543689 | false | false | false | false |
sergeydi/nc.Notes | NCloud.notes/CoreDataManager.swift | 1 | 2958 | //
// CoreDataManager.swift
// NCloud.notes
//
// Created by Sergey Didanov on 31.01.17.
// Copyright © 2017 Sergey Didanov. All rights reserved.
//
import Foundation
import CoreData
class CoreDataManager {
// Singleton
static let instance = CoreDataManager()
lazy var applicationDocumentsDirectory: NSURL = {
let urls = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
return urls[urls.count-1] as NSURL
}()
lazy var managedObjectModel: NSManagedObjectModel = {
let modelURL = Bundle.main.url(forResource: "NCloud_notes", withExtension: "momd")!
return NSManagedObjectModel(contentsOf: modelURL)!
}()
lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = {
let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
let url = self.applicationDocumentsDirectory.appendingPathComponent("SingleViewCoreData.sqlite")
var failureReason = "There was an error creating or loading the application's saved data."
do {
try coordinator.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: url, options: nil)
} catch {
var dict = [String: AnyObject]()
dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" as AnyObject?
dict[NSLocalizedFailureReasonErrorKey] = failureReason as AnyObject?
dict[NSUnderlyingErrorKey] = error as NSError
let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
NSLog("Unresolved error \(wrappedError), \(wrappedError.userInfo)")
abort()
}
return coordinator
}()
lazy var managedObjectContext: NSManagedObjectContext = {
let coordinator = self.persistentStoreCoordinator
var managedObjectContext = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType)
managedObjectContext.persistentStoreCoordinator = coordinator
return managedObjectContext
}()
// Entity for Name
func entityForName(entityName: String) -> NSEntityDescription {
return NSEntityDescription.entity(forEntityName: entityName, in: self.managedObjectContext)!
}
func deleteObject(object: NSManagedObject) {
managedObjectContext.delete(object)
saveContext()
}
func deleteObjects(objects: [NSManagedObject]) {
for object in objects {
managedObjectContext.delete(object)
}
saveContext()
}
func saveContext() {
let context = managedObjectContext
if context.hasChanges {
do {
try context.save()
} catch {
let nserror = error as NSError
fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
}
}
}
}
| apache-2.0 | 67c59be0944803ce259b085bd5228f6c | 35.506173 | 120 | 0.661819 | 5.820866 | false | false | false | false |
Jackysonglanlan/Scripts | swift/xunyou_accelerator/Sources/srcLibs/SwifterSwift/stdlib/SignedNumericExtensions.swift | 2 | 1501 | //
// SignedNumberExtensions.swift
// SwifterSwift
//
// Created by Omar Albeik on 8/15/17.
// Copyright © 2017 SwifterSwift
//
#if canImport(Foundation)
import Foundation
#endif
// MARK: - Properties
public extension SignedNumeric {
/// SwifterSwift: String.
public var string: String {
return String(describing: self)
}
#if canImport(Foundation)
/// SwifterSwift: String with number and current locale currency.
public var asLocaleCurrency: String? {
let formatter = NumberFormatter()
formatter.numberStyle = .currency
formatter.locale = Locale.current
// swiftlint:disable next force_cast
return formatter.string(from: self as! NSNumber)
}
#endif
}
// MARK: - Methods
public extension SignedNumeric {
#if canImport(Foundation)
/// SwifterSwift: Spelled out representation of a number.
///
/// print((12.32).spelledOutString()) // prints "twelve point three two"
///
/// - Parameter locale: Locale, default is .current.
/// - Returns: String representation of number spelled in specified locale language. E.g. input 92, output in "en": "ninety-two"
public func spelledOutString(locale: Locale = .current) -> String? {
let formatter = NumberFormatter()
formatter.locale = locale
formatter.numberStyle = .spellOut
guard let number = self as? NSNumber else { return nil }
return formatter.string(from: number)
}
#endif
}
| unlicense | d43c4a8c93a7690064b65cf11ce17bba | 26.777778 | 132 | 0.66 | 4.411765 | false | false | false | false |
dev-alex-alex2006hw/videomere | fastlane/SnapshotHelper.swift | 2 | 1947 | //
// SnapshotHelper.swift
// Example
//
// Created by Felix Krause on 10/8/15.
// Copyright © 2015 Felix Krause. All rights reserved.
//
import Foundation
import XCTest
var deviceLanguage = ""
func setLanguage(app: XCUIApplication) {
Snapshot.setLanguage(app)
}
func snapshot(name: String, waitForLoadingIndicator: Bool = false) {
Snapshot.snapshot(name, waitForLoadingIndicator: waitForLoadingIndicator)
}
class Snapshot: NSObject {
class func setLanguage(app: XCUIApplication) {
let path = "/tmp/language.txt"
do {
let locale = try NSString(contentsOfFile: path, encoding: NSUTF8StringEncoding) as String
deviceLanguage = locale.substringToIndex(locale.startIndex.advancedBy(2, limit:locale.endIndex))
app.launchArguments += ["-AppleLanguages", "(\(deviceLanguage))", "-AppleLocale", "\"\(locale)\"", "-ui_testing"]
} catch {
print("Couldn't detect/set language...")
}
}
class func snapshot(name: String, waitForLoadingIndicator: Bool = false) {
if waitForLoadingIndicator {
waitForLoadingIndicatorToDisappear()
}
print("snapshot: \(name)") // more information about this, check out https://github.com/krausefx/snapshot
sleep(1) // Waiting for the animation to be finished (kind of)
XCUIDevice.sharedDevice().orientation = .Unknown
}
class func waitForLoadingIndicatorToDisappear() {
let query = XCUIApplication().statusBars.childrenMatchingType(.Other).elementBoundByIndex(1).childrenMatchingType(.Other)
while query.count > 4 {
sleep(1)
print("Number of Elements in Status Bar: \(query.count)... waiting for status bar to disappear")
}
}
}
// Please don't remove the lines below
// They are used to detect outdated configuration files
// SnapshotHelperVersion [[1.0]]
| mit | d563959f42ee7b5e3e620267f90994d3 | 31.983051 | 129 | 0.656732 | 4.939086 | false | false | false | false |
0xced/Carthage | Source/CarthageKit/Git.swift | 1 | 18690 | //
// Git.swift
// Carthage
//
// Created by Alan Rogers on 14/10/2014.
// Copyright (c) 2014 Carthage. All rights reserved.
//
import Foundation
import LlamaKit
import ReactiveCocoa
import ReactiveTask
/// Represents a URL for a Git remote.
public struct GitURL: Equatable {
/// The string representation of the URL.
public let URLString: String
/// A normalized URL string, without protocol, authentication, or port
/// information. This is mostly useful for comparison, and not for any
/// actual Git operations.
private var normalizedURLString: String {
let parsedURL: NSURL? = NSURL(string: URLString)
if let parsedURL = parsedURL {
// Normal, valid URL.
let host = parsedURL.host ?? ""
let path = stripGitSuffix(parsedURL.path ?? "")
return "\(host)\(path)"
} else if URLString.hasPrefix("/") {
// Local path.
return stripGitSuffix(URLString)
} else {
// scp syntax.
var strippedURLString = URLString
if let index = find(strippedURLString, "@") {
strippedURLString.removeRange(Range(start: strippedURLString.startIndex, end: index))
}
var host = ""
if let index = find(strippedURLString, ":") {
host = strippedURLString[Range(start: strippedURLString.startIndex, end: index.predecessor())]
strippedURLString.removeRange(Range(start: strippedURLString.startIndex, end: index))
}
var path = strippedURLString
if !path.hasPrefix("/") {
// This probably isn't strictly legit, but we'll have a forward
// slash for other URL types.
path.insert("/", atIndex: path.startIndex)
}
return "\(host)\(path)"
}
}
/// The name of the repository, if it can be inferred from the URL.
public var name: String? {
let components = split(URLString, { $0 == "/" }, allowEmptySlices: false)
return components.last.map { self.stripGitSuffix($0) }
}
public init(_ URLString: String) {
self.URLString = URLString
}
/// Strips any trailing .git in the given name, if one exists.
private func stripGitSuffix(string: String) -> String {
if string.hasSuffix(".git") {
let nsString = string as NSString
return nsString.substringToIndex(nsString.length - 4) as String
} else {
return string
}
}
}
public func ==(lhs: GitURL, rhs: GitURL) -> Bool {
return lhs.normalizedURLString == rhs.normalizedURLString
}
extension GitURL: Hashable {
public var hashValue: Int {
return normalizedURLString.hashValue
}
}
extension GitURL: Printable {
public var description: String {
return URLString
}
}
/// A Git submodule.
public struct Submodule: Equatable {
/// The name of the submodule. Usually (but not always) the same as the
/// path.
public let name: String
/// The relative path at which the submodule is checked out.
public let path: String
/// The URL from which the submodule should be cloned, if present.
public var URL: GitURL
/// The SHA checked out in the submodule.
public var SHA: String
public init(name: String, path: String, URL: GitURL, SHA: String) {
self.name = name
self.path = path
self.URL = URL
self.SHA = SHA
}
}
public func ==(lhs: Submodule, rhs: Submodule) -> Bool {
return lhs.name == rhs.name && lhs.path == rhs.path && lhs.URL == rhs.URL && lhs.SHA == rhs.SHA
}
extension Submodule: Hashable {
public var hashValue: Int {
return name.hashValue
}
}
extension Submodule: Printable {
public var description: String {
return "\(name) @ \(SHA)"
}
}
/// Shells out to `git` with the given arguments, optionally in the directory
/// of an existing repository.
public func launchGitTask(arguments: [String], repositoryFileURL: NSURL? = nil, standardOutput: SinkOf<NSData>? = nil, standardError: SinkOf<NSData>? = nil, environment: [String: String]? = nil) -> ColdSignal<String> {
let taskDescription = TaskDescription(launchPath: "/usr/bin/env", arguments: [ "git" ] + arguments, workingDirectoryPath: repositoryFileURL?.path, environment: environment)
return launchTask(taskDescription, standardOutput: standardOutput, standardError: standardError)
.map { NSString(data: $0, encoding: NSUTF8StringEncoding) as String }
}
/// Returns a signal that completes when cloning completes successfully.
public func cloneRepository(cloneURL: GitURL, destinationURL: NSURL, bare: Bool = true) -> ColdSignal<String> {
precondition(destinationURL.fileURL)
var arguments = [ "clone" ]
if bare {
arguments.append("--bare")
}
return launchGitTask(arguments + [ "--quiet", cloneURL.URLString, destinationURL.path! ])
}
/// Returns a signal that completes when the fetch completes successfully.
public func fetchRepository(repositoryFileURL: NSURL, remoteURL: GitURL? = nil, refspec: String? = nil) -> ColdSignal<String> {
precondition(repositoryFileURL.fileURL)
var arguments = [ "fetch", "--tags", "--prune", "--quiet" ]
if let remoteURL = remoteURL {
arguments.append(remoteURL.URLString)
}
if let refspec = refspec {
arguments.append(refspec)
}
return launchGitTask(arguments, repositoryFileURL: repositoryFileURL)
}
/// Sends each tag found in the given Git repository.
public func listTags(repositoryFileURL: NSURL) -> ColdSignal<String> {
return launchGitTask([ "tag" ], repositoryFileURL: repositoryFileURL)
.map { (allTags: String) -> ColdSignal<String> in
return ColdSignal { (sink, disposable) in
let string = allTags as NSString
string.enumerateSubstringsInRange(NSMakeRange(0, string.length), options: NSStringEnumerationOptions.ByLines | NSStringEnumerationOptions.Reverse) { (line, substringRange, enclosingRange, stop) in
if disposable.disposed {
stop.memory = true
}
sink.put(.Next(Box(line as String)))
}
sink.put(.Completed)
}
}
.merge(identity)
}
/// Returns the text contents of the path at the given revision, or an error if
/// the path could not be loaded.
public func contentsOfFileInRepository(repositoryFileURL: NSURL, path: String, revision: String = "HEAD") -> ColdSignal<String> {
let showObject = "\(revision):\(path)"
return launchGitTask([ "show", showObject ], repositoryFileURL: repositoryFileURL, standardError: SinkOf<NSData> { _ in () })
}
/// Checks out the working tree of the given (ideally bare) repository, at the
/// specified revision, to the given folder. If the folder does not exist, it
/// will be created.
public func checkoutRepositoryToDirectory(repositoryFileURL: NSURL, workingDirectoryURL: NSURL, revision: String = "HEAD", shouldCloneSubmodule: Submodule -> Bool = { _ in true }) -> ColdSignal<()> {
return ColdSignal.lazy {
var error: NSError?
if !NSFileManager.defaultManager().createDirectoryAtURL(workingDirectoryURL, withIntermediateDirectories: true, attributes: nil, error: &error) {
return .error(error ?? CarthageError.RepositoryCheckoutFailed(workingDirectoryURL: workingDirectoryURL, reason: "Could not create working directory").error)
}
var environment = NSProcessInfo.processInfo().environment as [String: String]
environment["GIT_WORK_TREE"] = workingDirectoryURL.path!
return launchGitTask([ "checkout", "--quiet", "--force", revision ], repositoryFileURL: repositoryFileURL, environment: environment)
.then(cloneSubmodulesForRepository(repositoryFileURL, workingDirectoryURL, revision: revision, shouldCloneSubmodule: shouldCloneSubmodule))
}
}
/// Clones matching submodules for the given repository at the specified
/// revision, into the given working directory.
public func cloneSubmodulesForRepository(repositoryFileURL: NSURL, workingDirectoryURL: NSURL, revision: String = "HEAD", shouldCloneSubmodule: Submodule -> Bool = { _ in true }) -> ColdSignal<()> {
return submodulesInRepository(repositoryFileURL, revision: revision)
.map { submodule -> ColdSignal<()> in
if shouldCloneSubmodule(submodule) {
return cloneSubmoduleInWorkingDirectory(submodule, workingDirectoryURL)
} else {
return .empty()
}
}
.concat(identity)
.then(.empty())
}
/// Clones the given submodule into the working directory of its parent
/// repository, but without any Git metadata.
public func cloneSubmoduleInWorkingDirectory(submodule: Submodule, workingDirectoryURL: NSURL) -> ColdSignal<()> {
let submoduleDirectoryURL = workingDirectoryURL.URLByAppendingPathComponent(submodule.path, isDirectory: true)
let purgeGitDirectories = ColdSignal<()> { (sink, disposable) in
let enumerator = NSFileManager.defaultManager().enumeratorAtURL(submoduleDirectoryURL, includingPropertiesForKeys: [ NSURLIsDirectoryKey!, NSURLNameKey! ], options: nil, errorHandler: nil)!
while !disposable.disposed {
let URL: NSURL! = enumerator.nextObject() as? NSURL
if URL == nil {
break
}
var name: AnyObject?
var error: NSError?
if !URL.getResourceValue(&name, forKey: NSURLNameKey, error: &error) {
sink.put(.Error(error ?? CarthageError.RepositoryCheckoutFailed(workingDirectoryURL: submoduleDirectoryURL, reason: "could not enumerate name of descendant at \(URL.path!)").error))
return
}
if let name = name as? NSString {
if name != ".git" {
continue
}
} else {
continue
}
var isDirectory: AnyObject?
if !URL.getResourceValue(&isDirectory, forKey: NSURLIsDirectoryKey, error: &error) || isDirectory == nil {
sink.put(.Error(error ?? CarthageError.RepositoryCheckoutFailed(workingDirectoryURL: submoduleDirectoryURL, reason: "could not determine whether \(URL.path!) is a directory").error))
return
}
if let directory = isDirectory?.boolValue {
if directory {
enumerator.skipDescendants()
}
}
if !NSFileManager.defaultManager().removeItemAtURL(URL, error: &error) {
sink.put(.Error(error ?? CarthageError.RepositoryCheckoutFailed(workingDirectoryURL: submoduleDirectoryURL, reason: "could not remove \(URL.path!)").error))
return
}
}
sink.put(.Completed)
}
return ColdSignal<String>.lazy {
var error: NSError?
if !NSFileManager.defaultManager().removeItemAtURL(submoduleDirectoryURL, error: &error) {
return .error(error ?? CarthageError.RepositoryCheckoutFailed(workingDirectoryURL: submoduleDirectoryURL, reason: "could not remove submodule checkout").error)
}
return cloneRepository(submodule.URL, workingDirectoryURL.URLByAppendingPathComponent(submodule.path), bare: false)
}
.then(checkoutSubmodule(submodule, submoduleDirectoryURL))
.then(purgeGitDirectories)
}
/// Recursively checks out the given submodule's revision, in its working
/// directory.
private func checkoutSubmodule(submodule: Submodule, submoduleWorkingDirectoryURL: NSURL) -> ColdSignal<()> {
return launchGitTask([ "checkout", "--quiet", submodule.SHA ], repositoryFileURL: submoduleWorkingDirectoryURL)
.then(launchGitTask([ "submodule", "--quiet", "update", "--init", "--recursive" ], repositoryFileURL: submoduleWorkingDirectoryURL))
.then(.empty())
}
/// Parses each key/value entry from the given config file contents, optionally
/// stripping a known prefix/suffix off of each key.
private func parseConfigEntries(contents: String, keyPrefix: String = "", keySuffix: String = "") -> ColdSignal<(String, String)> {
let entries = split(contents, { $0 == "\0" }, allowEmptySlices: false)
return ColdSignal { (sink, disposable) in
for entry in entries {
if disposable.disposed {
break
}
let components = split(entry, { $0 == "\n" }, maxSplit: 1, allowEmptySlices: true)
if components.count != 2 {
continue
}
let value = components[1]
let scanner = NSScanner(string: components[0])
if !scanner.scanString(keyPrefix, intoString: nil) {
continue
}
var key: NSString?
if !scanner.scanUpToString(keySuffix, intoString: &key) {
continue
}
if let key = key as? String {
sink.put(.Next(Box((key, value))))
}
}
sink.put(.Completed)
}
}
/// Determines the SHA that the submodule at the given path is pinned to, in the
/// revision of the parent repository specified.
public func submoduleSHAForPath(repositoryFileURL: NSURL, path: String, revision: String = "HEAD") -> ColdSignal<String> {
return launchGitTask([ "ls-tree", "-z", revision, path ], repositoryFileURL: repositoryFileURL)
.tryMap { string -> Result<String> in
// Example:
// 160000 commit 083fd81ecf00124cbdaa8f86ef10377737f6325a External/ObjectiveGit
let components = split(string, { $0 == " " || $0 == "\t" }, maxSplit: 3, allowEmptySlices: false)
if components.count >= 3 {
return success(components[2])
} else {
return failure(CarthageError.ParseError(description: "expected submodule commit SHA in ls-tree output: \(string)").error)
}
}
}
/// Returns each submodule found in the given repository revision, or an empty
/// signal if none exist.
public func submodulesInRepository(repositoryFileURL: NSURL, revision: String = "HEAD") -> ColdSignal<Submodule> {
let modulesObject = "\(revision):.gitmodules"
let baseArguments = [ "config", "--blob", modulesObject, "-z" ]
return launchGitTask(baseArguments + [ "--get-regexp", "submodule\\..*\\.path" ], repositoryFileURL: repositoryFileURL, standardError: SinkOf<NSData> { _ in () })
.catch { _ in .empty() }
.map { parseConfigEntries($0, keyPrefix: "submodule.", keySuffix: ".path") }
.merge(identity)
.map { (name, path) -> ColdSignal<Submodule> in
return launchGitTask(baseArguments + [ "--get", "submodule.\(name).url" ], repositoryFileURL: repositoryFileURL)
.map { GitURL($0) }
.zipWith(submoduleSHAForPath(repositoryFileURL, path, revision: revision))
.map { (URL, SHA) in
return Submodule(name: name, path: path, URL: URL, SHA: SHA)
}
}
.merge(identity)
}
/// Determines whether the specified revision identifies a valid commit.
///
/// If the specified file URL does not represent a valid Git repository, `false`
/// will be sent.
public func commitExistsInRepository(repositoryFileURL: NSURL, revision: String = "HEAD") -> ColdSignal<Bool> {
return ColdSignal.lazy {
// NSTask throws a hissy fit (a.k.a. exception) if the working directory
// doesn't exist, so pre-emptively check for that.
var isDirectory: ObjCBool = false
if !NSFileManager.defaultManager().fileExistsAtPath(repositoryFileURL.path!, isDirectory: &isDirectory) || !isDirectory {
return .single(false)
}
return launchGitTask([ "rev-parse", "\(revision)^{commit}" ], repositoryFileURL: repositoryFileURL, standardOutput: SinkOf<NSData> { _ in () }, standardError: SinkOf<NSData> { _ in () })
.then(.single(true))
.catch { _ in .single(false) }
}
}
/// Attempts to resolve the given reference into an object SHA.
public func resolveReferenceInRepository(repositoryFileURL: NSURL, reference: String) -> ColdSignal<String> {
return launchGitTask([ "rev-parse", "\(reference)^{object}" ], repositoryFileURL: repositoryFileURL, standardError: SinkOf<NSData> { _ in () })
.map { string in
return string.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())
}
.catch { _ in .error(CarthageError.RepositoryCheckoutFailed(workingDirectoryURL: repositoryFileURL, reason: "No object named \"\(reference)\" exists").error) }
}
/// Returns the location of the .git folder within the given repository.
private func gitDirectoryURLInRepository(repositoryFileURL: NSURL) -> NSURL {
return repositoryFileURL.URLByAppendingPathComponent(".git")
}
/// Attempts to determine whether the given directory represents a Git
/// repository.
private func isGitRepository(directoryURL: NSURL) -> Bool {
return NSFileManager.defaultManager().fileExistsAtPath(gitDirectoryURLInRepository(directoryURL).path!)
}
/// Adds the given submodule to the given repository, cloning from `fetchURL` if
/// the desired revision does not exist or the submodule needs to be cloned.
public func addSubmoduleToRepository(repositoryFileURL: NSURL, submodule: Submodule, fetchURL: GitURL) -> ColdSignal<()> {
let submoduleDirectoryURL = repositoryFileURL.URLByAppendingPathComponent(submodule.path, isDirectory: true)
return ColdSignal.lazy {
if isGitRepository(submoduleDirectoryURL) {
// If the submodule repository already exists, just check out and
// stage the correct revision.
return fetchRepository(submoduleDirectoryURL, remoteURL: fetchURL)
.then(launchGitTask([ "config", "--file", ".gitmodules", "submodule.\(submodule.name).url", submodule.URL.URLString ], repositoryFileURL: repositoryFileURL))
.then(launchGitTask([ "submodule", "--quiet", "sync" ], repositoryFileURL: repositoryFileURL))
.then(checkoutSubmodule(submodule, submoduleDirectoryURL))
.then(launchGitTask([ "add", "--force", submodule.path ], repositoryFileURL: repositoryFileURL))
.then(.empty())
} else {
let addSubmodule = launchGitTask([ "submodule", "--quiet", "add", "--force", "--name", submodule.name, "--", submodule.URL.URLString, submodule.path ], repositoryFileURL: repositoryFileURL)
// A failure to add usually means the folder was already added
// to the index. That's okay.
.catch { _ in .empty() }
// If it doesn't exist, clone and initialize a submodule from our
// local bare repository.
return cloneRepository(fetchURL, submoduleDirectoryURL, bare: false)
.then(launchGitTask([ "remote", "set-url", "origin", submodule.URL.URLString ], repositoryFileURL: submoduleDirectoryURL))
.then(checkoutSubmodule(submodule, submoduleDirectoryURL))
.then(addSubmodule)
.then(launchGitTask([ "submodule", "--quiet", "init", "--", submodule.path ], repositoryFileURL: repositoryFileURL))
.then(.empty())
}
}
}
/// Moves an item within a Git repository, or within a simple directory if a Git
/// repository is not found.
///
/// Sends the new URL of the item after moving.
public func moveItemInPossibleRepository(repositoryFileURL: NSURL, #fromPath: String, #toPath: String) -> ColdSignal<NSURL> {
let toURL = repositoryFileURL.URLByAppendingPathComponent(toPath)
let parentDirectoryURL = toURL.URLByDeletingLastPathComponent!
return ColdSignal.lazy {
var error: NSError?
if !NSFileManager.defaultManager().createDirectoryAtURL(parentDirectoryURL, withIntermediateDirectories: true, attributes: nil, error: &error) {
return .error(error ?? CarthageError.WriteFailed(parentDirectoryURL).error)
}
if isGitRepository(repositoryFileURL) {
return launchGitTask([ "mv", "-k", fromPath, toPath ], repositoryFileURL: repositoryFileURL)
.then(.single(toURL))
} else {
let fromURL = repositoryFileURL.URLByAppendingPathComponent(fromPath)
var error: NSError?
if NSFileManager.defaultManager().moveItemAtURL(fromURL, toURL: toURL, error: &error) {
return .single(toURL)
} else {
return .error(error ?? CarthageError.WriteFailed(toURL).error)
}
}
}
}
| mit | 0cf5fa62e5c9bc221c80e162f0e8c4c6 | 38.264706 | 218 | 0.726271 | 4.156104 | false | false | false | false |
hirohisa/RxSwift | Playgrounds/ObservablesOperators/Observables+Combining.playground/Contents.swift | 3 | 7164 | import Cocoa
import RxSwift
/*:
# To use playgrounds please open `Rx.xcworkspace`, build `RxSwift-OSX` scheme and then open playgrounds in `Rx.xcworkspace` tree view.
*/
/*:
## Combination operators
Operators that work with multiple source Observables to create a single Observable.
### `startWith`
Return an observeble which emits a specified item before emitting the items from the source Observable.
[More info in reactive.io website]( http://reactivex.io/documentation/operators/startwith.html )
*/
example("startWith") {
let aggregateSubscriber = from([4, 5, 6, 7, 8, 9])
>- startWith(3)
>- startWith(2)
>- startWith(1)
>- startWith(0)
>- subscribeNext { int in
println(int)
}
}
/*:
### `combineLatest`
Takes several source Obserbables and a closure as parameters, returns an Observable which emits the latest items of each source Obsevable, procesed through the closure.
Once each source Observables have each emitted an item, `combineLatest` emits an item every time either source Observable emits an item.
[More info in reactive.io website]( http://reactivex.io/documentation/operators/combinelatest.html )
The next example shows how
*/
example("combineLatest 1st") {
let intOb1 = PublishSubject<String>()
let intOb2 = PublishSubject<Int>()
combineLatest(intOb1, intOb2) {
"\($0) \($1)"
}
>- subscribeNext {
println($0)
}
println("send A to first channel")
sendNext(intOb1, "A")
println("note that nothing outputs")
println("\nsend 1 to second channel")
sendNext(intOb2, 1)
println("now that there is something in both channels, there is output")
println("\nsend B to first channel")
sendNext(intOb1, "B")
println("now that both channels are full, whenever either channel emits a value, the combined channel also emits a value")
println("\nsend 2 to second channel")
sendNext(intOb2, 2)
println("note that the combined channel emits a value whenever either sub-channel emits a value, even if the value is the same")
}
//: This example show once in each channel there are output for each new channel output the resulting observable also produces an output
example("combineLatest 2nd") {
let intOb1 = just(2)
let intOb2 = from([0, 1, 2, 3, 4])
combineLatest(intOb1, intOb2) {
$0 * $1
}
>- subscribeNext {
println($0)
}
}
/*:
There are a serie of functions `combineLatest`, they take from two to ten sources Obserbables and the closure
The next sample shows combineLatest called with three sorce Observables
*/
example("combineLatest 3rd") {
let intOb1 = just(2)
let intOb2 = from([0, 1, 2, 3])
let intOb3 = from([0, 1, 2, 3, 4])
combineLatest(intOb1, intOb2, intOb3) {
($0 + $1) * $2
}
>- subscribeNext {
println($0)
}
}
/*:
### `zip`
Takes several source Observables and a closure as parameters, returns an Observable which emit the items of the second Obsevable procesed, through the closure, with the last item of first Observable
The Observable returned by `zip` emits an item only when all of the imputs Observables have emited an item
[More info in reactive.io website](http://reactivex.io/documentation/operators/zip.html)
*/
example("zip 1st") {
let intOb1 = PublishSubject<String>()
let intOb2 = PublishSubject<Int>()
zip(intOb1, intOb2) {
"\($0) \($1)"
}
>- subscribeNext {
println($0)
}
println("send A to first channel")
sendNext(intOb1, "A")
println("note that nothing outputs")
println("\nsend 1 to second channel")
sendNext(intOb2, 1)
println("now that both source channels have output, there is output")
println("\nsend B to first channel")
sendNext(intOb1, "B")
println("note that nothing outputs, since channel 1 has two outputs but channel 2 only has one")
println("\nsend C to first channel")
sendNext(intOb1, "C")
println("note that nothing outputs, it is the same as in the previous step, since channel 1 has three outputs but channel 2 only has one")
println("\nsend 2 to second channel")
sendNext(intOb2, 2)
println("note that the combined channel emits a value with the second output of each channel")
}
//: This example show once in each channel there are output for each new channel output the resulting observable also produces an output
example("zip 2nd") {
let intOb1 = just(2)
let intOb2 = from([0, 1, 2, 3, 4])
zip(intOb1, intOb2) {
$0 * $1
}
>- subscribeNext {
println($0)
}
}
/*:
There are a serie of functions `zip`, they take from two to ten sources Obserbables and the closure
The next sample shows zip called with three sorce Observables
*/
example("zip 3rd") {
let intOb1 = from([0, 1])
let intOb2 = from([0, 1, 2, 3])
let intOb3 = from([0, 1, 2, 3, 4])
zip(intOb1, intOb2, intOb3) {
($0 + $1) * $2
}
>- subscribeNext {
println($0)
}
}
/*:
### `merge`
Combine multiple Observables, of the same type, into one by merging their emissions
[More info in reactive.io website]( http://reactivex.io/documentation/operators/merge.html )
*/
example("merge 1st") {
let subject1 = PublishSubject<Int>()
let subject2 = PublishSubject<Int>()
merge(returnElements(subject1, subject2))
>- subscribeNext { int in
println(int)
}
sendNext(subject1, 20)
sendNext(subject1, 40)
sendNext(subject1, 60)
sendNext(subject2, 1)
sendNext(subject1, 80)
sendNext(subject1, 100)
sendNext(subject2, 1)
}
example("merge 2nd") {
let subject1 = PublishSubject<Int>()
let subject2 = PublishSubject<Int>()
returnElements(subject1, subject2)
>- merge(maxConcurrent: 2)
>- subscribeNext { int in
println(int)
}
sendNext(subject1, 20)
sendNext(subject1, 40)
sendNext(subject1, 60)
sendNext(subject2, 1)
sendNext(subject1, 80)
sendNext(subject1, 100)
sendNext(subject2, 1)
}
/*:
### `switchLatest`
Convert an Observable that emits Observables into a single Observable that emits the items emitted by the most-recently-emitted of those Observables.
[More info in reactive.io website]( http://reactivex.io/documentation/operators/switch.html )
*/
example("switchLatest") {
let var1 = Variable(0)
let var2 = Variable(200)
// var3 is like an Observable<Observable<Int>>
let var3 = Variable(var1 as Observable<Int>)
let d = var3
>- switchLatest
>- subscribeNext { (e: Int) -> Void in
println("\(e)")
}
var1.next(1)
var1.next(2)
var1.next(3)
var1.next(4)
var3.next(var2)
var2.next(201)
println("Note which no listen to var1")
var1.next(5)
var1.next(6)
var1.next(7)
sendCompleted(var1)
var2.next(202)
var2.next(203)
var2.next(204)
}
| mit | 0532f0292029f4d67b225152ad8298c2 | 25.731343 | 199 | 0.642099 | 3.938428 | false | true | false | false |
dreamsxin/swift | validation-test/compiler_crashers_fixed/01237-swift-nominaltypedecl-getdeclaredtypeincontext.swift | 11 | 760 | // This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// RUN: not %target-swift-frontend %s -parse
struct c<h : b> : b {
typealias e = a<c<h>0) {
}
let c = a
protocol a : a {
}
class a {
}
struct A<T> {
}
protocol a : a {
}
protocol a {
}
class b<h : c, i : c where h.g == i> : a {
}
class b<h, i> {
}
protocol c {
}
f: A where D.C == E> {s func c() { }
}
func c<d {
enum c {
}
}
func a<T>() -> (T, T -> T) -> T {
}
protocol a {
}
class b: a {
}
class a<f : b, g : b
| apache-2.0 | 614466411260dee5cb605f07ea975d8a | 17.536585 | 78 | 0.613158 | 2.676056 | false | false | false | false |
argon/mas | MasKitTests/Controllers/MasStoreSearchSpec.swift | 1 | 2589 | //
// MasStoreSearchSpec.swift
// MasKitTests
//
// Created by Ben Chatelain on 1/4/19.
// Copyright © 2019 mas-cli. All rights reserved.
//
@testable import MasKit
import Nimble
import Quick
class MasStoreSearchSpec: QuickSpec {
override func spec() {
describe("store") {
context("when searched") {
it("can find slack") {
let networkSession = NetworkSessionMockFromFile(responseFile: "search/slack.json")
let storeSearch = MasStoreSearch(networkManager: NetworkManager(session: networkSession))
var searchList: SearchResultList
do {
searchList = try storeSearch.search(for: "slack")
expect(searchList.resultCount) == 39
expect(searchList.results.count) == 39
} catch {
let maserror = error as! MASError
if case let .jsonParsing(nserror) = maserror {
fail("\(maserror) \(nserror!)")
}
}
}
}
context("when lookup used") {
it("can find slack") {
let appId = 803_453_959
let networkSession = NetworkSessionMockFromFile(responseFile: "lookup/slack.json")
let storeSearch = MasStoreSearch(networkManager: NetworkManager(session: networkSession))
var lookup: SearchResult?
do {
lookup = try storeSearch.lookup(app: appId)
} catch {
let maserror = error as! MASError
if case let .jsonParsing(nserror) = maserror {
fail("\(maserror) \(nserror!)")
}
}
guard let result = lookup else { fatalError("lookup result was nil") }
expect(result.trackId) == appId
expect(result.bundleId) == "com.tinyspeck.slackmacgap"
expect(result.price) == 0
expect(result.sellerName) == "Slack Technologies, Inc."
expect(result.sellerUrl) == "https://slack.com"
expect(result.trackName) == "Slack"
expect(result.trackViewUrl) == "https://itunes.apple.com/us/app/slack/id803453959?mt=12&uo=4"
expect(result.version) == "3.3.3"
}
}
}
}
}
| mit | 09e00bf883559d7e0227e6913ea71aa7 | 38.815385 | 113 | 0.489567 | 5.044834 | false | false | false | false |
ben-ng/swift | benchmark/single-source/ArrayOfPOD.swift | 1 | 1420 | //===--- ArrayOfPOD.swift -------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
// This benchmark tests creation and destruction of an array of
// trivial static type. It is meant to be a baseline for comparison against
// ArrayOfGenericPOD.
//
// For comparison, we always create three arrays of 200,000 words.
class RefArray<T> {
var array : [T]
init(_ i:T, count:Int = 100_000) {
array = [T](repeating: i, count: count)
}
}
@inline(never)
func genIntArray() {
_ = RefArray<Int>(3, count:200_000)
// should be a nop
}
enum PODEnum {
case Some(Int)
init(i:Int) { self = .Some(i) }
}
@inline(never)
func genEnumArray() {
_ = RefArray<PODEnum>(PODEnum.Some(3))
// should be a nop
}
struct S {
var x: Int
var y: Int
}
@inline(never)
func genStructArray() {
_ = RefArray<S>(S(x:3, y:4))
// should be a nop
}
@inline(never)
public func run_ArrayOfPOD(_ N: Int) {
for _ in 0...N {
genIntArray()
genEnumArray()
genStructArray()
}
}
| apache-2.0 | a315e3344d0be8c20fbc92f190729506 | 21.903226 | 80 | 0.6 | 3.514851 | false | false | false | false |
nathantannar4/NTComponents | NTComponents Demo/StandardViewControllers.swift | 1 | 3021 | //
// StandardViewControllers.swift
// NTComponents
//
// Copyright © 2017 Nathan Tannar.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
// Created by Nathan Tannar on 6/25/17.
//
import NTComponents
class StandardViewControllers: NTTableViewController {
var rootControllers: [UIViewController] = {
var vcs = [UIViewController]()
for index in 0...4 {
let vc = NTViewController()
vc.title = "Item \(index + 1)"
vc.tabBarItem.image = Icon.NTLogo
vc.view.backgroundColor = Color.Default.Background.ViewController.darker(by: CGFloat(index * 2))
vcs.append(vc)
}
return vcs
}()
var controllers: [UIViewController] = []
override func viewDidLoad() {
super.viewDidLoad()
controllers = [
NTTabBarController(viewControllers: rootControllers),
NTScrollableTabBarController(viewControllers: rootControllers),
FeedViewController()
]
}
override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return "Container Controllers"
}
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return controllers.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = NTTableViewCell()
cell.textLabel?.text = String(describing: type(of: controllers[indexPath.row]))
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let navVC = NTNavigationController(rootViewController: controllers[indexPath.row].addDismissalBarButtonItem())
present(navVC, animated: true, completion: nil)
}
}
| mit | 0a129f702d419cdaa1fa72746c700db3 | 37.227848 | 118 | 0.68543 | 4.902597 | false | false | false | false |
KrishMunot/swift | stdlib/public/SDK/CoreMedia/CMTimeRange.swift | 3 | 2749 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
@_exported import CoreMedia // Clang module
// CMTIMERANGE_IS_VALID
// CMTIMERANGE_IS_INVALID
// CMTIMERANGE_IS_INDEFINITE
// CMTIMERANGE_IS_EMPTY
// CMTimeRangeGetEnd
// CMTimeRangeGetUnion
// CMTimeRangeGetIntersection
// CMTimeRangeContainsTime
// CMTimeRangeContainsTimeRange
// CMTimeRangeFromTimeToTime
extension CMTimeRange {
public init(start: CMTime, end: CMTime) {
self = CMTimeRangeFromTimeToTime(start, end)
}
public var isValid: Bool {
return self.start.isValid &&
self.duration.isValid && (self.duration.epoch == 0)
}
public var isIndefinite: Bool {
return self.isValid &&
(self.start.isIndefinite || self.duration.isIndefinite)
}
public var isEmpty: Bool {
return self.isValid && (self.duration == kCMTimeZero)
}
public var end: CMTime {
return CMTimeRangeGetEnd(self)
}
@warn_unused_result
public func union(_ otherRange: CMTimeRange) -> CMTimeRange {
return CMTimeRangeGetUnion(self, otherRange)
}
@warn_unused_result
public func intersection(_ otherRange: CMTimeRange) -> CMTimeRange {
return CMTimeRangeGetIntersection(self, otherRange)
}
@warn_unused_result
public func containsTime(_ time: CMTime) -> Bool {
return CMTimeRangeContainsTime(self, time).boolValue
}
@warn_unused_result
public func containsTimeRange(_ range: CMTimeRange) -> Bool {
return CMTimeRangeContainsTimeRange(self, range).boolValue
}
}
@warn_unused_result
public func CMTIMERANGE_IS_VALID (_ range: CMTimeRange) -> Bool {
return range.isValid
}
@warn_unused_result
public func CMTIMERANGE_IS_INVALID (_ range: CMTimeRange) -> Bool {
return !range.isValid
}
@warn_unused_result
public func CMTIMERANGE_IS_INDEFINITE (_ range: CMTimeRange) -> Bool {
return range.isIndefinite
}
@warn_unused_result
public func CMTIMERANGE_IS_EMPTY (_ range: CMTimeRange) -> Bool {
return range.isEmpty
}
extension CMTimeRange : Equatable {}
// CMTimeRangeEqual
@warn_unused_result
public func == (range1: CMTimeRange, range2: CMTimeRange) -> Bool {
return CMTimeRangeEqual(range1, range2).boolValue
}
@warn_unused_result
public func != (range1: CMTimeRange, range2: CMTimeRange) -> Bool {
return !CMTimeRangeEqual(range1, range2).boolValue
}
| apache-2.0 | 3639b8f63ca32b0dec1097e0e4cc17c1 | 27.936842 | 80 | 0.692252 | 4.09687 | false | false | false | false |
akuraru/PureViewIcon | PureViewIcon/Views/PVICrop.swift | 1 | 2015 | //
// PVICrop.swift
//
// Created by akuraru on 2017/02/11.
//
import UIKit
import SnapKit
extension PVIView {
func makeCropConstraints() {
base.snp.updateConstraints { (make) in
make.width.equalToSuperview()
make.height.equalToSuperview()
make.center.equalToSuperview()
}
base.transform = resetTransform()
before.setup(width: 2)
main.setup(width: 2)
after.setup(width: 1)
// before
before.top.alpha = 1
before.left.alpha = 0
before.right.alpha = 1
before.bottom.alpha = 0
before.view.snp.makeConstraints { (make) in
make.centerX.equalToSuperview().multipliedBy(14 / 17.0)
make.centerY.equalToSuperview().multipliedBy(20 / 17.0)
make.width.equalToSuperview().multipliedBy(21 / 34.0)
make.height.equalToSuperview().multipliedBy(21 / 34.0)
}
before.view.transform = resetTransform()
// main
main.top.alpha = 0
main.left.alpha = 1
main.right.alpha = 0
main.bottom.alpha = 1
main.view.snp.makeConstraints { (make) in
make.centerX.equalToSuperview().multipliedBy(20 / 17.0)
make.centerY.equalToSuperview().multipliedBy(14 / 17.0)
make.width.equalToSuperview().multipliedBy(21 / 34.0)
make.height.equalToSuperview().multipliedBy(21 / 34.0)
}
main.view.transform = resetTransform()
// after
after.top.alpha = 1
after.left.alpha = 0
after.right.alpha = 0
after.bottom.alpha = 0
after.view.snp.makeConstraints { (make) in
make.center.equalToSuperview()
make.width.equalToSuperview().multipliedBy(27 / 34.0)
make.height.equalToSuperview().multipliedBy(1 / 34.0)
}
after.view.transform = CGAffineTransform(rotationAngle: CGFloat(-M_PI_4))
}
}
| mit | 9a3443daa440976c3d9979b5bdf5c6c8 | 30.484375 | 81 | 0.576675 | 4.342672 | false | false | false | false |
zcfsmile/Swifter | BasicSyntax/010控制流/010控制流.playground/Contents.swift | 1 | 4619 | //: Playground - noun: a place where people can play
import UIKit
//: 控制流
//: for-in
for index in 1...5 {
print("\(index) times 5 is \(index * 5)")
}
//: While
//: while
//: Repeat- while
//: if
//: if else
//: Switch
//: 在 Swift 中,当匹配的 case 分支中的代码执行完毕后,程序会终止switch语句,而不会继续执行下一个 case 分支。这也就是说,不需要在 case 分支中显式地使用break语句。
//: 值绑定
let anotherPoint = (2, 0)
switch anotherPoint {
case (let x, 0):
print(x)
case (0, let y):
print(y)
case let (x, y):
print("\(x), \(y)")
}
//: Where
// case 分支的模式可以使用where语句来判断额外的条件
let yetAnotherPoint = (1, -1)
switch yetAnotherPoint {
case let (x, y) where x == y:
print("(\(x), \(y)) is on the line x == y")
case let (x, y) where x == -y:
print("(\(x), \(y)) is on the line x == -y")
case let (x, y):
print("(\(x), \(y)) is just some arbitrary point")
}
// 输出 "(1, -1) is on the line x == -y"}
//: 复合匹配
// 当多个条件可以使用同一种方法来处理时,可以将这几种可能放在同一个case后面,并且用逗号隔开。当case后面的任意一种模式匹配的时候,这条分支就会被匹配。并且,如果匹配列表过长,还可以分行书写:
let someCharacter: Character = "e"
switch someCharacter {
case "a", "e", "i", "o", "u":
print("\(someCharacter) is a vowel")
case "b", "c", "d", "f", "g", "h", "j", "k", "l", "m",
"n", "p", "q", "r", "s", "t", "v", "w", "x", "y", "z":
print("\(someCharacter) is a consonant")
default:
print("\(someCharacter) is not a vowel or a consonant")
}
// 输出 "e is a vowel"
//: 控制转移语句
// continue
// break
// fallthrough
// return
// throw
//: 带标签的语句
//: 在 Swift 中,你可以在循环体和条件语句中嵌套循环体和条件语句来创造复杂的控制流结构。并且,循环体和条件语句都可以使用break语句来提前结束整个代码块。因此,显式地指明break语句想要终止的是哪个循环体或者条件语句,会很有用。类似地,如果你有许多嵌套的循环体,显式指明continue语句想要影响哪一个循环体也会非常有用。
//: 声明一个带标签的语句是通过在该语句的关键词的同一行前面放置一个标签,作为这个语句的前导关键字(introducor keyword),并且该标签后面跟随一个冒号。下面是一个针对while循环体的标签语法,同样的规则适用于所有的循环体和条件语句。 label name: while condition { statements }
//let finalSquare = 25
//var board = [Int](repeating: 0, count: finalSquare + 1)
//board[03] = +08; board[06] = +11; board[09] = +09; board[10] = +02
//board[14] = -10; board[19] = -11; board[22] = -02; board[24] = -08
//var square = 0
//var diceRoll = 0
//
//gameLoop: while square != finalSquare {
// diceRoll += 1
// if diceRoll == 7 { diceRoll = 1 }
// switch square + diceRoll {
// case finalSquare:
// // 骰子数刚好使玩家移动到最终的方格里,游戏结束。
// break gameLoop
// case let newSquare where newSquare > finalSquare:
// // 骰子数将会使玩家的移动超出最后的方格,那么这种移动是不合法的,玩家需要重新掷骰子
// continue gameLoop
// default:
// // 合法移动,做正常的处理
// square += diceRoll
// square += board[square]
// }
//}
//print("Game over!")
//: guard
//: 像if语句一样,guard的执行取决于一个表达式的布尔值。我们可以使用guard语句来要求条件必须为真时,以执行guard语句后的代码。不同于if语句,一个guard语句总是有一个else从句,如果条件不为真则执行else从句中的代码。
func greet(person: [String: String]) {
guard let name = person["name"] else {
return
}
print("Hello \(name)")
guard let location = person["location"] else {
print("I hope the weather is nice near you.")
return
}
print("I hope the weather is nice in \(location).")
}
greet(person: ["name": "John"])
// 输出 "Hello John!"
// 输出 "I hope the weather is nice near you."
greet(person: ["name": "Jane", "location": "Cupertino"])
// 输出 "Hello Jane!"
// 输出 "I hope the weather is nice in Cupertino."
//: 检测 API 的可用性
if #available(iOS 10, macOS 10.12, *) {
// 在 iOS 使用 iOS 10 的 API, 在 macOS 使用 macOS 10.12 的 API
} else {
// 使用先前版本的 iOS 和 macOS 的 API
}
| mit | 28953bfc220216b63d81fa50bebaea96 | 23.801471 | 169 | 0.621702 | 2.63928 | false | false | false | false |
ruslanskorb/CoreStore | Sources/BaseDataTransaction.swift | 1 | 20405 | //
// BaseDataTransaction.swift
// CoreStore
//
// Copyright © 2018 John Rommel Estropia
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
import Foundation
import CoreData
// MARK: - BaseDataTransaction
/**
The `BaseDataTransaction` is an abstract interface for `NSManagedObject` creates, updates, and deletes. All `BaseDataTransaction` subclasses manage a private `NSManagedObjectContext` which are direct children of the `NSPersistentStoreCoordinator`'s root `NSManagedObjectContext`. This means that all updates are saved first to the persistent store, and then propagated up to the read-only `NSManagedObjectContext`.
*/
public /*abstract*/ class BaseDataTransaction {
// MARK: Object management
/**
Indicates if the transaction has pending changes
*/
public var hasChanges: Bool {
return self.context.hasChanges
}
/**
Creates a new `NSManagedObject` or `CoreStoreObject` with the specified entity type.
- parameter into: the `Into` clause indicating the destination `NSManagedObject` or `CoreStoreObject` entity type and the destination configuration
- returns: a new `NSManagedObject` or `CoreStoreObject` instance of the specified entity type.
*/
public func create<O>(_ into: Into<O>) -> O {
let entityClass = into.entityClass
Internals.assert(
self.isRunningInAllowedQueue(),
"Attempted to create an entity of type \(Internals.typeName(entityClass)) outside its designated queue."
)
let context = self.context
let dataStack = context.parentStack!
let entityIdentifier = Internals.EntityIdentifier(entityClass)
if into.inferStoreIfPossible {
switch dataStack.persistentStore(
for: entityIdentifier,
configuration: nil,
inferStoreIfPossible: true
) {
case (let persistentStore?, _):
return entityClass.cs_forceCreate(
entityDescription: dataStack.entityDescription(for: entityIdentifier)!,
into: context,
assignTo: persistentStore
)
case (nil, true):
Internals.abort("Attempted to create an entity of type \(Internals.typeName(entityClass)) with ambiguous destination persistent store, but the configuration name was not specified.")
default:
Internals.abort("Attempted to create an entity of type \(Internals.typeName(entityClass)), but a destination persistent store containing the entity type could not be found.")
}
}
else {
switch dataStack.persistentStore(
for: entityIdentifier,
configuration: into.configuration
?? DataStack.defaultConfigurationName,
inferStoreIfPossible: false
) {
case (let persistentStore?, _):
return entityClass.cs_forceCreate(
entityDescription: dataStack.entityDescription(for: entityIdentifier)!,
into: context,
assignTo: persistentStore
)
case (nil, true):
Internals.abort("Attempted to create an entity of type \(Internals.typeName(entityClass)) with ambiguous destination persistent store, but the configuration name was not specified.")
default:
if let configuration = into.configuration {
Internals.abort("Attempted to create an entity of type \(Internals.typeName(entityClass)) into the configuration \"\(configuration)\", which it doesn't belong to.")
}
else {
Internals.abort("Attempted to create an entity of type \(Internals.typeName(entityClass)) into the default configuration, which it doesn't belong to.")
}
}
}
}
/**
Returns an editable proxy of a specified `NSManagedObject` or `CoreStoreObject`.
- parameter object: the `NSManagedObject` or `CoreStoreObject` type to be edited
- returns: an editable proxy for the specified `NSManagedObject` or `CoreStoreObject`.
*/
public func edit<O: DynamicObject>(_ object: O?) -> O? {
Internals.assert(
self.isRunningInAllowedQueue(),
"Attempted to update an entity of type \(Internals.typeName(object)) outside its designated queue."
)
guard let object = object else {
return nil
}
return self.context.fetchExisting(object)
}
/**
Returns an editable proxy of the object with the specified `NSManagedObjectID`.
- parameter into: an `Into` clause specifying the entity type
- parameter objectID: the `NSManagedObjectID` for the object to be edited
- returns: an editable proxy for the specified `NSManagedObject` or `CoreStoreObject`.
*/
public func edit<O>(_ into: Into<O>, _ objectID: NSManagedObjectID) -> O? {
Internals.assert(
self.isRunningInAllowedQueue(),
"Attempted to update an entity of type \(Internals.typeName(into.entityClass)) outside its designated queue."
)
Internals.assert(
into.inferStoreIfPossible
|| (into.configuration ?? DataStack.defaultConfigurationName) == objectID.persistentStore?.configurationName,
"Attempted to update an entity of type \(Internals.typeName(into.entityClass)) but the specified persistent store do not match the `NSManagedObjectID`."
)
return self.fetchExisting(objectID)
}
/**
Deletes the objects with the specified `NSManagedObjectID`s.
- parameter objectIDs: the `NSManagedObjectID`s of the objects to delete
*/
public func delete<S: Sequence>(objectIDs: S) where S.Iterator.Element: NSManagedObjectID {
Internals.assert(
self.isRunningInAllowedQueue(),
"Attempted to delete an entity outside its designated queue."
)
let context = self.context
objectIDs.forEach {
context.fetchExisting($0).map(context.delete(_:))
}
}
/**
Deletes the specified `NSManagedObject`s or `CoreStoreObject`s represented by series of `ObjectRepresentation`s.
- parameter object: the `ObjectRepresentation` representing an `NSManagedObject` or `CoreStoreObject` to be deleted
- parameter objects: other `ObjectRepresentation`s representing `NSManagedObject`s or `CoreStoreObject`s to be deleted
*/
public func delete<O: ObjectRepresentation>(_ object: O?, _ objects: O?...) {
Internals.assert(
self.isRunningInAllowedQueue(),
"Attempted to delete an entity outside its designated queue."
)
self.delete(([object] + objects).compactMap { $0 })
}
/**
Deletes the specified `NSManagedObject`s or `CoreStoreObject`s represented by an `ObjectRepresenation`.
- parameter objects: the `ObjectRepresenation`s representing `NSManagedObject`s or `CoreStoreObject`s to be deleted
*/
public func delete<S: Sequence>(_ objects: S) where S.Iterator.Element: ObjectRepresentation {
Internals.assert(
self.isRunningInAllowedQueue(),
"Attempted to delete entities outside their designated queue."
)
let context = self.context
objects.forEach {
$0.asEditable(in: self).map({ context.delete($0.cs_toRaw()) })
}
}
/**
Refreshes all registered objects `NSManagedObject`s in the transaction.
*/
public func refreshAndMergeAllObjects() {
Internals.assert(
self.isRunningInAllowedQueue(),
"Attempted to refresh entities outside their designated queue."
)
self.context.refreshAndMergeAllObjects()
}
// MARK: Inspecting Pending Objects
/**
Returns `true` if the object has any property values changed. This method should not be called after the `commit()` method was called.
- parameter object: the `DynamicObject` instance
- returns: `true` if the object has any property values changed.
*/
public func objectHasPersistentChangedValues<O: DynamicObject>(_ object: O) -> Bool {
Internals.assert(
self.isRunningInAllowedQueue(),
"Attempted to access inserted objects from a \(Internals.typeName(self)) outside its designated queue."
)
Internals.assert(
!self.isCommitted,
"Attempted to access inserted objects from an already committed \(Internals.typeName(self))."
)
return object.cs_toRaw().hasPersistentChangedValues
}
/**
Returns all pending `DynamicObject`s of the specified type that were inserted to the transaction. This method should not be called after the `commit()` method was called.
- parameter entity: the `DynamicObject` subclass to filter
- returns: a `Set` of pending `DynamicObject`s of the specified type that were inserted to the transaction.
*/
public func insertedObjects<O: DynamicObject>(_ entity: O.Type) -> Set<O> {
Internals.assert(
self.isRunningInAllowedQueue(),
"Attempted to access inserted objects from a \(Internals.typeName(self)) outside its designated queue."
)
Internals.assert(
!self.isCommitted,
"Attempted to access inserted objects from an already committed \(Internals.typeName(self))."
)
return Set(self.context.insertedObjects.compactMap({ entity.cs_matches(object: $0) ? entity.cs_fromRaw(object: $0) : nil }))
}
/**
Returns all pending `NSManagedObjectID`s that were inserted to the transaction. This method should not be called after the `commit()` method was called.
- returns: a `Set` of pending `NSManagedObjectID`s that were inserted to the transaction.
*/
public func insertedObjectIDs() -> Set<NSManagedObjectID> {
Internals.assert(
self.isRunningInAllowedQueue(),
"Attempted to access inserted object IDs from a \(Internals.typeName(self)) outside its designated queue."
)
Internals.assert(
!self.isCommitted,
"Attempted to access inserted objects IDs from an already committed \(Internals.typeName(self))."
)
return Set(self.context.insertedObjects.map { $0.objectID })
}
/**
Returns all pending `NSManagedObjectID`s of the specified type that were inserted to the transaction. This method should not be called after the `commit()` method was called.
- parameter entity: the `DynamicObject` subclass to filter
- returns: a `Set` of pending `NSManagedObjectID`s of the specified type that were inserted to the transaction.
*/
public func insertedObjectIDs<O: DynamicObject>(_ entity: O.Type) -> Set<NSManagedObjectID> {
Internals.assert(
self.isRunningInAllowedQueue(),
"Attempted to access inserted object IDs from a \(Internals.typeName(self)) outside its designated queue."
)
Internals.assert(
!self.isCommitted,
"Attempted to access inserted objects IDs from an already committed \(Internals.typeName(self))."
)
return Set(self.context.insertedObjects.compactMap({ entity.cs_matches(object: $0) ? $0.objectID : nil }))
}
/**
Returns all pending `DynamicObject`s of the specified type that were updated in the transaction. This method should not be called after the `commit()` method was called.
- parameter entity: the `DynamicObject` subclass to filter
- returns: a `Set` of pending `DynamicObject`s of the specified type that were updated in the transaction.
*/
public func updatedObjects<O: DynamicObject>(_ entity: O.Type) -> Set<O> {
Internals.assert(
self.isRunningInAllowedQueue(),
"Attempted to access updated objects from a \(Internals.typeName(self)) outside its designated queue."
)
Internals.assert(
!self.isCommitted,
"Attempted to access updated objects from an already committed \(Internals.typeName(self))."
)
return Set(self.context.updatedObjects.compactMap({ entity.cs_matches(object: $0) ? entity.cs_fromRaw(object: $0) : nil }))
}
/**
Returns all pending `NSManagedObjectID`s that were updated in the transaction. This method should not be called after the `commit()` method was called.
- returns: a `Set` of pending `NSManagedObjectID`s that were updated in the transaction.
*/
public func updatedObjectIDs() -> Set<NSManagedObjectID> {
Internals.assert(
self.isRunningInAllowedQueue(),
"Attempted to access updated object IDs from a \(Internals.typeName(self)) outside its designated queue."
)
Internals.assert(
!self.isCommitted,
"Attempted to access updated object IDs from an already committed \(Internals.typeName(self))."
)
return Set(self.context.updatedObjects.map { $0.objectID })
}
/**
Returns all pending `NSManagedObjectID`s of the specified type that were updated in the transaction. This method should not be called after the `commit()` method was called.
- parameter entity: the `DynamicObject` subclass to filter
- returns: a `Set` of pending `NSManagedObjectID`s of the specified type that were updated in the transaction.
*/
public func updatedObjectIDs<O: DynamicObject>(_ entity: O.Type) -> Set<NSManagedObjectID> {
Internals.assert(
self.isRunningInAllowedQueue(),
"Attempted to access updated object IDs from a \(Internals.typeName(self)) outside its designated queue."
)
Internals.assert(
!self.isCommitted,
"Attempted to access updated object IDs from an already committed \(Internals.typeName(self))."
)
return Set(self.context.updatedObjects.compactMap({ entity.cs_matches(object: $0) ? $0.objectID : nil }))
}
/**
Returns all pending `DynamicObject`s of the specified type that were deleted from the transaction. This method should not be called after the `commit()` method was called.
- parameter entity: the `DynamicObject` subclass to filter
- returns: a `Set` of pending `DynamicObject`s of the specified type that were deleted from the transaction.
*/
public func deletedObjects<O: DynamicObject>(_ entity: O.Type) -> Set<O> {
Internals.assert(
self.isRunningInAllowedQueue(),
"Attempted to access deleted objects from a \(Internals.typeName(self)) outside its designated queue."
)
Internals.assert(
!self.isCommitted,
"Attempted to access deleted objects from an already committed \(Internals.typeName(self))."
)
return Set(self.context.deletedObjects.compactMap({ entity.cs_matches(object: $0) ? entity.cs_fromRaw(object: $0) : nil }))
}
/**
Returns all pending `NSManagedObjectID`s of the specified type that were deleted from the transaction. This method should not be called after the `commit()` method was called.
- parameter entity: the `DynamicObject` subclass to filter
- returns: a `Set` of pending `NSManagedObjectID`s of the specified type that were deleted from the transaction.
*/
public func deletedObjectIDs() -> Set<NSManagedObjectID> {
Internals.assert(
self.isRunningInAllowedQueue(),
"Attempted to access deleted object IDs from a \(Internals.typeName(self)) outside its designated queue."
)
Internals.assert(
!self.isCommitted,
"Attempted to access deleted object IDs from an already committed \(Internals.typeName(self))."
)
return Set(self.context.deletedObjects.map { $0.objectID })
}
/**
Returns all pending `NSManagedObjectID`s of the specified type that were deleted from the transaction. This method should not be called after the `commit()` method was called.
- parameter entity: the `DynamicObject` subclass to filter
- returns: a `Set` of pending `NSManagedObjectID`s of the specified type that were deleted from the transaction.
*/
public func deletedObjectIDs<O: DynamicObject>(_ entity: O.Type) -> Set<NSManagedObjectID> {
Internals.assert(
self.isRunningInAllowedQueue(),
"Attempted to access deleted object IDs from a \(Internals.typeName(self)) outside its designated queue."
)
Internals.assert(
!self.isCommitted,
"Attempted to access deleted object IDs from an already committed \(Internals.typeName(self))."
)
return Set(self.context.deletedObjects.compactMap({ entity.cs_matches(object: $0) ? $0.objectID : nil }))
}
// MARK: 3rd Party Utilities
/**
Allow external libraries to store custom data in the transaction. App code should rarely have a need for this.
```
enum Static {
static var myDataKey: Void?
}
transaction.userInfo[&Static.myDataKey] = myObject
```
- Important: Do not use this method to store thread-sensitive data.
*/
public let userInfo = UserInfo()
// MARK: Internal
internal let context: NSManagedObjectContext
internal let transactionQueue: DispatchQueue
internal let childTransactionQueue = DispatchQueue.serial("com.corestore.datastack.childTransactionQueue")
internal let supportsUndo: Bool
internal let bypassesQueueing: Bool
internal var isCommitted = false
internal var result: (hasChanges: Bool, error: CoreStoreError?)?
internal init(mainContext: NSManagedObjectContext, queue: DispatchQueue, supportsUndo: Bool, bypassesQueueing: Bool) {
let context = mainContext.temporaryContextInTransactionWithConcurrencyType(
queue == .main
? .mainQueueConcurrencyType
: .privateQueueConcurrencyType
)
self.transactionQueue = queue
self.context = context
self.supportsUndo = supportsUndo
self.bypassesQueueing = bypassesQueueing
context.parentTransaction = self
context.isTransactionContext = true
if !supportsUndo {
context.undoManager = nil
}
else if context.undoManager == nil {
context.undoManager = UndoManager()
}
}
internal func isRunningInAllowedQueue() -> Bool {
return self.bypassesQueueing || self.transactionQueue.cs_isCurrentExecutionContext()
}
deinit {
self.context.reset()
}
}
| mit | 10b0d171efe84483396b9183fc5d0b68 | 42.320594 | 415 | 0.64752 | 5.234479 | false | false | false | false |
bixubot/AcquainTest | ChatRoom/ChatRoom/NewMessageController.swift | 1 | 3077 | //
// NewMessageController.swift
// ChatRoom
//
// Created by Binwei Xu on 3/22/17.
// Copyright © 2017 Binwei Xu. All rights reserved.
//
import UIKit
import Firebase
class NewMessageController: UITableViewController {
//class variables
let cellId = "cellId"
var users = [User]() // array to store all other users visible to current user
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.leftBarButtonItem = UIBarButtonItem(title: "Cancel", style: .plain, target: self, action: #selector(handleCancel))
tableView.register(UserCell.self, forCellReuseIdentifier: cellId)
fetchUser()
}
func fetchUser() {
// We can change the directory here to fetch only the connected friends
FIRDatabase.database().reference().child("users").observe(.childAdded, with: { (snapshot) in
if let dictionary = snapshot.value as? [String: AnyObject] {
let user = User()
user.id = snapshot.key
// this setter may crash the app if the User class properties don't exactly match up with the Firebase dictionary keys
user.setValuesForKeys(dictionary)
self.users.append(user)
// This will crash because of background thread, so let's use dispatch_async to fix
DispatchQueue.main.async {
self.tableView.reloadData()
}
// safer choice instead of the setter above is to individually fetch and set the values
// user.name = dictionary["name"]
}
}, withCancel: nil)
}
// return to MessageController
func handleCancel() {
dismiss(animated: true, completion: nil)
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return users.count
}
var messagesController: MessageController?
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
dismiss(animated: true) {
let user = self.users[indexPath.row]
self.messagesController?.showChatControllerForUser(user: user)
}
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: cellId, for: indexPath) as! UserCell
let user = users[indexPath.row]
cell.textLabel?.text = user.name
cell.detailTextLabel?.text = user.email
if let profileImageUrl = user.profileImageUrl {
cell.profileImageView.loadImageUsingCacheWithUrlString(urlString: profileImageUrl)
}
return cell
}
// set the height of each cell
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 66
}
}
| mit | 7e32a3b4b9cd73388323f3165888fcd9 | 32.802198 | 137 | 0.613459 | 5.396491 | false | false | false | false |
sima-11/SMSegmentView | SMSegmentViewController/ViewController.swift | 3 | 3880 | //
// SMSegmentViewController
//
// Created by Si Ma on 05/01/2015.
// Copyright (c) 2015 Si Ma. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
var segmentView: SMSegmentView!
var margin: CGFloat = 10.0
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor(white: 0.95, alpha: 1.0)
/*
Use SMSegmentAppearance to set segment related UI properties.
Each property has its own default value, so you only need to specify the ones you are interested.
*/
let appearance = SMSegmentAppearance()
appearance.segmentOnSelectionColour = UIColor(red: 245.0/255.0, green: 174.0/255.0, blue: 63.0/255.0, alpha: 1.0)
appearance.segmentOffSelectionColour = UIColor.white
appearance.titleOnSelectionFont = UIFont.systemFont(ofSize: 12.0)
appearance.titleOffSelectionFont = UIFont.systemFont(ofSize: 12.0)
appearance.contentVerticalMargin = 10.0
/*
Init SMsegmentView
Set divider colour and width here if there is a need
*/
let segmentFrame = CGRect(x: self.margin, y: 120.0, width: self.view.frame.size.width - self.margin*2, height: 40.0)
self.segmentView = SMSegmentView(frame: segmentFrame, dividerColour: UIColor(white: 0.95, alpha: 0.3), dividerWidth: 1.0, segmentAppearance: appearance)
self.segmentView.backgroundColor = UIColor.clear
self.segmentView.layer.cornerRadius = 5.0
self.segmentView.layer.borderColor = UIColor(white: 0.85, alpha: 1.0).cgColor
self.segmentView.layer.borderWidth = 1.0
// Add segments
self.segmentView.addSegmentWithTitle("Clip", onSelectionImage: UIImage(named: "clip_light"), offSelectionImage: UIImage(named: "clip"))
self.segmentView.addSegmentWithTitle("Blub", onSelectionImage: UIImage(named: "bulb_light"), offSelectionImage: UIImage(named: "bulb"))
self.segmentView.addSegmentWithTitle("Cloud", onSelectionImage: UIImage(named: "cloud_light"), offSelectionImage: UIImage(named: "cloud"))
self.segmentView.addTarget(self, action: #selector(selectSegmentInSegmentView(segmentView:)), for: .valueChanged)
// Set segment with index 0 as selected by default
self.segmentView.selectedSegmentIndex = 0
self.view.addSubview(self.segmentView)
}
// SMSegment selector for .ValueChanged
func selectSegmentInSegmentView(segmentView: SMSegmentView) {
/*
Replace the following line to implement what you want the app to do after the segment gets tapped.
*/
print("Select segment at index: \(segmentView.selectedSegmentIndex)")
}
override func willAnimateRotation(to toInterfaceOrientation: UIInterfaceOrientation, duration: TimeInterval) {
/*
MARK: Replace the following line to your own frame setting for segmentView.
*/
if toInterfaceOrientation == UIInterfaceOrientation.landscapeLeft || toInterfaceOrientation == UIInterfaceOrientation.landscapeRight {
self.segmentView.organiseMode = .vertical
if let appearance = self.segmentView.segmentAppearance {
appearance.contentVerticalMargin = 25.0
}
self.segmentView.frame = CGRect(x: self.view.frame.size.width/2 - 40.0, y: 100.0, width: 80.0, height: 220.0)
}
else {
self.segmentView.organiseMode = .horizontal
if let appearance = self.segmentView.segmentAppearance {
appearance.contentVerticalMargin = 10.0
}
self.segmentView.frame = CGRect(x: self.margin, y: 120.0, width: self.view.frame.size.width - self.margin*2, height: 40.0)
}
}
}
| mit | a4f47ab2c0fb32753ac25ad46d5ceda6 | 43.597701 | 160 | 0.662113 | 4.743276 | false | false | false | false |
Allow2CEO/browser-ios | Storage/SQL/SchemaTable.swift | 7 | 2132 | /* 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
// A table for holding info about other tables (also holds info about itself :)). This is used
// to let us handle table upgrades when the table is first accessed, rather than when the database
// itself is created.
class SchemaTable: GenericTable<TableInfo> {
override var name: String { return "tableList" }
override var version: Int { return 1 }
override var rows: String { return "id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"name TEXT NOT NULL UNIQUE, " +
"version INTEGER NOT NULL" }
override func getInsertAndArgs(_ item: inout TableInfo) -> (String, Args)? {
var args = Args()
args.append(item.name as String )
args.append(item.version )
return ("INSERT INTO \(name) (name, version) VALUES (?,?)", args)
}
override func getUpdateAndArgs(_ item: inout TableInfo) -> (String, Args)? {
var args = Args()
args.append(item.version )
args.append(item.name as String )
return ("UPDATE \(name) SET version = ? WHERE name = ?", args)
}
override func getDeleteAndArgs(_ item: inout TableInfo?) -> (String, Args)? {
var args = Args()
var sql = "DELETE FROM \(name)"
if let table = item {
args.append(table.name as String )
sql += " WHERE name = ?"
}
return (sql, args)
}
override var factory: ((_ row: SDRow) -> TableInfo)? {
return { row -> TableInfo in
return TableInfoWrapper(name: row["name"] as! String, version: row["version"] as! Int)
}
}
override func getQueryAndArgs(_ options: QueryOptions?) -> (String, Args)? {
var args = Args()
if let filter: Any = options?.filter {
args.append(filter)
return ("SELECT name, version FROM \(name) WHERE name = ?", args)
}
return ("SELECT name, version FROM \(name)", args)
}
}
| mpl-2.0 | a98e28e3705ca100ee61eaf27dde49ff | 37.071429 | 98 | 0.606942 | 4.19685 | false | false | false | false |
prebid/prebid-mobile-ios | Example/PrebidDemo/PrebidDemoTests/Helpers/StubbingHandler.swift | 1 | 1768 | /* Copyright 2018-2021 Prebid.org, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import Foundation
import TestUtils
public class StubbingHandler {
private init() {}
public static let shared = StubbingHandler()
public func turnOn() {
PBHTTPStubbingManager.shared().enable()
PBHTTPStubbingManager.shared().ignoreUnstubbedRequests = true
PBHTTPStubbingManager.shared().broadcastRequests = true
}
public func turnOff() {
PBHTTPStubbingManager.shared().disable()
PBHTTPStubbingManager.shared().removeAllStubs()
PBHTTPStubbingManager.shared().broadcastRequests = false
PBHTTPStubbingManager.shared().ignoreUnstubbedRequests = true
}
public func stubRequest(with responseName: String, requestURL: String) {
let currentBundle = Bundle(for: TestUtils.PBHTTPStubbingManager.self)
let baseResponse = try? String(contentsOfFile: currentBundle.path(forResource: responseName, ofType: "json") ?? "", encoding: .utf8)
let requestStub = PBURLConnectionStub()
requestStub.requestURL = requestURL
requestStub.responseCode = 200
requestStub.responseBody = baseResponse
PBHTTPStubbingManager.shared().add(requestStub)
}
}
| apache-2.0 | d765ad1c1190f0a95a57f762e6291d32 | 36.617021 | 140 | 0.723416 | 4.727273 | false | false | false | false |
NachoSoto/protobuf-swift | src/ProtocolBuffers/runtime-pb-swift/AbstractMessage.swift | 1 | 5802 | // Protocol Buffers for Swift
//
// Copyright 2014 Alexey Khohklov(AlexeyXo).
// Copyright 2008 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License")
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import Foundation
public typealias ONEOF_NOT_SET = Int
public protocol MessageInit:class
{
init()
}
public protocol Message:class,MessageInit
{
var unknownFields:UnknownFieldSet{get}
func serializedSize() -> Int32
func isInitialized() -> Bool
func writeToCodedOutputStream(output:CodedOutputStream)
func writeToOutputStream(output:NSOutputStream)
func data()-> NSData
class func classBuilder()-> MessageBuilder
func classBuilder()-> MessageBuilder
}
public protocol MessageBuilder: class
{
var unknownFields:UnknownFieldSet{get set}
func clear() -> Self
func isInitialized()-> Bool
func build() -> AbstractMessage
func mergeUnknownFields(unknownField:UnknownFieldSet) ->Self
func mergeFromCodedInputStream(input:CodedInputStream) -> Self
func mergeFromCodedInputStream(input:CodedInputStream, extensionRegistry:ExtensionRegistry) -> Self
func mergeFromData(data:NSData) -> Self
func mergeFromData(data:NSData, extensionRegistry:ExtensionRegistry) -> Self
func mergeFromInputStream(input:NSInputStream) -> Self
func mergeFromInputStream(input:NSInputStream, extensionRegistry:ExtensionRegistry) -> Self
}
public func == (lhs: AbstractMessage, rhs: AbstractMessage) -> Bool
{
return true
}
public class AbstractMessage:Equatable, Hashable, Message {
public var unknownFields:UnknownFieldSet
required public init()
{
unknownFields = UnknownFieldSet(fields: Dictionary())
}
public func data() -> NSData
{
var ser_size = serializedSize()
let data = NSMutableData(length: Int(ser_size))!
var stream:CodedOutputStream = CodedOutputStream(data: data)
writeToCodedOutputStream(stream)
return stream.buffer.buffer
}
public func isInitialized() -> Bool
{
return false
}
public func serializedSize() -> Int32
{
return 0
}
public func writeDescriptionTo(inout output:String, indent:String)
{
NSException(name:"Override", reason:"", userInfo: nil).raise()
}
public func writeToCodedOutputStream(output: CodedOutputStream)
{
NSException(name:"Override", reason:"", userInfo: nil).raise()
}
public func writeToOutputStream(output: NSOutputStream)
{
var codedOutput:CodedOutputStream = CodedOutputStream(output:output)
writeToCodedOutputStream(codedOutput)
codedOutput.flush()
}
public class func classBuilder() -> MessageBuilder
{
return AbstractMessageBuilder()
}
public func classBuilder() -> MessageBuilder
{
return AbstractMessageBuilder()
}
public var hashValue: Int {
get {
return 0
}
}
}
public class AbstractMessageBuilder:MessageBuilder
{
public var unknownFields:UnknownFieldSet
public init()
{
unknownFields = UnknownFieldSet(fields:Dictionary())
}
public func build() -> AbstractMessage {
return AbstractMessage()
}
public func clone() -> Self
{
return self
}
public func clear() -> Self
{
return self
}
public func isInitialized() -> Bool
{
return false
}
public func mergeFromCodedInputStream(input:CodedInputStream) -> Self
{
return mergeFromCodedInputStream(input, extensionRegistry:ExtensionRegistry())
}
public func mergeFromCodedInputStream(input:CodedInputStream, extensionRegistry:ExtensionRegistry) -> Self
{
NSException(name:"ImproperSubclassing", reason:"", userInfo: nil).raise()
return self
}
public func mergeUnknownFields(unknownField:UnknownFieldSet) -> Self
{
var merged:UnknownFieldSet = UnknownFieldSet.builderWithUnknownFields(unknownFields).mergeUnknownFields(unknownField).build()
unknownFields = merged
return self
}
public func mergeFromData(data:NSData) -> Self
{
var input:CodedInputStream = CodedInputStream(data:data)
mergeFromCodedInputStream(input)
input.checkLastTagWas(0)
return self
}
public func mergeFromData(data:NSData, extensionRegistry:ExtensionRegistry) -> Self
{
var input:CodedInputStream = CodedInputStream(data:data)
mergeFromCodedInputStream(input, extensionRegistry:extensionRegistry)
input.checkLastTagWas(0)
return self
}
public func mergeFromInputStream(input:NSInputStream) -> Self
{
var codedInput:CodedInputStream = CodedInputStream(inputStream: input)
mergeFromCodedInputStream(codedInput)
codedInput.checkLastTagWas(0)
return self
}
public func mergeFromInputStream(input:NSInputStream, extensionRegistry:ExtensionRegistry) -> Self
{
var codedInput:CodedInputStream = CodedInputStream(inputStream: input)
mergeFromCodedInputStream(codedInput, extensionRegistry:extensionRegistry)
codedInput.checkLastTagWas(0)
return self
}
}
| apache-2.0 | 7066448bc31ecba9f24be56ae6ce277b | 27.441176 | 133 | 0.684936 | 5.284153 | false | false | false | false |
wanderwaltz/SwiftSquirrel | SwiftSquirrel/Compiler.swift | 1 | 2221 | //
// Compiler.swift
// SwiftSquirrel
//
// Created by Egor Chiglintsev on 18.04.15.
// Copyright (c) 2015 Egor Chiglintsev
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
import Foundation
import CSquirrel
public class Compiler {
public typealias Result = SwiftSquirrel.Result<String, SQValue>
init(vm: SquirrelVM) {
self.vm = vm.vm
self.stack = vm.stack
}
// MARK: - methods
public func execute(#script: String) -> Result {
var result = Result.error("Unknown error occurred")
let (length, cScript) = script.toSquirrelString()
let top = stack.top
if (SQ_SUCCEEDED(sq_compilebuffer(vm, cScript, length, cBufferName, SQBool(SQTrue)))) {
sq_pushroottable(vm)
if (SQ_SUCCEEDED(sq_call(vm, 1, SQBool(SQTrue), SQBool(SQTrue)))) {
result = Result.success(stack[-1])
}
}
stack.top = top
return result
}
// MARK: - private
private let vm: HSQUIRRELVM
private let stack: Stack
private let (bufferNameLength, cBufferName) = "buffer".toSquirrelString()
} | mit | 4cd42b73f636a62f9302587bb001e611 | 34.83871 | 95 | 0.669068 | 4.13594 | false | false | false | false |
corchwll/amos-ss15-proj5_ios | MobileTimeAccounting/UserInterface/Projects/EditProjectTableViewController.swift | 1 | 7401 | /*
Mobile Time Accounting
Copyright (C) 2015
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import UIKit
import MapKit
protocol EditProjectDelegate
{
func didEditProject()
}
class EditProjectTableViewController: UITableViewController, CLLocationManagerDelegate
{
@IBOutlet weak var projectIDLabel: UILabel!
@IBOutlet weak var projectNameTextField: UITextField!
@IBOutlet weak var projectFinalDateTextField: UITextField!
@IBOutlet weak var projectLatitudeTextField: UITextField!
@IBOutlet weak var projectLongitudeTextField: UITextField!
@IBOutlet weak var doneButton: UIBarButtonItem!
@IBOutlet weak var locationProcessIndicatorView: UIActivityIndicatorView!
@IBOutlet weak var findLocationButton: UIButton!
var delegate: EditProjectDelegate!
var project: Project!
let datePicker = UIDatePicker()
let dateFormatter = NSDateFormatter()
let locationManager = CLLocationManager()
/*
iOS life-cycle function, called when view did load. Sets up date formatter and input view for date picker.
@methodtype Hook
@pre -
@post View is set up
*/
override func viewDidLoad()
{
super.viewDidLoad()
setUpDateFormatter()
setUpDatePickerInputView()
setUpLocationManager()
setUpProject()
refreshDoneButtonState()
}
/*
Function is called to set up date formatter.
@methodtype Command
@pre -
@post Date formatter has been set up
*/
func setUpDateFormatter()
{
dateFormatter.timeStyle = NSDateFormatterStyle.NoStyle
dateFormatter.dateStyle = NSDateFormatterStyle.MediumStyle
}
/*
Function is called to set up date picker input view.
@methodtype Command
@pre -
@post Input view has been set up
*/
func setUpDatePickerInputView()
{
datePicker.datePickerMode = UIDatePickerMode.Date
datePicker.addTarget(self, action: Selector("datePickerDidChange"), forControlEvents: UIControlEvents.ValueChanged)
projectFinalDateTextField.inputView = datePicker
}
/*
Sets up location manager.
@methodtype Command
@pre Location manager must be initialized
@post Location manager is set up
*/
func setUpLocationManager()
{
locationManager.delegate = self
locationManager.requestAlwaysAuthorization()
locationManager.desiredAccuracy = kCLLocationAccuracyBest
}
/*
Sets up project that is about to be edited.
@methodtype Command
@pre Project must be set
@post Project is set, ui is updated
*/
func setUpProject()
{
//fixed values
projectIDLabel.text = project.id
projectNameTextField.text = project.name
//optional values
projectFinalDateTextField.text = project.finalDate.timeIntervalSince1970 == 0 ? "-" : dateFormatter.stringFromDate(project.finalDate)
projectLatitudeTextField.text = project.location.coordinate.latitude == 0.0 ? "-" : "\(project.location.coordinate.latitude)"
projectLongitudeTextField.text = project.location.coordinate.longitude == 0.0 ? "-" : "\(project.location.coordinate.longitude)"
}
/*
Function is called when date picker has changed. Sets text field to selected date.
@methodtype Hook
@pre -
@post Final date text field has been set to selected date
*/
func datePickerDidChange()
{
projectFinalDateTextField.text = dateFormatter.stringFromDate(datePicker.date)
}
/*
iOS listener function. Called when editing project name, refreshes 'done'-button state.
@methodtype Command
@pre -
@post Refreshes done button
*/
@IBAction func projectNameChanged(sender: AnyObject)
{
refreshDoneButtonState()
}
/*
Function for enabling 'done'-button. Button will be enabled when all mandatory text fiels are filled.
@methodtype Command
@pre Text field are not empty
@post Button will be enabled
*/
func refreshDoneButtonState()
{
var isEmpty = false
isEmpty = isEmpty || projectNameTextField.text.isEmpty
doneButton.enabled = !isEmpty
}
/*
Determines current location and fills in coordinates into ui. Start process indicator animation and hides button.
@methodtype Command
@pre Location manager has been initialized
@post Finding location process is triggered
*/
@IBAction func getCurrentLocation(sender: AnyObject)
{
locationManager.startUpdatingLocation()
findLocationButton.hidden = true
locationProcessIndicatorView.startAnimating()
}
/*
Function is called when location is found. Updated coordinates text fields and stops process indicator animation.
Also stops the process of finding new locations.
@methodtype Command
@pre Location was found
@post Coordinates has been printed
*/
func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!)
{
let location = locations.last as! CLLocation
projectLatitudeTextField.text = "\(location.coordinate.latitude)"
projectLongitudeTextField.text = "\(location.coordinate.longitude)"
locationManager.stopUpdatingLocation()
locationProcessIndicatorView.stopAnimating()
findLocationButton.hidden = false
}
/*
Called when project editing is done. Updates project in database.
@methodtype Command
@pre Valid user input
@post Project is updated
*/
@IBAction func updateProject(sender: AnyObject)
{
let updatedProject = Project(id: projectIDLabel.text!, name: projectNameTextField.text, finalDate: dateFormatter.dateFromString(projectFinalDateTextField.text), latitude: projectLatitudeTextField.text.toDouble(), longitude: projectLongitudeTextField.text.toDouble())
projectDAO.updateProject(updatedProject)
delegate.didEditProject()
dismissViewControllerAnimated(true, completion: {})
}
/*
iOS listener function. Called when pressing 'cancel'-button, dismisses current view.
@methodtype Command
@pre -
@post Dismisses current view
*/
@IBAction func cancel(sender: AnyObject)
{
self.dismissViewControllerAnimated(true, completion: {})
}
}
| agpl-3.0 | f928f91e7767b31f0ad997355f43ec4b | 30.493617 | 274 | 0.664099 | 5.602574 | false | false | false | false |
wenghengcong/Coderpursue | BeeFun/BeeFun/View/User/UserCell/BFUserTypeSecCell.swift | 1 | 2040 | //
// BFUserTypeSecCell.swift
// BeeFun
//
// Created by WengHengcong on 04/07/2017.
// Copyright © 2017 JungleSong. All rights reserved.
//
import UIKit
class BFUserTypeSecCell: BFBaseCell {
@IBOutlet weak var noLabel: UILabel!
@IBOutlet weak var avatarImgV: UIImageView!
@IBOutlet weak var nameLabel: UILabel!
var userNo: Int? {
didSet {
noLabel.text = "\(userNo!+1)"
self.setNeedsLayout()
}
}
var user: ObjUser? {
didSet {
if let avatarUrl = user?.avatar_url {
avatarImgV.kf.setImage(with: URL(string: avatarUrl))
}
if let name = user?.login {
nameLabel.text = name
}
}
}
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
tdc_customView()
}
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
func tdc_customView() {
avatarImgV.layer.cornerRadius = avatarImgV.width/2
avatarImgV.layer.masksToBounds = true
// noLabel.backgroundColor = UIColor.blueColor
}
override func layoutSubviews() {
// if(userNo < 3){
//
// noLabel.textColor = UIColor.bfRedColor
// nameLabel.textColor = UIColor.bfRedColor
//
// }else{
noLabel.textColor = UIColor.iOS11Black
nameLabel.textColor = UIColor.iOS11Black
// }
// noLabel.sizeToFit()
}
}
| mit | 6693b85cce967e70c44c90c1b50c06a4 | 22.988235 | 74 | 0.535557 | 4.854762 | false | false | false | false |
suzuki-0000/SKPhotoBrowser | SKPhotoBrowser/SKPhotoBrowserOptions.swift | 3 | 2805 | //
// SKPhotoBrowserOptions.swift
// SKPhotoBrowser
//
// Created by 鈴木 啓司 on 2016/08/18.
// Copyright © 2016年 suzuki_keishi. All rights reserved.
//
import UIKit
public struct SKPhotoBrowserOptions {
public static var displayStatusbar: Bool = false
public static var displayCloseButton: Bool = true
public static var displayDeleteButton: Bool = false
public static var displayAction: Bool = true
public static var shareExtraCaption: String?
public static var actionButtonTitles: [String]?
public static var displayCounterLabel: Bool = true
public static var displayBackAndForwardButton: Bool = true
public static var displayHorizontalScrollIndicator: Bool = true
public static var displayVerticalScrollIndicator: Bool = true
public static var displayPagingHorizontalScrollIndicator: Bool = true
public static var bounceAnimation: Bool = false
public static var enableZoomBlackArea: Bool = true
public static var enableSingleTapDismiss: Bool = false
public static var backgroundColor: UIColor = .black
public static var indicatorColor: UIColor = .white
public static var indicatorStyle: UIActivityIndicatorView.Style = .whiteLarge
/// By default close button is on left side and delete button is on right.
///
/// Set this property to **true** for swap they.
///
/// Default: false
public static var swapCloseAndDeleteButtons: Bool = false
public static var disableVerticalSwipe: Bool = false
/// if this value is true, the long photo width will match the screen,
/// and the minScale is 1.0, the maxScale is 2.5
/// Default: false
public static var longPhotoWidthMatchScreen: Bool = false
/// Provide custom session configuration (eg. for headers, etc.)
public static var sessionConfiguration: URLSessionConfiguration = .default
}
public struct SKButtonOptions {
public static var closeButtonPadding: CGPoint = CGPoint(x: 5, y: 20)
public static var deleteButtonPadding: CGPoint = CGPoint(x: 5, y: 20)
}
public struct SKCaptionOptions {
public enum CaptionLocation {
case basic
case bottom
}
public static var textColor: UIColor = .white
public static var textAlignment: NSTextAlignment = .center
public static var numberOfLine: Int = 3
public static var lineBreakMode: NSLineBreakMode = .byTruncatingTail
public static var font: UIFont = .systemFont(ofSize: 17.0)
public static var backgroundColor: UIColor = .clear
public static var captionLocation: CaptionLocation = .basic
}
public struct SKToolbarOptions {
public static var textColor: UIColor = .white
public static var font: UIFont = .systemFont(ofSize: 17.0)
public static var textShadowColor: UIColor = .black
}
| mit | c5f361c9d603a6cdda1bfdf5f11200fd | 35.763158 | 81 | 0.730852 | 4.867596 | false | false | false | false |
kinetic-fit/sensors-swift | Sources/SwiftySensors/CyclingSpeedCadenceSerializer.swift | 1 | 3027 | //
// CyclingSpeedCadenceSerializer.swift
// SwiftySensors
//
// https://github.com/kinetic-fit/sensors-swift
//
// Copyright © 2017 Kinetic. All rights reserved.
//
import Foundation
/// :nodoc:
open class CyclingSpeedCadenceSerializer {
struct MeasurementFlags: OptionSet {
let rawValue: UInt8
static let WheelRevolutionDataPresent = MeasurementFlags(rawValue: 1 << 0)
static let CrankRevolutionDataPresent = MeasurementFlags(rawValue: 1 << 1)
}
public struct Features: OptionSet {
public let rawValue: UInt16
public static let WheelRevolutionDataSupported = Features(rawValue: 1 << 0)
public static let CrankRevolutionDataSupported = Features(rawValue: 1 << 1)
public static let MultipleSensorLocationsSupported = Features(rawValue: 1 << 2)
public init(rawValue: UInt16) {
self.rawValue = rawValue
}
}
public struct MeasurementData: CyclingMeasurementData, CustomDebugStringConvertible {
public var timestamp: Double = 0
public var cumulativeWheelRevolutions: UInt32?
public var lastWheelEventTime: UInt16?
public var cumulativeCrankRevolutions: UInt16?
public var lastCrankEventTime: UInt16?
public var debugDescription: String {
return "\(cumulativeWheelRevolutions ?? 0) \(lastWheelEventTime ?? 0) \(cumulativeCrankRevolutions ?? 0) \(lastCrankEventTime ?? 0)"
}
}
public static func readFeatures(_ data: Data) -> Features {
let bytes = data.map { $0 }
let rawFeatures: UInt16 = UInt16(bytes[0]) | UInt16(bytes[1]) << 8
return Features(rawValue: rawFeatures)
}
public static func readMeasurement(_ data: Data) -> MeasurementData {
var measurement = MeasurementData()
let bytes = data.map { $0 }
var index: Int = 0
let rawFlags: UInt8 = bytes[index++=]
let flags = MeasurementFlags(rawValue: rawFlags)
if flags.contains(.WheelRevolutionDataPresent) {
var cumulativeWheelRevolutions = UInt32(bytes[index++=])
cumulativeWheelRevolutions |= UInt32(bytes[index++=]) << 8
cumulativeWheelRevolutions |= UInt32(bytes[index++=]) << 16
cumulativeWheelRevolutions |= UInt32(bytes[index++=]) << 24
measurement.cumulativeWheelRevolutions = cumulativeWheelRevolutions
measurement.lastWheelEventTime = UInt16(bytes[index++=]) | UInt16(bytes[index++=]) << 8
}
if flags.contains(.CrankRevolutionDataPresent) {
measurement.cumulativeCrankRevolutions = UInt16(bytes[index++=]) | UInt16(bytes[index++=]) << 8
measurement.lastCrankEventTime = UInt16(bytes[index++=]) | UInt16(bytes[index++=]) << 8
}
measurement.timestamp = Date.timeIntervalSinceReferenceDate
return measurement
}
}
| mit | 74dcee1e4fcba3664e3c306075ddf14e | 36.358025 | 147 | 0.631527 | 4.662558 | false | false | false | false |
younata/RSSClient | TethysKitSpecs/Helpers/SharedBehavior.swift | 1 | 6650 | import Quick
import Nimble
import CBGPromise
import TethysKit
import FutureHTTP
func itCachesInProgressFutures<T>(factory: @escaping () -> Future<Result<T, TethysError>>,
callChecker: @escaping (Int) -> Void,
resolver: @escaping (TethysError?) -> Result<T, TethysError>,
equator: @escaping (Result<T, TethysError>, Result<T, TethysError>) -> Void) {
var future: Future<Result<T, TethysError>>!
beforeEach {
future = factory()
}
it("returns an in-progress future") {
expect(future).toNot(beResolved())
}
it("makes a call to the underlying service") {
callChecker(1)
}
it("does not make another call to the underlying service if called before that future resolves") {
_ = factory()
callChecker(1)
}
describe("on success") {
var expectedValue: Result<T, TethysError>!
beforeEach {
expectedValue = resolver(nil)
}
it("resolves the future with the error") {
expect(future.value).toNot(beNil())
guard let received = future.value else { return }
equator(received, expectedValue)
}
describe("if called again") {
beforeEach {
future = factory()
}
it("returns an in-progress future") {
expect(future).toNot(beResolved())
}
it("makes another call to the underlying service") {
callChecker(2)
}
}
}
describe("on error") {
var expectedValue: Result<T, TethysError>!
beforeEach {
expectedValue = resolver(TethysError.unknown)
}
it("resolves the future with the error") {
expect(future.value?.error).to(equal(expectedValue.error))
}
describe("if called again") {
beforeEach {
future = factory()
}
it("returns an in-progress future") {
expect(future).toNot(beResolved())
}
it("makes another call to the underlying service") {
callChecker(2)
}
}
}
}
func itBehavesLikeTheRequestFailed<T>(url: URL, shouldParseData: Bool = true, file: String = #file, line: UInt = #line,
httpClient: @escaping () -> FakeHTTPClient,
future: @escaping () -> Future<Result<T, TethysError>>) {
if T.self != Void.self && shouldParseData {
describe("when the request succeeds") {
context("and the data is not valid") {
beforeEach {
guard httpClient().requestPromises.last?.future.value == nil else {
fail("most recent promise was already resolved", file: file, line: line)
return
}
httpClient().requestPromises.last?.resolve(.success(HTTPResponse(
body: "[\"bad\": \"data\"]".data(using: .utf8)!,
status: .ok,
mimeType: "Application/JSON",
headers: [:]
)))
}
it("resolves the future with a bad response error") {
expect(future().value, file: file, line: line).toNot(beNil(), description: "Expected future to be resolved")
expect(future().value?.error, file: file, line: line).to(equal(
TethysError.network(url, .badResponse("[\"bad\": \"data\"]".data(using: .utf8)!))
))
}
}
}
}
describe("when the request fails") {
context("when the request fails with a 400 level error") {
beforeEach {
guard httpClient().requestPromises.last?.future.value == nil else {
fail("most recent promise was already resolved", file: file, line: line)
return
}
httpClient().requestPromises.last?.resolve(.success(HTTPResponse(
body: "403".data(using: .utf8)!,
status: HTTPStatus.init(rawValue: 403)!,
mimeType: "Application/JSON",
headers: [:]
)))
}
it("resolves the future with the error") {
expect(future().value, file: file, line: line).toNot(beNil(), description: "Expected future to be resolved")
expect(future().value?.error, file: file, line: line).to(equal(
TethysError.network(url, .http(.forbidden, "403".data(using: .utf8)!))
))
}
}
context("when the request fails with a 500 level error") {
beforeEach {
guard httpClient().requestPromises.last?.future.value == nil else {
fail("most recent promise was already resolved", file: file, line: line)
return
}
httpClient().requestPromises.last?.resolve(.success(HTTPResponse(
body: "502".data(using: .utf8)!,
status: HTTPStatus.init(rawValue: 502)!,
mimeType: "Application/JSON",
headers: [:]
)))
}
it("resolves the future with the error") {
expect(future().value, file: file, line: line).toNot(beNil(), description: "Expected future to be resolved")
expect(future().value?.error, file: file, line: line).to(equal(
TethysError.network(url, .http(.badGateway, "502".data(using: .utf8)!))
))
}
}
context("when the request fails with an error") {
beforeEach {
guard httpClient().requestPromises.last?.future.value == nil else {
fail("most recent promise was already resolved", file: file, line: line)
return
}
httpClient().requestPromises.last?.resolve(.failure(HTTPClientError.network(.timedOut)))
}
it("resolves the future with an error") {
expect(future().value, file: file, line: line).toNot(beNil(), description: "Expected future to be resolved")
expect(future().value?.error, file: file, line: line).to(equal(
TethysError.network(url, .timedOut)
))
}
}
}
}
| mit | 1a88de495d58f648a2a6b6fe5a8387cb | 37 | 128 | 0.506466 | 5.095785 | false | false | false | false |
iMetalk/TCZKit | TCZKitDemo/TCZKit/Extension/String/String+TCZ.swift | 1 | 11453 | //
// String+TCZ.swift
// Dormouse
//
// Created by tczy on 2017/8/11.
// Copyright © 2017年 WangSuyan. All rights reserved.
//
import UIKit
import Foundation
extension String {
/// 字符长度
public var length: Int {
return self.characters.count
}
/// 检查是否空白
public var isBlank: Bool {
let trimmed = trimmingCharacters(in: .whitespacesAndNewlines)
return trimmed.isEmpty
}
///去空格换行
public mutating func trim() {
self = self.trimmed()
}
/// string字数
public var countofWords: Int {
let regex = try? NSRegularExpression(pattern: "\\w+", options: NSRegularExpression.Options())
return regex?.numberOfMatches(in: self, options: NSRegularExpression.MatchingOptions(), range: NSRange(location: 0, length: self.length)) ?? 0
}
/// 去空格换行 返回新的字符串
public func trimmed() -> String {
return self.trimmingCharacters(in: .whitespacesAndNewlines)
}
/// json 字符转字典
public func toDictionary() -> [String:AnyObject]? {
if let data = self.data(using: String.Encoding.utf8) {
do {
return try JSONSerialization.jsonObject(with: data, options: [JSONSerialization.ReadingOptions.init(rawValue: 0)]) as? [String:AnyObject]
} catch let error as NSError {
print(error)
}
}
return nil
}
/// String to Int
public func toInt() -> Int? {
if let num = NumberFormatter().number(from: self) {
return num.intValue
} else {
return nil
}
}
/// String to Double
public func toDouble() -> Double? {
if let num = NumberFormatter().number(from: self) {
return num.doubleValue
} else {
return nil
}
}
/// String to Float
public func toFloat() -> Float? {
if let num = NumberFormatter().number(from: self) {
return num.floatValue
} else {
return nil
}
}
/// String to Bool
public func toBool() -> Bool? {
let trimmedString = trimmed().lowercased()
if trimmedString == "true" || trimmedString == "false" {
return (trimmedString as NSString).boolValue
}
return nil
}
/// String to NSString
public var toNSString: NSString { return self as NSString }
///字符串高度
public func height(_ width: CGFloat, font: UIFont, lineBreakMode: NSLineBreakMode?) -> CGFloat {
var attrib: [String: AnyObject] = [NSFontAttributeName: font]
if lineBreakMode != nil {
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineBreakMode = lineBreakMode!
attrib.updateValue(paragraphStyle, forKey: NSParagraphStyleAttributeName)
}
let size = CGSize(width: width, height: CGFloat(Double.greatestFiniteMagnitude))
return ceil((self as NSString).boundingRect(with: size, options: NSStringDrawingOptions.usesLineFragmentOrigin, attributes:attrib, context: nil).height)
}
// /// MD5
// ///
// /// - Returns: MD5
// func md5() -> String {
// let str = self.cString(using: String.Encoding.utf8)
// let strLen = CUnsignedInt(self.lengthOfBytes(using: String.Encoding.utf8))
// let digestLen = Int(CC_MD5_DIGEST_LENGTH)
// let result = UnsafeMutablePointer<CUnsignedChar>.allocate(capacity: digestLen)
//
// CC_MD5(str!, strLen, result)
// let hash = NSMutableString()
// for i in 0 ..< digestLen {
// hash.appendFormat("%02x", result[i])
// }
//
// result.deallocate(capacity: digestLen)
//
// return String(format: hash as String)
// }
/// 是否为正确的是手机号
///
/// - Parameter phone: 手机号
/// - Returns: 是否正确
static func isValidPhone (phone:String)->(Bool){
let str = "^[1-9][0-9]{4,11}$"
let mobilePredicate = NSPredicate(format: "SELF MATCHES %@",str)
return mobilePredicate.evaluate(with: phone)
}
/// 千分符 1,000格式
///
/// - Parameter str: 数字
/// - Returns: 1,000
static func calcuteSymbolLocation(str: String) -> String {
var resultStr = str
let symbolStr = "."
let subRange = (resultStr as NSString).range(of: symbolStr)
if subRange.location == 4 || subRange.location == 5 {
resultStr.insert(",", at: str.index(resultStr.startIndex, offsetBy: 1))
}
return resultStr
}
/// 清除字符串小数点末尾的0
func cleanDecimalPointZear() -> String {
let newStr = self as NSString
var s = NSString()
var offset = newStr.length - 1
while offset > 0 {
s = newStr.substring(with: NSMakeRange(offset, 1)) as NSString
if s.isEqual(to: "0") || s.isEqual(to: ".") {
offset -= 1
} else {
break
}
}
return newStr.substring(to: offset + 1)
}
/// 判断是否为合法的身份证号
///
/// - Parameter sfz: 身份证
/// - Returns: 是否合法
static func isValidateIDCardNumber(sfz:String)->(Bool){
let value = sfz.trimmingCharacters(in: NSCharacterSet.whitespacesAndNewlines)
var length = 0
if value == "" {
return false
}else{
length = value.characters.count
if length != 15 && length != 18 {
return false
}
}
//省份代码
let arearsArray = ["11","12", "13", "14", "15", "21", "22", "23", "31", "32", "33", "34", "35", "36", "37", "41", "42", "43", "44", "45", "46", "50", "51", "52", "53", "54", "61", "62", "63", "64", "65", "71", "81", "82", "91"]
let valueStart2 = (value as NSString).substring(to: 2)
var arareFlag = false
if arearsArray.contains(valueStart2) {
arareFlag = true
}
if !arareFlag{
return false
}
var regularExpression = NSRegularExpression()
var numberofMatch = Int()
var year = 0
switch (length) {
case 15:
year = Int((value as NSString).substring(with: NSRange(location:6,length:2)))!
if year%4 == 0 || (year%100 == 0 && year%4 == 0){
do{
regularExpression = try NSRegularExpression.init(pattern: "^[1-9][0-9]{5}[0-9]{2}((01|03|05|07|08|10|12)(0[1-9]|[1-2][0-9]|3[0-1])|(04|06|09|11)(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|[1-2][0-9]))[0-9]{3}$", options: .caseInsensitive) //检测出生日期的合法性
}catch{
}
}else{
do{
regularExpression = try NSRegularExpression.init(pattern: "^[1-9][0-9]{5}[0-9]{2}((01|03|05|07|08|10|12)(0[1-9]|[1-2][0-9]|3[0-1])|(04|06|09|11)(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|1[0-9]|2[0-8]))[0-9]{3}$", options: .caseInsensitive) //检测出生日期的合法性
}catch{}
}
numberofMatch = regularExpression.numberOfMatches(in: value, options:NSRegularExpression.MatchingOptions.reportProgress, range: NSMakeRange(0, value.characters.count))
if(numberofMatch > 0) {
return true
}else {
return false
}
case 18:
year = Int((value as NSString).substring(with: NSRange(location:6,length:4)))!
if year%4 == 0 || (year%100 == 0 && year%4 == 0){
do{
regularExpression = try NSRegularExpression.init(pattern: "^[1-9][0-9]{5}19[0-9]{2}((01|03|05|07|08|10|12)(0[1-9]|[1-2][0-9]|3[0-1])|(04|06|09|11)(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|[1-2][0-9]))[0-9]{3}[0-9Xx]$", options: .caseInsensitive) //检测出生日期的合法性
}catch{
}
}else{
do{
regularExpression = try NSRegularExpression.init(pattern: "^[1-9][0-9]{5}19[0-9]{2}((01|03|05|07|08|10|12)(0[1-9]|[1-2][0-9]|3[0-1])|(04|06|09|11)(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|1[0-9]|2[0-8]))[0-9]{3}[0-9Xx]$", options: .caseInsensitive) //检测出生日期的合法性
}catch{}
}
numberofMatch = regularExpression.numberOfMatches(in: value, options:NSRegularExpression.MatchingOptions.reportProgress, range: NSMakeRange(0, value.characters.count))
if(numberofMatch > 0) {
let s =
(Int((value as NSString).substring(with: NSRange(location:0,length:1)))! +
Int((value as NSString).substring(with: NSRange(location:10,length:1)))!) * 7 +
(Int((value as NSString).substring(with: NSRange(location:1,length:1)))! +
Int((value as NSString).substring(with: NSRange(location:11,length:1)))!) * 9 +
(Int((value as NSString).substring(with: NSRange(location:2,length:1)))! +
Int((value as NSString).substring(with: NSRange(location:12,length:1)))!) * 10 +
(Int((value as NSString).substring(with: NSRange(location:3,length:1)))! +
Int((value as NSString).substring(with: NSRange(location:13,length:1)))!) * 5 +
(Int((value as NSString).substring(with: NSRange(location:4,length:1)))! +
Int((value as NSString).substring(with: NSRange(location:14,length:1)))!) * 8 +
(Int((value as NSString).substring(with: NSRange(location:5,length:1)))! +
Int((value as NSString).substring(with: NSRange(location:15,length:1)))!) * 4 +
(Int((value as NSString).substring(with: NSRange(location:6,length:1)))! +
Int((value as NSString).substring(with: NSRange(location:16,length:1)))!) * 2 +
Int((value as NSString).substring(with: NSRange(location:7,length:1)))! * 1 +
Int((value as NSString).substring(with: NSRange(location:8,length:1)))! * 6 +
Int((value as NSString).substring(with: NSRange(location:9,length:1)))! * 3
let Y = s%11
var M = "F"
let JYM = "10X98765432"
M = (JYM as NSString).substring(with: NSRange(location:Y,length:1))
if M == (value as NSString).substring(with: NSRange(location:17,length:1))
{
return true
}else{return false}
}else {
return false
}
default:
return false
}
}
}
| mit | 369a5bf6a98c09ecc41f041dcca26985 | 36.116279 | 273 | 0.509398 | 4.084826 | false | false | false | false |
omondigeno/ActionablePushMessages | Pods/MK/Sources/CaptureView.swift | 1 | 15418 | /*
* Copyright (C) 2015 - 2016, Daniel Dahan and CosmicMind, Inc. <http://cosmicmind.io>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* * Neither the name of MaterialKit nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import UIKit
import AVFoundation
public enum CaptureMode {
case Photo
case Video
}
@objc(CaptureViewDelegate)
public protocol CaptureViewDelegate : MaterialDelegate {
/**
:name: captureViewDidStartRecordTimer
*/
optional func captureViewDidStartRecordTimer(captureView: CaptureView)
/**
:name: captureViewDidUpdateRecordTimer
*/
optional func captureViewDidUpdateRecordTimer(captureView: CaptureView, hours: Int, minutes: Int, seconds: Int)
/**
:name: captureViewDidStopRecordTimer
*/
optional func captureViewDidStopRecordTimer(captureView: CaptureView, hours: Int, minutes: Int, seconds: Int)
/**
:name: captureViewDidTapToFocusAtPoint
*/
optional func captureViewDidTapToFocusAtPoint(captureView: CaptureView, point: CGPoint)
/**
:name: captureViewDidTapToExposeAtPoint
*/
optional func captureViewDidTapToExposeAtPoint(captureView: CaptureView, point: CGPoint)
/**
:name: captureViewDidTapToResetAtPoint
*/
optional func captureViewDidTapToResetAtPoint(captureView: CaptureView, point: CGPoint)
/**
:name: captureViewDidPressFlashButton
*/
optional func captureViewDidPressFlashButton(captureView: CaptureView, button: UIButton)
/**
:name: captureViewDidPressSwitchCamerasButton
*/
optional func captureViewDidPressSwitchCamerasButton(captureView: CaptureView, button: UIButton)
/**
:name: captureViewDidPressCaptureButton
*/
optional func captureViewDidPressCaptureButton(captureView: CaptureView, button: UIButton)
/**
:name: captureViewDidPressCameraButton
*/
optional func captureViewDidPressCameraButton(captureView: CaptureView, button: UIButton)
/**
:name: captureViewDidPressVideoButton
*/
optional func captureViewDidPressVideoButton(captureView: CaptureView, button: UIButton)
}
public class CaptureView : MaterialView, UIGestureRecognizerDelegate {
/**
:name: timer
*/
private var timer: NSTimer?
/**
:name: tapToFocusGesture
*/
private var tapToFocusGesture: UITapGestureRecognizer?
/**
:name: tapToExposeGesture
*/
private var tapToExposeGesture: UITapGestureRecognizer?
/**
:name: tapToResetGesture
*/
private var tapToResetGesture: UITapGestureRecognizer?
/**
:name: captureMode
*/
public lazy var captureMode: CaptureMode = .Video
/**
:name: tapToFocusEnabled
*/
public var tapToFocusEnabled: Bool = false {
didSet {
if tapToFocusEnabled {
tapToResetEnabled = true
prepareFocusLayer()
prepareTapGesture(&tapToFocusGesture, numberOfTapsRequired: 1, numberOfTouchesRequired: 1, selector: "handleTapToFocusGesture:")
if let v: UITapGestureRecognizer = tapToExposeGesture {
tapToFocusGesture!.requireGestureRecognizerToFail(v)
}
} else {
removeTapGesture(&tapToFocusGesture)
focusLayer?.removeFromSuperlayer()
focusLayer = nil
}
}
}
/**
:name: tapToExposeEnabled
*/
public var tapToExposeEnabled: Bool = false {
didSet {
if tapToExposeEnabled {
tapToResetEnabled = true
prepareExposureLayer()
prepareTapGesture(&tapToExposeGesture, numberOfTapsRequired: 2, numberOfTouchesRequired: 1, selector: "handleTapToExposeGesture:")
if let v: UITapGestureRecognizer = tapToFocusGesture {
v.requireGestureRecognizerToFail(tapToExposeGesture!)
}
} else {
removeTapGesture(&tapToExposeGesture)
exposureLayer?.removeFromSuperlayer()
exposureLayer = nil
}
}
}
/**
:name: tapToResetEnabled
*/
public var tapToResetEnabled: Bool = false {
didSet {
if tapToResetEnabled {
prepareResetLayer()
prepareTapGesture(&tapToResetGesture, numberOfTapsRequired: 2, numberOfTouchesRequired: 2, selector: "handleTapToResetGesture:")
if let v: UITapGestureRecognizer = tapToFocusGesture {
v.requireGestureRecognizerToFail(tapToResetGesture!)
}
if let v: UITapGestureRecognizer = tapToExposeGesture {
v.requireGestureRecognizerToFail(tapToResetGesture!)
}
} else {
removeTapGesture(&tapToResetGesture)
resetLayer?.removeFromSuperlayer()
resetLayer = nil
}
}
}
/**
:name: contentInsets
*/
public var contentInsetPreset: MaterialEdgeInsetPreset = .None {
didSet {
contentInset = MaterialEdgeInsetPresetToValue(contentInsetPreset)
}
}
/**
:name: contentInset
*/
public var contentInset: UIEdgeInsets = MaterialEdgeInsetPresetToValue(.Square4) {
didSet {
reloadView()
}
}
/**
:name: previewView
*/
public private(set) lazy var previewView: CapturePreviewView = CapturePreviewView()
/**
:name: capture
*/
public private(set) lazy var captureSession: CaptureSession = CaptureSession()
/**
:name: focusLayer
*/
public private(set) var focusLayer: MaterialLayer?
/**
:name: exposureLayer
*/
public private(set) var exposureLayer: MaterialLayer?
/**
:name: resetLayer
*/
public private(set) var resetLayer: MaterialLayer?
/**
:name: cameraButton
*/
public var cameraButton: UIButton? {
didSet {
if let v: UIButton = cameraButton {
v.addTarget(self, action: "handleCameraButton:", forControlEvents: .TouchUpInside)
}
reloadView()
}
}
/**
:name: captureButton
*/
public var captureButton: UIButton? {
didSet {
if let v: UIButton = captureButton {
v.addTarget(self, action: "handleCaptureButton:", forControlEvents: .TouchUpInside)
}
reloadView()
}
}
/**
:name: videoButton
*/
public var videoButton: UIButton? {
didSet {
if let v: UIButton = videoButton {
v.addTarget(self, action: "handleVideoButton:", forControlEvents: .TouchUpInside)
}
reloadView()
}
}
/**
:name: switchCamerasButton
*/
public var switchCamerasButton: UIButton? {
didSet {
if let v: UIButton = switchCamerasButton {
v.addTarget(self, action: "handleSwitchCamerasButton:", forControlEvents: .TouchUpInside)
}
}
}
/**
:name: flashButton
*/
public var flashButton: UIButton? {
didSet {
if let v: UIButton = flashButton {
v.addTarget(self, action: "handleFlashButton:", forControlEvents: .TouchUpInside)
}
}
}
/**
:name: init
*/
public convenience init() {
self.init(frame: CGRectNull)
}
/**
:name: layoutSubviews
*/
public override func layoutSubviews() {
super.layoutSubviews()
previewView.frame = bounds
if let v: UIButton = cameraButton {
v.frame.origin.y = bounds.height - contentInset.bottom - v.bounds.height
v.frame.origin.x = contentInset.left
}
if let v: UIButton = captureButton {
v.frame.origin.y = bounds.height - contentInset.bottom - v.bounds.height
v.frame.origin.x = (bounds.width - v.bounds.width) / 2
}
if let v: UIButton = videoButton {
v.frame.origin.y = bounds.height - contentInset.bottom - v.bounds.height
v.frame.origin.x = bounds.width - v.bounds.width - contentInset.right
}
if let v: AVCaptureConnection = (previewView.layer as! AVCaptureVideoPreviewLayer).connection {
v.videoOrientation = captureSession.currentVideoOrientation
}
}
/**
:name: prepareView
*/
public override func prepareView() {
super.prepareView()
backgroundColor = MaterialColor.black
preparePreviewView()
}
/**
:name: reloadView
*/
public func reloadView() {
// clear constraints so new ones do not conflict
removeConstraints(constraints)
for v in subviews {
v.removeFromSuperview()
}
insertSubview(previewView, atIndex: 0)
if let v: UIButton = captureButton {
insertSubview(v, atIndex: 1)
}
if let v: UIButton = cameraButton {
insertSubview(v, atIndex: 2)
}
if let v: UIButton = videoButton {
insertSubview(v, atIndex: 3)
}
}
/**
:name: startTimer
*/
internal func startTimer() {
timer?.invalidate()
timer = NSTimer(timeInterval: 0.5, target: self, selector: "updateTimer", userInfo: nil, repeats: true)
NSRunLoop.mainRunLoop().addTimer(timer!, forMode: NSRunLoopCommonModes)
(delegate as? CaptureViewDelegate)?.captureViewDidStartRecordTimer?(self)
}
/**
:name: updateTimer
*/
internal func updateTimer() {
let duration: CMTime = captureSession.recordedDuration
let time: Double = CMTimeGetSeconds(duration)
let hours: Int = Int(time / 3600)
let minutes: Int = Int((time / 60) % 60)
let seconds: Int = Int(time % 60)
(delegate as? CaptureViewDelegate)?.captureViewDidUpdateRecordTimer?(self, hours: hours, minutes: minutes, seconds: seconds)
}
/**
:name: stopTimer
*/
internal func stopTimer() {
let duration: CMTime = captureSession.recordedDuration
let time: Double = CMTimeGetSeconds(duration)
let hours: Int = Int(time / 3600)
let minutes: Int = Int((time / 60) % 60)
let seconds: Int = Int(time % 60)
timer?.invalidate()
timer = nil
(delegate as? CaptureViewDelegate)?.captureViewDidStopRecordTimer?(self, hours: hours, minutes: minutes, seconds: seconds)
}
/**
:name: handleFlashButton
*/
internal func handleFlashButton(button: UIButton) {
(delegate as? CaptureViewDelegate)?.captureViewDidPressFlashButton?(self, button: button)
}
/**
:name: handleSwitchCamerasButton
*/
internal func handleSwitchCamerasButton(button: UIButton) {
captureSession.switchCameras()
(delegate as? CaptureViewDelegate)?.captureViewDidPressSwitchCamerasButton?(self, button: button)
}
/**
:name: handleCaptureButton
*/
internal func handleCaptureButton(button: UIButton) {
if .Photo == captureMode {
captureSession.captureStillImage()
} else if .Video == captureMode {
if captureSession.isRecording {
captureSession.stopRecording()
stopTimer()
} else {
captureSession.startRecording()
startTimer()
}
}
(delegate as? CaptureViewDelegate)?.captureViewDidPressCaptureButton?(self, button: button)
}
/**
:name: handleCameraButton
*/
internal func handleCameraButton(button: UIButton) {
captureMode = .Photo
(delegate as? CaptureViewDelegate)?.captureViewDidPressCameraButton?(self, button: button)
}
/**
:name: handleVideoButton
*/
internal func handleVideoButton(button: UIButton) {
captureMode = .Video
(delegate as? CaptureViewDelegate)?.captureViewDidPressVideoButton?(self, button: button)
}
/**
:name: handleTapToFocusGesture
*/
internal func handleTapToFocusGesture(recognizer: UITapGestureRecognizer) {
if tapToFocusEnabled && captureSession.cameraSupportsTapToFocus {
let point: CGPoint = recognizer.locationInView(self)
captureSession.focusAtPoint(previewView.captureDevicePointOfInterestForPoint(point))
animateTapLayer(layer: focusLayer!, point: point)
(delegate as? CaptureViewDelegate)?.captureViewDidTapToFocusAtPoint?(self, point: point)
}
}
/**
:name: handleTapToExposeGesture
*/
internal func handleTapToExposeGesture(recognizer: UITapGestureRecognizer) {
if tapToExposeEnabled && captureSession.cameraSupportsTapToExpose {
let point: CGPoint = recognizer.locationInView(self)
captureSession.exposeAtPoint(previewView.captureDevicePointOfInterestForPoint(point))
animateTapLayer(layer: exposureLayer!, point: point)
(delegate as? CaptureViewDelegate)?.captureViewDidTapToExposeAtPoint?(self, point: point)
}
}
/**
:name: handleTapToResetGesture
*/
internal func handleTapToResetGesture(recognizer: UITapGestureRecognizer) {
if tapToResetEnabled {
captureSession.resetFocusAndExposureModes()
let point: CGPoint = previewView.pointForCaptureDevicePointOfInterest(CGPointMake(0.5, 0.5))
animateTapLayer(layer: resetLayer!, point: point)
(delegate as? CaptureViewDelegate)?.captureViewDidTapToResetAtPoint?(self, point: point)
}
}
/**
:name: prepareTapGesture
*/
private func prepareTapGesture(inout gesture: UITapGestureRecognizer?, numberOfTapsRequired: Int, numberOfTouchesRequired: Int, selector: Selector) {
removeTapGesture(&gesture)
gesture = UITapGestureRecognizer(target: self, action: selector)
gesture!.delegate = self
gesture!.numberOfTapsRequired = numberOfTapsRequired
gesture!.numberOfTouchesRequired = numberOfTouchesRequired
addGestureRecognizer(gesture!)
}
/**
:name: removeTapToFocusGesture
*/
private func removeTapGesture(inout gesture: UITapGestureRecognizer?) {
if let v: UIGestureRecognizer = gesture {
removeGestureRecognizer(v)
gesture = nil
}
}
/**
:name: preparePreviewView
*/
private func preparePreviewView() {
(previewView.layer as! AVCaptureVideoPreviewLayer).session = captureSession.session
captureSession.startSession()
}
/**
:name: prepareFocusLayer
*/
private func prepareFocusLayer() {
if nil == focusLayer {
focusLayer = MaterialLayer(frame: CGRectMake(0, 0, 150, 150))
focusLayer!.hidden = true
focusLayer!.borderWidth = 2
focusLayer!.borderColor = MaterialColor.white.CGColor
previewView.layer.addSublayer(focusLayer!)
}
}
/**
:name: prepareExposureLayer
*/
private func prepareExposureLayer() {
if nil == exposureLayer {
exposureLayer = MaterialLayer(frame: CGRectMake(0, 0, 150, 150))
exposureLayer!.hidden = true
exposureLayer!.borderWidth = 2
exposureLayer!.borderColor = MaterialColor.yellow.darken1.CGColor
previewView.layer.addSublayer(exposureLayer!)
}
}
/**
:name: prepareResetLayer
*/
private func prepareResetLayer() {
if nil == resetLayer {
resetLayer = MaterialLayer(frame: CGRectMake(0, 0, 150, 150))
resetLayer!.hidden = true
resetLayer!.borderWidth = 2
resetLayer!.borderColor = MaterialColor.red.accent1.CGColor
previewView.layer.addSublayer(resetLayer!)
}
}
/**
:name: animateTapLayer
*/
private func animateTapLayer(layer v: MaterialLayer, point: CGPoint) {
MaterialAnimation.animationDisabled {
v.transform = CATransform3DIdentity
v.position = point
v.hidden = false
}
MaterialAnimation.animateWithDuration(0.25, animations: {
v.transform = CATransform3DMakeScale(0.5, 0.5, 1)
}) {
MaterialAnimation.delay(0.4) {
MaterialAnimation.animationDisabled {
v.hidden = true
}
}
}
}
} | apache-2.0 | 2adf9da8691136013871b0cc13cce3c1 | 26.484848 | 150 | 0.738747 | 3.765079 | false | false | false | false |
prangbi/PrBasicREST | iOS/PrBasicRest/PrBasicRest/Network/HttpRequest.swift | 1 | 6845 | //
// HttpRequest.swift
// PrBasicRest
//
// Created by 구홍석 on 2017. 2. 8..
// Copyright © 2017년 Prangbi. All rights reserved.
//
import Foundation
class HttpRequest: NSObject {
// MARK: - Deifinition
enum API {
case get_ARTICLE
case get_ARTICLES
case post_ARTICLE
case put_ARTICLE
case delete_ARTICLE
}
static let API_URL_ARTICLE = API_URL + "/articles"
// MARK: - GET
func getArticle(id: Int, success: ((API, Any?) -> Void)?, failure: ((Error?) -> Void)?) {
let url = URL(string: HttpRequest.API_URL_ARTICLE + "/\(id)")
var request = URLRequest(url: url!)
request.httpMethod = "GET"
request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
URLSession.shared.dataTask(
with: request,
completionHandler: { (data, response, error) in
let httpResponse = response as? HTTPURLResponse
if nil == error && nil != httpResponse &&
(200 <= httpResponse!.statusCode && 299 >= httpResponse!.statusCode) {
var article: Article?
if let jsonDic = Util.dictionaryWithData(data, rootKey: "article") {
article = Article()
article?.dictionary = jsonDic
}
DispatchQueue.main.async(execute: {
success?(.get_ARTICLE, article)
})
} else {
DispatchQueue.main.async(execute: {
failure?(error)
})
}
}).resume()
}
func getArticles(success: ((API, Any?) -> Void)?, failure: ((Error?) -> Void)?) {
let url = URL(string: HttpRequest.API_URL_ARTICLE)
var request = URLRequest(url: url!)
request.httpMethod = "GET"
request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
URLSession.shared.dataTask(
with: request,
completionHandler: { (data, response, error) in
let httpResponse = response as? HTTPURLResponse
if nil == error && nil != httpResponse &&
(200 <= httpResponse!.statusCode && 299 >= httpResponse!.statusCode) {
var articles = Array<Article>()
if let jsonDics = Util.dictionaryArrayWithData(data, rootKey: "articles") {
for jsonDic in jsonDics {
var article = Article()
article.dictionary = jsonDic
articles.append(article)
}
}
DispatchQueue.main.async(execute: {
success?(.get_ARTICLES, articles)
})
} else {
DispatchQueue.main.async(execute: {
failure?(error)
})
}
}).resume()
}
// MARK: - POST
func postArticle(content: String,
success: ((API, Any?) -> Void)?, failure: ((Error?) -> Void)?) {
let url = URL(string: HttpRequest.API_URL_ARTICLE)
var params = Dictionary<String, Any>()
params["article"] = ["content": content]
var request = URLRequest(url: url!)
request.httpMethod = "POST"
request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
do {
try request.httpBody = JSONSerialization.data(withJSONObject: params, options: .prettyPrinted)
} catch {
print(error)
}
URLSession.shared.dataTask(
with: request,
completionHandler: { (data, response, error) in
let httpResponse = response as? HTTPURLResponse
if nil == error && nil != httpResponse &&
(200 <= httpResponse!.statusCode && 299 >= httpResponse!.statusCode) {
DispatchQueue.main.async(execute: {
success?(.post_ARTICLE, nil)
})
} else {
DispatchQueue.main.async(execute: {
failure?(error)
})
}
}).resume()
}
// MARK: - PUT
func putArticle(articleDict: Dictionary<String, Any>,
success: ((API, Any?) -> Void)?, failure: ((Error?) -> Void)?) {
let url = URL(string: HttpRequest.API_URL_ARTICLE)
var params = Dictionary<String, Any>()
params["article"] = articleDict
var request = URLRequest(url: url!)
request.httpMethod = "PUT"
request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
do {
try request.httpBody = JSONSerialization.data(withJSONObject: params, options: .prettyPrinted)
} catch {
print(error)
}
URLSession.shared.dataTask(
with: request,
completionHandler: { (data, response, error) in
let httpResponse = response as? HTTPURLResponse
if nil == error && nil != httpResponse &&
(200 <= httpResponse!.statusCode && 299 >= httpResponse!.statusCode) {
DispatchQueue.main.async(execute: {
success?(.put_ARTICLE, nil)
})
} else {
DispatchQueue.main.async(execute: {
failure?(error)
})
}
}).resume()
}
// MARK: - DELETE
func deleteArticle(id: Int, success: ((API, Any?) -> Void)?, failure: ((Error?) -> Void)?) {
let url = URL(string: HttpRequest.API_URL_ARTICLE + "/\(id)")
var request = URLRequest(url: url!)
request.httpMethod = "DELETE"
request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
URLSession.shared.dataTask(
with: request,
completionHandler: { (data, response, error) in
let httpResponse = response as? HTTPURLResponse
if nil == error && nil != httpResponse &&
(200 <= httpResponse!.statusCode && 299 >= httpResponse!.statusCode) {
DispatchQueue.main.async(execute: {
success?(.delete_ARTICLE, nil)
})
} else {
DispatchQueue.main.async(execute: {
failure?(error)
})
}
}).resume()
}
}
| unlicense | 45d16816b221ef078f1c4451be24393d | 38.062857 | 106 | 0.494441 | 5.155354 | false | false | false | false |
yanagiba/swift-lint | Tests/RuleTests/XCTestCase+RuleTests.swift | 2 | 1563 | /*
Copyright 2015-2017 Ryuichi Laboratories and the Yanagiba project contributors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import Foundation
@testable import AST
@testable import Parser
@testable import Source
@testable import Lint
extension String {
func inspect(withRule rule: Rule, configurations: [String: Any]? = nil) -> [Issue] {
let issueCollector = TestIssueCollector()
let testDriver = Driver()
testDriver.setReporter(issueCollector)
testDriver.registerRule(rule, ruleIdentifiers: [rule.identifier])
testDriver.updateOutputHandle(.nullDevice)
let lintResult = testDriver.lint(
sourceFiles: [SourceFile(path: "test/test", content: self)],
ruleConfigurations: configurations)
if lintResult == .failedInParsingFile {
fatalError("Failed in parsing file.")
}
return issueCollector.issues
}
}
fileprivate class TestIssueCollector : Reporter {
fileprivate var issues = [Issue]()
fileprivate func handle(issues: [Issue]) -> String {
self.issues = issues
return ""
}
}
| apache-2.0 | aa1acca25b67507d89a8fb47dcec3fa9 | 31.5625 | 86 | 0.733845 | 4.491379 | false | true | false | false |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.