repo_name
stringlengths 6
91
| ref
stringlengths 12
59
| path
stringlengths 7
936
| license
stringclasses 15
values | copies
stringlengths 1
3
| content
stringlengths 61
714k
| hash
stringlengths 32
32
| line_mean
float64 4.88
60.8
| line_max
int64 12
421
| alpha_frac
float64 0.1
0.92
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
hoffmanjon/SwiftyBones | refs/heads/master | Sources/SwiftyBonesAnalog.swift | mit | 1 | //
// SwiftyBonesAnalog.swift
//
// Created by Jon Hoffman on 5/1/16.
//
#if arch(arm) && os(Linux)
import Glibc
#else
import Darwin
#endif
/**
This is the list of analog pins that we can use
*/
var AnalogPins:[String: BBExpansionPin] = [
"AIN0": (header:.P9, pin:39),
"AIN1": (header:.P9, pin:40),
"AIN2": (header:.P9, pin:37),
"AIN3": (header:.P9, pin:38),
"AIN4": (header:.P9, pin:33),
"AIN5": (header:.P9, pin:36),
"AIN6": (header:.P9, pin:35)
]
/**
We would use the SBAnalog type to access the analog pins on the BeagleBone Black
*/
struct SBAnalog: GPIO {
/**
Variables and paths needed
*/
private static let ANALOG_BASE_PATH = "/sys/bus/iio/devices/iio:device0/"
private static let ANALOG_VALUE_FILE_START = "/in_voltage"
private static let ANALOG_VALUE_FILE_END = "_raw"
private static let SLOTS_PATH = "/sys/devices/platform/bone_capemgr/slots"
private static let ENABLE_ANALOG_IN_SLOTS = "BB-ADC"
private var header: BBExpansionHeader
private var pin: Int
private var id: String
/**
Failable initiator which will fail if an invalid ID is entered
- Parameter id: The ID of the pin. The ID starts with AIN and then contains a number 0 -> 7
*/
init?(id: String) {
if let val = AnalogPins[id] {
self.id = id
self.header = val.header
self.pin = val.pin
if !isPinActive() {
initPin()
}
} else {
return nil
}
}
/**
Failable initiator which will fail if either the header or pin number is invalid
- Parameter header: This is the header which will be either .P8 or .P9
- Parameter pin: the pin number
*/
init?(header: BBExpansionHeader, pin: Int) {
for (key, expansionPin) in AnalogPins where expansionPin.header == header && expansionPin.pin == pin {
self.header = header
self.pin = pin
self.id = key
if !isPinActive() {
if !initPin() {
return nil
}
}
return
}
return nil
}
/**
This method configures the pin for Analog IN
- Returns: true if the pin was successfully configured for analog in
*/
func initPin() -> Bool {
if !writeStringToFile(SBAnalog.ENABLE_ANALOG_IN_SLOTS, path: SBAnalog.SLOTS_PATH) {
return false
}
usleep(1000000)
return true
}
/**
This function checks to see if the pin is configured for Analog IN
- Returns: true if the pin is already configured otherwise false
*/
func isPinActive() -> Bool {
if let _ = readStringFromFile(getValuePath()) {
return true
} else {
return false
}
}
/**
Gets the present value from the pin
- Returns: returns the value for the pin
*/
func getValue() -> Int? {
if let value = readStringFromFile(getValuePath()), intValue = Int(value) {
return intValue
}
return nil
}
/**
Determines the path to the file for this particular analog pin
- Returns: Path to file
*/
private func getValuePath() -> String {
return SBAnalog.ANALOG_BASE_PATH + SBAnalog.ANALOG_VALUE_FILE_START + getPinNumber() + SBAnalog.ANALOG_VALUE_FILE_END
}
/**
Gets the Analog pin number (0 -> 6) from the ID
- Returns: the analog pin number (0 -> 6)
*/
private func getPinNumber() -> String {
let range = id.startIndex.advancedBy(3)..<id.endIndex.advancedBy(0)
return id[range]
}
}
| fb9a56cdc66d8cc99bd3eaecbe50473d | 26.639706 | 125 | 0.570897 | false | false | false | false |
joerocca/GitHawk | refs/heads/master | Classes/Issues/Managing/IssueManagingExpansionModel.swift | mit | 2 | //
// IssueManagingExpansionModel.swift
// Freetime
//
// Created by Ryan Nystrom on 11/13/17.
// Copyright © 2017 Ryan Nystrom. All rights reserved.
//
import Foundation
import IGListKit
final class IssueManagingExpansionModel: ListDiffable {
let expanded: Bool
init(expanded: Bool) {
self.expanded = expanded
}
// MARK: ListDiffable
func diffIdentifier() -> NSObjectProtocol {
return "managing-model" as NSObjectProtocol
}
func isEqual(toDiffableObject object: ListDiffable?) -> Bool {
if self === object { return true }
guard let object = object as? IssueManagingExpansionModel else { return false }
return expanded == object.expanded
}
}
| 1fc8a83acd77f1e4863c38be4feb0e9d | 21.6875 | 87 | 0.674931 | false | false | false | false |
tlax/GaussSquad | refs/heads/master | GaussSquad/View/CalculatorOptions/VCalculatorOptions.swift | mit | 1 | import UIKit
class VCalculatorOptions:VView, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout
{
private weak var controller:CCalculatorOptions!
private weak var collectionView:VCollection!
private weak var layoutBaseBottom:NSLayoutConstraint!
private let kBaseHeight:CGFloat = 280
private let kAnimationDuration:TimeInterval = 0.25
private let kCellHeight:CGFloat = 52
private let kHeaderHeight:CGFloat = 64
private let kCollectionBottom:CGFloat = 20
private let kInterItem:CGFloat = 1
override init(controller:CController)
{
super.init(controller:controller)
backgroundColor = UIColor.clear
self.controller = controller as? CCalculatorOptions
let blur:VBlur = VBlur.dark()
let closeButton:UIButton = UIButton()
closeButton.translatesAutoresizingMaskIntoConstraints = false
closeButton.addTarget(
self,
action:#selector(actionClose(sender:)),
for:UIControlEvents.touchUpInside)
let viewBase:UIView = UIView()
viewBase.backgroundColor = UIColor(white:0.95, alpha:1)
viewBase.translatesAutoresizingMaskIntoConstraints = false
let collectionView:VCollection = VCollection()
collectionView.alwaysBounceVertical = true
collectionView.delegate = self
collectionView.dataSource = self
collectionView.registerCell(cell:VCalculatorOptionsCell.self)
collectionView.registerHeader(header:VCalculatorOptionsHeader.self)
self.collectionView = collectionView
if let flow:VCollectionFlow = collectionView.collectionViewLayout as? VCollectionFlow
{
flow.headerReferenceSize = CGSize(width:0, height:kHeaderHeight)
flow.minimumInteritemSpacing = kInterItem
flow.minimumLineSpacing = kInterItem
flow.sectionInset = UIEdgeInsets(
top:kInterItem,
left:0,
bottom:kCollectionBottom,
right:0)
}
viewBase.addSubview(collectionView)
addSubview(blur)
addSubview(closeButton)
addSubview(viewBase)
NSLayoutConstraint.equals(
view:blur,
toView:self)
NSLayoutConstraint.equals(
view:closeButton,
toView:self)
NSLayoutConstraint.height(
view:viewBase,
constant:kBaseHeight)
layoutBaseBottom = NSLayoutConstraint.bottomToBottom(
view:viewBase,
toView:self,
constant:kBaseHeight)
NSLayoutConstraint.equalsHorizontal(
view:viewBase,
toView:self)
NSLayoutConstraint.equals(
view:collectionView,
toView:viewBase)
}
required init?(coder:NSCoder)
{
return nil
}
override func layoutSubviews()
{
collectionView.collectionViewLayout.invalidateLayout()
super.layoutSubviews()
}
//MARK: actions
func actionClose(sender button:UIButton)
{
controller.back()
}
//MARK: private
private func modelAtIndex(index:IndexPath) -> MCalculatorFunctions
{
let item:MCalculatorFunctions = controller.model.functions[index.item]
return item
}
//MARK: public
func viewAppeared()
{
layoutBaseBottom.constant = 0
UIView.animate(
withDuration:kAnimationDuration,
animations:
{ [weak self] in
self?.layoutIfNeeded()
})
{ [weak self] (done:Bool) in
guard
let functionList:[MCalculatorFunctions] = self?.controller.model.functions,
let selectedFunction:MCalculatorFunctions = self?.controller.model.currentFunction
else
{
return
}
var indexFunction:Int = 0
for function:MCalculatorFunctions in functionList
{
if function === selectedFunction
{
break
}
indexFunction += 1
}
let indexPath:IndexPath = IndexPath(
item:indexFunction,
section:0)
self?.collectionView.selectItem(
at:indexPath,
animated:true,
scrollPosition:UICollectionViewScrollPosition.centeredVertically)
}
}
//MARK: collectionView delegate
func collectionView(_ collectionView:UICollectionView, layout collectionViewLayout:UICollectionViewLayout, sizeForItemAt indexPath:IndexPath) -> CGSize
{
let width:CGFloat = collectionView.bounds.maxX
let size:CGSize = CGSize(width:width, height:kCellHeight)
return size
}
func numberOfSections(in collectionView:UICollectionView) -> Int
{
return 1
}
func collectionView(_ collectionView:UICollectionView, numberOfItemsInSection section:Int) -> Int
{
let count:Int = controller.model.functions.count
return count
}
func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView
{
let header:VCalculatorOptionsHeader = collectionView.dequeueReusableSupplementaryView(
ofKind:kind,
withReuseIdentifier:
VCalculatorOptionsHeader.reusableIdentifier,
for:indexPath) as! VCalculatorOptionsHeader
header.config(controller:controller)
return header
}
func collectionView(_ collectionView:UICollectionView, cellForItemAt indexPath:IndexPath) -> UICollectionViewCell
{
let item:MCalculatorFunctions = modelAtIndex(index:indexPath)
let cell:VCalculatorOptionsCell = collectionView.dequeueReusableCell(
withReuseIdentifier:
VCalculatorOptionsCell.reusableIdentifier,
for:indexPath) as! VCalculatorOptionsCell
cell.config(model:item)
return cell
}
func collectionView(_ collectionView:UICollectionView, didSelectItemAt indexPath:IndexPath)
{
collectionView.isUserInteractionEnabled = false
let item:MCalculatorFunctions = modelAtIndex(index:indexPath)
controller.selectOption(item:item)
}
}
| 2caaea2598c7c6b56b245ac8191bf086 | 30.740566 | 160 | 0.617179 | false | false | false | false |
mmrmmlrr/ModelsTreeKit | refs/heads/master | JetPack/Signal+BooleanType.swift | mit | 1 | //
// Signal+BooleanType.swift
// ModelsTreeKit
//
// Created by aleksey on 03.06.16.
// Copyright © 2016 aleksey chernish. All rights reserved.
//
import Foundation
public protocol BooleanType {
var boolValue: Bool { get }
}
extension Bool: BooleanType {
public var boolValue: Bool {
return self
}
}
public extension Signal where T: BooleanType {
func and(_ otherSignal: Signal<T>) -> Signal<Bool> {
return observable().combineLatest(otherSignal.observable()).map {
guard let value1 = $0, let value2 = $1 else { return false }
return value1.boolValue && value2.boolValue
}
}
func or(_ otherSignal: Signal<T>) -> Signal<Bool> {
return observable().combineLatest(otherSignal.observable()).map { $0?.boolValue == true || $1?.boolValue == true }
}
func xor(_ otherSignal: Signal<T>) -> Signal<Bool> {
return observable().combineLatest(otherSignal.observable()).map {
return $0?.boolValue == true && $1?.boolValue != true || $0?.boolValue != true && $1?.boolValue == true
}
}
func not() -> Signal<Bool> {
return map { !$0.boolValue }
}
}
public func && <T> (left: Signal<T>, right: Signal<T>) -> Signal<Bool> where T: BooleanType {
return left.and(right)
}
public func || <T> (left: Signal<T>, right: Signal<T>) -> Signal<Bool> where T: BooleanType {
return left.or(right)
}
public func != <T> (left: Signal<T>, right: Signal<T>) -> Signal<Bool> where T: BooleanType {
return left.xor(right)
}
public prefix func ! <T> (left: Signal<T>) -> Signal<Bool> where T: BooleanType {
return left.not()
}
| 74fda8d6e5f6007a7be54c740ec74581 | 24.171875 | 118 | 0.637492 | false | false | false | false |
Mindera/Alicerce | refs/heads/master | Tests/AlicerceTests/AutoLayout/TrailingConstrainableProxyTestCase.swift | mit | 1 | import XCTest
@testable import Alicerce
final class TrailingConstrainableProxyTestCase: BaseConstrainableProxyTestCase {
override func setUp() {
super.setUp()
view0.translatesAutoresizingMaskIntoConstraints = false
view0.widthAnchor.constraint(equalToConstant: 100).isActive = true
view0.heightAnchor.constraint(equalToConstant: 100).isActive = true
}
func testConstrain_WithTrailingConstraint_ShouldSupportRelativeEquality() {
var constraint: NSLayoutConstraint!
constrain(host, view0) { host, view0 in
constraint = view0.trailing(to: host)
}
let expected = NSLayoutConstraint(
item: view0!,
attribute: .trailing,
relatedBy: .equal,
toItem: host,
attribute: .trailing,
multiplier: 1,
constant: 0,
priority: .required,
active: true
)
XCTAssertConstraint(constraint, expected)
host.layoutIfNeeded()
XCTAssertEqual(view0.frame.maxX, host.frame.maxX)
}
func testConstrain_withTrailingConstraint_ShouldSupportRelativeInequalities() {
var constraint1: NSLayoutConstraint!
var constraint2: NSLayoutConstraint!
constrain(host, view0) { host, view0 in
constraint1 = view0.trailing(to: host, relation: .equalOrLess)
constraint2 = view0.trailing(to: host, relation: .equalOrGreater)
}
let expected1 = NSLayoutConstraint(
item: view0!,
attribute: .trailing,
relatedBy: .lessThanOrEqual,
toItem: host,
attribute: .trailing,
multiplier: 1,
constant: 0,
priority: .required,
active: true
)
XCTAssertConstraint(constraint1, expected1)
let expected2 = NSLayoutConstraint(
item: view0!,
attribute: .trailing,
relatedBy: .greaterThanOrEqual,
toItem: host,
attribute: .trailing,
multiplier: 1,
constant: 0,
priority: .required,
active: true
)
XCTAssertConstraint(constraint2, expected2)
host.layoutIfNeeded()
XCTAssertEqual(view0.frame.maxX, 500)
}
func testConstrain_WithTrailingConstraint_ShouldSupportPositiveOffset() {
var constraint: NSLayoutConstraint!
constrain(host, view0) { host, view0 in
constraint = view0.trailing(to: host, offset: 100)
}
let expected = NSLayoutConstraint(
item: view0!,
attribute: .trailing,
relatedBy: .equal,
toItem: host,
attribute: .trailing,
multiplier: 1,
constant: 100,
priority: .required,
active: true
)
XCTAssertConstraint(constraint, expected)
host.layoutIfNeeded()
XCTAssertEqual(view0.frame.maxX, 500 + 100)
}
func testConstrain_WithTrailingConstraint_ShouldSupportNegativeOffset() {
var constraint: NSLayoutConstraint!
constrain(host, view0) { host, view0 in
constraint = view0.trailing(to: host, offset: -100)
}
let expected = NSLayoutConstraint(
item: view0!,
attribute: .trailing,
relatedBy: .equal,
toItem: host,
attribute: .trailing,
multiplier: 1,
constant: -100,
priority: .required,
active: true
)
XCTAssertConstraint(constraint, expected)
host.layoutIfNeeded()
XCTAssertEqual(view0.frame.maxX, 500 - 100)
}
func testConstrain_WithTrailingConstraint_ShouldSupportLeadingAttribute() {
var constraint: NSLayoutConstraint!
constrain(host, view0) { host, view0 in
constraint = view0.trailingToLeading(of: host)
}
let expected = NSLayoutConstraint(
item: view0!,
attribute: .trailing,
relatedBy: .equal,
toItem: host,
attribute: .leading,
multiplier: 1,
constant: 0,
priority: .required,
active: true)
XCTAssertConstraint(constraint, expected)
host.layoutIfNeeded()
XCTAssertEqual(view0.frame.maxX, 0)
}
func testConstrain_WithTrailingConstraint_ShouldSupportCenterXAttribute() {
var constraint: NSLayoutConstraint!
constrain(host, view0) { host, view0 in
constraint = view0.trailingToCenterX(of: host)
}
let expected = NSLayoutConstraint(
item: view0!,
attribute: .trailing,
relatedBy: .equal,
toItem: host,
attribute: .centerX,
multiplier: 1,
constant: 0,
priority: .required,
active: true)
XCTAssertConstraint(constraint, expected)
host.layoutIfNeeded()
XCTAssertEqual(view0.frame.maxX, 250)
}
func testConstrain_WithTrailingConstraint_ShouldSupportCustomPriority() {
var constraint: NSLayoutConstraint!
constrain(host, view0) { host, view0 in
constraint = view0.trailing(to: host, priority: .init(666))
}
let expected = NSLayoutConstraint(
item: view0!,
attribute: .trailing,
relatedBy: .equal,
toItem: host,
attribute: .trailing,
multiplier: 1,
constant: 0,
priority: .init(666),
active: true
)
XCTAssertConstraint(constraint, expected)
}
func testConstrain_WithLayoutGuideTrailingConstraint_ShouldSupportRelativeEquality() {
var constraint: NSLayoutConstraint!
constrain(host, layoutGuide) { host, layoutGuide in
constraint = layoutGuide.trailing(to: host)
}
let expected = NSLayoutConstraint(
item: layoutGuide!,
attribute: .trailing,
relatedBy: .equal,
toItem: host,
attribute: .trailing,
multiplier: 1,
constant: 0,
priority: .required,
active: true
)
XCTAssertConstraint(constraint, expected)
host.layoutIfNeeded()
XCTAssertEqual(layoutGuide.layoutFrame.maxX, host.frame.maxX)
}
func testConstrain_WithAlignTrailingConstraintAndEmptyArray_ShouldReturnEmptyArray() {
let constraints = [UIView.ProxyType]().alignTrailing()
XCTAssertConstraints(constraints, [])
}
func testConstrain_WithAlignTrailingConstraint_ShouldSupportRelativeEquality() {
var constraints: [NSLayoutConstraint]!
view1.translatesAutoresizingMaskIntoConstraints = false
view2.translatesAutoresizingMaskIntoConstraints = false
constrain(host, view0, view1, view2) { host, view0, view1, view2 in
view0.trailing(to: host, offset: -50)
constraints = [view0, view1, view2].alignTrailing()
}
let expected = [
NSLayoutConstraint(
item: view0!,
attribute: .trailing,
relatedBy: .equal,
toItem: view1,
attribute: .trailing,
multiplier: 1,
constant: 0,
priority: .required,
active: true
),
NSLayoutConstraint(
item: view0!,
attribute: .trailing,
relatedBy: .equal,
toItem: view2,
attribute: .trailing,
multiplier: 1,
constant: 0,
priority: .required,
active: true
)
]
XCTAssertConstraints(constraints, expected)
host.layoutIfNeeded()
XCTAssertEqual(view0.frame.maxX, view1.frame.maxX)
XCTAssertEqual(view0.frame.maxX, view2.frame.maxX)
}
func testConstrain_WithTrailingConstraintAndTwoConstraintGroups_ShouldReturnCorrectIsActiveConstraint() {
var constraint0: NSLayoutConstraint!
var constraint1: NSLayoutConstraint!
let constraintGroup0 = constrain(host, view0, activate: false) { host, view0 in
constraint0 = view0.trailing(to: host)
}
let constraintGroup1 = constrain(host, view0, activate: false) { host, view0 in
constraint1 = view0.trailing(to: host, offset: -50)
}
let expected = [
NSLayoutConstraint(
item: view0!,
attribute: .trailing,
relatedBy: .equal,
toItem: host,
attribute: .trailing,
multiplier: 1,
constant: 0,
priority: .required,
active: false
),
NSLayoutConstraint(
item: view0!,
attribute: .trailing,
relatedBy: .equal,
toItem: host,
attribute: .trailing,
multiplier: 1,
constant: -50,
priority: .required,
active: false
)
]
XCTAssertConstraints([constraint0, constraint1], expected)
constraintGroup0.isActive = true
host.layoutIfNeeded()
XCTAssert(constraintGroup0.isActive)
XCTAssertFalse(constraintGroup1.isActive)
XCTAssertEqual(view0.frame.maxX, host.frame.maxX)
constraintGroup0.isActive = false
constraintGroup1.isActive = true
host.setNeedsLayout()
host.layoutIfNeeded()
XCTAssertFalse(constraintGroup0.isActive)
XCTAssert(constraintGroup1.isActive)
XCTAssertEqual(view0.frame.maxX, host.frame.maxX - 50)
}
}
| f8daa32f199fcb996c9528f1ce6f10b1 | 27.765217 | 109 | 0.574063 | false | false | false | false |
Legoless/Saystack | refs/heads/master | Code/Extensions/Core/Array+Utilities.swift | mit | 1 | //
// Array+Utilities.swift
// Saystack
//
// Created by Dal Rupnik on 23/05/16.
// Copyright © 2016 Unified Sense. All rights reserved.
//
import Foundation
extension Array where Element : AnyObject {
public mutating func remove(object: Element) {
if let index = firstIndex(where: { $0 === object }) {
self.remove(at: index)
}
}
}
extension Array where Element : Hashable {
public func unique() -> Array {
var seen: [Element : Bool] = [:]
return self.filter { seen.updateValue(true, forKey: $0) == nil }
}
}
extension Array {
public mutating func shuffle() {
for i in 0 ..< (count - 1) {
let j = Int(arc4random_uniform(UInt32(count - i))) + i
if i != j {
swapAt(i, j)
//swapAt(&self[i], &self[j])
}
}
}
public func shuffled() -> Array {
var shuffledArray = self
shuffledArray.shuffle()
return shuffledArray
}
}
extension Array {
public func containsType<T>(type: T.Type) -> Bool {
for object in self {
if object is T {
return true
}
}
return false
}
public func containsType<T>(type: T) -> Bool {
return containsType(type: T.self)
}
}
extension Array {
public func distinct(_ filter: ((Element) -> String?)) -> Array {
var hashes = Set<String>()
var finalArray : [Element] = []
for object in self {
let hash = filter(object)
if let hash = hash, !hashes.contains(hash) {
hashes.insert(hash)
finalArray.append(object)
}
}
return finalArray
}
}
| 65d9d5bd84b2c09432861c6092c7d0df | 21.481928 | 72 | 0.491961 | false | false | false | false |
codeWorm2015/LRLPhotoBrowser | refs/heads/master | Sources/LRLPhotoBrowser.swift | mit | 1 | //
// LRLPhotoBrowser.swift
// FeelfelCode
//
// Created by liuRuiLong on 17/5/17.
// Copyright © 2017年 李策. All rights reserved.
//
import UIKit
import SnapKit
public enum LRLPhotoBrowserModel{
case imageName(String)
case image(UIImage)
case imageUrl(ur: String, placeHolder: UIImage?)
case videoUrl(url: URL, placeHolder: UIImage?)
}
public enum LRLPBCollectionViewPageType {
case common
case slide
}
public protocol LRLPhotoBrowserDelegate: class{
func imageDidScroll(index: Int) -> UIImageView?
func imageSwipViewDismiss(imageView: UIImageView?)
}
public class LRLPhotoBrowser: UIView, LRLPBCollectionDelegate{
/// 所点击的 imageView
public var selectedImageView: UIImageView?
/// 当前所选中ImageView 相对于 pbSuperView 的位置
public var selectedFrame: CGRect?
public weak var delegate: LRLPhotoBrowserDelegate?
/// 是否开启拖动
public var animition = false{
didSet{
self.collectionView?.panEnable = animition
}
}
/// 相册的实例化方法
///
/// - Parameters:
/// - frame: 相册视图尺寸, 默认为屏幕尺寸
/// - dataSource: 数据源
/// - initialIndex: 初始位置
/// - selectedImageView: 所点击的imageView 根据这个imageView 内部进行动画
/// - delegate: 代理
/// - animition: 是否开启拖拽和动画
public init(frame: CGRect = UIScreen.main.bounds, dataSource: [LRLPhotoBrowserModel], initialIndex: Int, selectedImageView: UIImageView?, delegate: LRLPhotoBrowserDelegate?, animition: Bool = true, pageType: LRLPBCollectionViewPageType = .slide) {
self.pageType = pageType
super.init(frame:frame)
self.dataSource = dataSource
self.delegateHolder = LRLPBCollectionDelegateHolder(delegate: self)
self.imgContentMode = contentMode
self.initialIndex = initialIndex
self.currentIndex = initialIndex
self.selectedImageView = selectedImageView
self.delegate = delegate
self.animition = animition
configUI()
}
/// 显示相册
public func show(){
guard let window = pbSuperView else{
fatalError("no superView")
}
if let inImageView = selectedImageView, let initialFrame = inImageView.superview?.convert(inImageView.frame, to: window){
selectedFrame = initialFrame
let imageView = LRLPBImageView(frame: initialFrame)
imageView.contentMode = .scaleAspectFill
imageView.image = inImageView.image
window.addSubview(imageView)
window.isUserInteractionEnabled = false
UIView.animate(withDuration: 0.2, animations: {
imageView.contentMode = .scaleAspectFit
imageView.frame = self.frame
imageView.backgroundColor = UIColor.black
}, completion: { (complete) in
window.isUserInteractionEnabled = true
imageView.removeFromSuperview()
window.addSubview(self)
})
}else{
window.addSubview(self)
}
}
public func dismiss(){
if let cell = collectionView?.cellForItem(at: IndexPath(item: currentIndex, section: 0)) as? LRLPBImageCell{
dismissCell(cell)
}else{
self.removeFromSuperview()
self.delegate?.imageSwipViewDismiss(imageView: nil)
}
}
private var dataSource:[LRLPhotoBrowserModel]?
private var imgContentMode: UIViewContentMode = .scaleAspectFill
private var initialIndex: Int?
private var collectionView: LRLPBCollectionView?
private var pageControl: UIPageControl?
private var collectionDelegate: LRLPBCollectionDelegate?
private var delegateHolder: LRLPBCollectionDelegateHolder?
private var currentIndex:Int = 0
private var pageType: LRLPBCollectionViewPageType = .slide
private var pbSuperView: UIWindow?{
get{
return UIApplication.shared.keyWindow
}
}
required public init?(coder aDecoder: NSCoder) {
fatalError()
}
private func configUI() {
let myLayout = UICollectionViewFlowLayout()
myLayout.scrollDirection = .horizontal
myLayout.minimumLineSpacing = 0
myLayout.minimumInteritemSpacing = 0
collectionView = LRLPBCollectionView(frame: CGRect(x: 0, y: 0, width: self.bounds.size.width, height: self.bounds.size.height), collectionViewLayout: myLayout)
collectionView?.dismissBlock = dismissCell
collectionView?.register(LRLPBImageCell.self, forCellWithReuseIdentifier: LRLPBImageCell.reuseIdentifier())
collectionView?.register(LRLPBVideoCell.self, forCellWithReuseIdentifier: LRLPBVideoCell.reuseIdentifier())
collectionView?.panEnable = self.animition
collectionView?.isPagingEnabled = true
collectionView?.delegate = delegateHolder
collectionView?.dataSource = delegateHolder
addSubview(collectionView!)
if let index = initialIndex{
let index = IndexPath(item: index, section: 0)
collectionView?.scrollToItem(at: index, at: .centeredHorizontally, animated: false)
collectionView?.reloadData()
}
pageControl = UIPageControl()
pageControl?.numberOfPages = self.dataSource?.count ?? 0
addSubview(pageControl!)
pageControl?.addTarget(self, action: #selector(LRLPhotoBrowser.pageControlAct), for: .touchUpInside)
pageControl?.snp.makeConstraints { (make) in
make.centerX.equalTo(self)
make.leading.equalTo(self)
make.trailing.equalTo(self)
make.bottom.equalTo(self).offset(-20.0)
}
if let index = self.initialIndex {
pageControl?.currentPage = index
}
}
lazy private var dismissCell: (LRLPBCell) -> Void = { [weak self] (dissMissCell) in
guard let s = self else{
return
}
let imageView = dissMissCell.showView
func dismiss(){
imageView.removeFromSuperview()
s.removeFromSuperview()
s.delegate?.imageSwipViewDismiss(imageView: imageView.imageView)
}
imageView.removeFromSuperview()
if let localView = UIApplication.shared.keyWindow, let loc = s.selectedFrame, s.animition{
localView.addSubview(imageView)
UIView.animate(withDuration: 0.3, animations: {
imageView.transform = CGAffineTransform.identity
imageView.setZoomScale(scale: 1.0)
imageView.contentMode = UIViewContentMode.scaleAspectFill
imageView.frame = loc
s.alpha = 0.0
}, completion: { (success) in
dismiss()
})
}else{
dismiss()
}
}
@objc private func pageControlAct(page: UIPageControl){
if !(collectionView?.panning ?? true){
let indexPath = IndexPath(item: page.currentPage, section: 0)
collectionView?.scrollToItem(at: indexPath, at: .centeredHorizontally, animated: true)
hasScrollTo(index: page.currentPage)
}else{
page.currentPage = currentIndex
}
}
private func hasScrollTo(index:Int){
if let inImageView = self.delegate?.imageDidScroll(index: index){
self.selectedFrame = inImageView.superview?.convert(inImageView.frame, to: pbSuperView)
}
currentIndex = index
}
//MARK: UICollectionViewDataSource
public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
guard let data = dataSource?[indexPath.row] else { return UICollectionViewCell() }
let cell:UICollectionViewCell
switch data {
case .videoUrl(url: _, placeHolder: _):
cell = collectionView.dequeueReusableCell(withReuseIdentifier: LRLPBVideoCell.reuseIdentifier(), for: indexPath) as! LRLPBVideoCell
default:
cell = collectionView.dequeueReusableCell(withReuseIdentifier: LRLPBImageCell.reuseIdentifier(), for: indexPath) as! LRLPBImageCell
}
switch data {
case .imageName(let name):
(cell as! LRLPBImageCell).setData(imageName: name)
case .imageUrl(let imageUrl, let placeHolder):
(cell as! LRLPBImageCell).setData(imageUrl: imageUrl, placeHolder: placeHolder)
case .image(let image):
(cell as! LRLPBImageCell).setData(image: image)
case .videoUrl(url: let videoUrl, placeHolder: let image):
(cell as! LRLPBVideoCell).setData(videoUrl: videoUrl, placeHolder: image)
}
return cell
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return self.dataSource?.count ?? 0
}
//MARK: UICollectionViewDelegate
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
if let cell = collectionView.cellForItem(at: indexPath) as? LRLPBCell{
dismissCell(cell)
}
}
func collectionView(_ collectionView: UICollectionView, didEndDisplaying cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
(cell as? LRLPBCell)?.endDisplay()
}
//MARK: UICollectionViewDelegateFlowLayout
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: self.bounds.size.width, height: self.bounds.size.height)
}
//MARK:
func scrollViewDidScroll(_ scrollView: UIScrollView) {
guard pageType == .slide else {
return
}
var offset = scrollView.contentOffset.x/scrollView.bounds.width
if offset >= 0 && offset < CGFloat(self.dataSource?.count ?? 0){
let i = floor(offset)
let j = ceil(offset)
if i != offset || j != offset{
offset = offset - floor(offset)
}else{
offset = 1.0
}
if self.collectionView?.visibleCells.count ?? 0 == 2 {
let cell1 = collectionView?.cellForItem(at: IndexPath(item: Int(i), section: 0)) as? LRLPBCell
cell1?.changeTheImageViewLocationWithOffset(offset: offset)
let cell2 = collectionView?.cellForItem(at: IndexPath(item: Int(j), section: 0)) as? LRLPBCell
cell2?.changeTheImageViewLocationWithOffset(offset: offset - 1.0)
}
}
}
func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
let index = Int(scrollView.contentOffset.x/self.bounds.size.width)
self.pageControl?.currentPage = index
hasScrollTo(index: index)
}
fileprivate class LRLPBCollectionDelegateHolder: NSObject, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout{
private override init() {
fatalError()
}
init(delegate: LRLPBCollectionDelegate) {
collectionDelegate = delegate
}
fileprivate weak var collectionDelegate: LRLPBCollectionDelegate?
//MARK: UICollectionViewDataSource
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
return collectionDelegate?.collectionView(collectionView, cellForItemAt: indexPath) ?? UICollectionViewCell()
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return collectionDelegate?.collectionView(collectionView, numberOfItemsInSection: section) ?? 0
}
//MARK: UICollectionViewDelegate
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
collectionDelegate?.collectionView(collectionView, didSelectItemAt: indexPath)
}
func collectionView(_ collectionView: UICollectionView, didEndDisplaying cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
collectionDelegate?.collectionView(collectionView, didEndDisplaying: cell, forItemAt: indexPath)
}
//MARK: UICollectionViewDelegateFlowLayout
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return collectionDelegate?.collectionView(collectionView, layout: collectionViewLayout, sizeForItemAt: indexPath) ?? CGSize.zero
}
//MARK: UIScrollViewDelegate
func scrollViewDidScroll(_ scrollView: UIScrollView) {
collectionDelegate?.scrollViewDidScroll(scrollView)
}
func scrollViewDidEndDecelerating(_ scrollView: UIScrollView){
collectionDelegate?.scrollViewDidEndDecelerating(scrollView)
}
}
}
fileprivate protocol LRLPBCollectionDelegate: NSObjectProtocol{
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath)
func collectionView(_ collectionView: UICollectionView, didEndDisplaying cell: UICollectionViewCell, forItemAt indexPath: IndexPath)
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize
func scrollViewDidScroll(_ scrollView: UIScrollView)
func scrollViewDidEndDecelerating(_ scrollView: UIScrollView)
}
| 52f877f6a5d87043a79c6f150efeba5a | 41.54908 | 251 | 0.666787 | false | false | false | false |
lee0741/Glider | refs/heads/master | Glider/HomeController.swift | mit | 1 | //
// HomeController.swift
// Glider
//
// Created by Yancen Li on 2/24/17.
// Copyright © 2017 Yancen Li. All rights reserved.
//
import UIKit
import CoreSpotlight
import MobileCoreServices
class HomeController: UITableViewController, UISearchResultsUpdating {
let cellId = "homeId"
let defaults = UserDefaults.standard
var stories = [Story]()
var storyType = StoryType.news
var query = ""
var pagination = 1
var updating = false
var searchController: UISearchController!
var searchResults = [Story]()
var savedSearches = [String]()
var searchableItems = [CSSearchableItem]()
override func viewDidLoad() {
super.viewDidLoad()
configController()
Story.getStories(type: storyType, query: query, pagination: 1) { stories in
self.stories = stories
UIApplication.shared.isNetworkActivityIndicatorVisible = false
self.tableView.reloadData()
self.setupSearchableContent(stories)
}
}
func configController() {
if let savedSearch = defaults.object(forKey: "SavedQuery") {
savedSearches = savedSearch as! [String]
}
UIApplication.shared.isNetworkActivityIndicatorVisible = true
UIApplication.shared.statusBarStyle = .lightContent
if storyType == .search {
navigationItem.title = query
if savedSearches.contains(query) == false {
let saveBarButtonItem = UIBarButtonItem(barButtonSystemItem: .save, target: self, action: #selector(saveAction))
navigationItem.setRightBarButton(saveBarButtonItem, animated: true)
}
} else {
navigationItem.title = storyType.rawValue
}
navigationItem.backBarButtonItem = UIBarButtonItem(title: "", style: .plain, target: nil, action: nil)
tableView.register(HomeCell.self, forCellReuseIdentifier: cellId)
tableView.estimatedRowHeight = 80.0
tableView.rowHeight = UITableViewAutomaticDimension
tableView.separatorColor = .separatorColor
searchController = UISearchController(searchResultsController: nil)
tableView.tableHeaderView = searchController.searchBar
searchController.searchResultsUpdater = self
searchController.dimsBackgroundDuringPresentation = false
searchController.hidesNavigationBarDuringPresentation = false
searchController.searchBar.tintColor = .mainColor
searchController.searchBar.searchBarStyle = .minimal
definesPresentationContext = true
searchController.loadViewIfNeeded()
refreshControl = UIRefreshControl()
refreshControl?.tintColor = .mainColor
refreshControl?.addTarget(self, action: #selector(handleRefresh(_:)), for: UIControlEvents.valueChanged)
if traitCollection.forceTouchCapability == .available {
registerForPreviewing(with: self as UIViewControllerPreviewingDelegate, sourceView: view)
}
}
func saveAction() {
navigationItem.setRightBarButton(UIBarButtonItem(), animated: true)
savedSearches.append(query)
defaults.set(savedSearches, forKey: "SavedQuery")
defaults.synchronize()
}
// MARK: - Spotlight Search
func setupSearchableContent(_ newStories: [Story]) {
newStories.forEach { story in
let searchableItemAttributeSet = CSSearchableItemAttributeSet(itemContentType: kUTTypeText as String)
searchableItemAttributeSet.title = story.title
searchableItemAttributeSet.contentDescription = story.domain
searchableItemAttributeSet.keywords = [story.title]
let searchableItem = CSSearchableItem(uniqueIdentifier: "org.yancen.glider.\(story.id)", domainIdentifier: "story", attributeSet: searchableItemAttributeSet)
searchableItems.append(searchableItem)
}
CSSearchableIndex.default().indexSearchableItems(searchableItems) { (error) -> Void in
if error != nil {
print(error?.localizedDescription ?? "Fail to index")
}
}
}
override func restoreUserActivityState(_ activity: NSUserActivity) {
if activity.activityType == CSSearchableItemActionType {
if let userInfo = activity.userInfo {
let selectedStory = userInfo[CSSearchableItemActivityIdentifier] as! String
let commentController = CommentController()
commentController.itemId = Int(selectedStory.components(separatedBy: ".").last!)!
navigationController?.pushViewController(commentController, animated: true)
}
}
}
// MARK: - Pull to Refresh
func handleRefresh(_ refreshControl: UIRefreshControl) {
pagination = 1
UIApplication.shared.isNetworkActivityIndicatorVisible = true
Story.getStories(type: storyType, query: query, pagination: 1) { stories in
self.stories = stories
UIApplication.shared.isNetworkActivityIndicatorVisible = false
OperationQueue.main.addOperation {
self.tableView.reloadData()
refreshControl.endRefreshing()
self.searchableItems = [CSSearchableItem]()
self.setupSearchableContent(stories)
}
}
}
// MARK: - Search Logic
func filterContent(for searchText: String) {
searchResults = stories.filter { (story) -> Bool in
let isMatch = story.title.localizedCaseInsensitiveContains(searchText)
return isMatch
}
}
func updateSearchResults(for searchController: UISearchController) {
if let searchText = searchController.searchBar.text {
filterContent(for: searchText)
tableView.reloadData()
}
}
override func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
searchController.searchBar.endEditing(true)
}
// MARK: - Table View Data Source
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return searchController.isActive ? searchResults.count : stories.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: cellId, for: indexPath) as! HomeCell
let story = searchController.isActive ? searchResults[indexPath.row] : stories[indexPath.row]
cell.story = story
cell.commentView.addTarget(self, action: #selector(pushToCommentView(_:)), for: .touchUpInside)
cell.layoutIfNeeded()
return cell
}
override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
if storyType != .search && stories.count - indexPath.row < 10 && !updating && pagination < 18 {
updating = true
pagination += 1
UIApplication.shared.isNetworkActivityIndicatorVisible = true
Story.getStories(type: storyType, query: query, pagination: pagination) { stories in
self.stories += stories
self.updating = false
UIApplication.shared.isNetworkActivityIndicatorVisible = false
self.tableView.reloadData()
self.setupSearchableContent(stories)
}
}
}
// MARK: - Table View Delegate
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let story = searchController.isActive ? searchResults[indexPath.row] : stories[indexPath.row]
if story.url.hasPrefix("https://news.ycombinator.com/item?id=") {
let commentController = CommentController()
commentController.itemId = story.id
navigationController?.pushViewController(commentController, animated: true)
} else {
let safariController = MySafariViewContoller(url: URL(string: story.url)!)
present(safariController, animated: true, completion: nil)
}
}
override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
return searchController.isActive ? false : true
}
override func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
let story = self.stories[indexPath.row]
let shareAction = UITableViewRowAction(style: .default, title: "Share", handler:
{ (action, indexPath) -> Void in
let defaultText = story.title + " " + story.url
let activityController = UIActivityViewController(activityItems: [defaultText], applicationActivities: nil)
self.present(activityController, animated: true, completion: nil)
})
shareAction.backgroundColor = .mainColor
return [shareAction]
}
func pushToCommentView(_ sender: CommentIconView) {
guard sender.numberOfComment != 0 else { return }
let commentController = CommentController()
commentController.itemId = sender.itemId
navigationController?.pushViewController(commentController, animated: true)
}
}
// MARK: - 3D Touch
extension HomeController: UIViewControllerPreviewingDelegate {
func previewingContext(_ previewingContext: UIViewControllerPreviewing, viewControllerForLocation location: CGPoint) -> UIViewController? {
guard let indexPath = tableView.indexPathForRow(at: location),
let cell = tableView.cellForRow(at: indexPath),
let url = URL(string: stories[indexPath.row].url) else {
return nil
}
let safariController = MySafariViewContoller(url: url)
previewingContext.sourceRect = cell.frame
return safariController
}
func previewingContext(_ previewingContext: UIViewControllerPreviewing, commit viewControllerToCommit: UIViewController) {
present(viewControllerToCommit, animated: true, completion: nil)
}
}
| 1248d262084d8f20c2c3cf1c487caf34 | 36.1875 | 163 | 0.723845 | false | false | false | false |
Mattmlm/codepathrottentomatoes | refs/heads/master | Rotten Tomatoes/Rotten Tomatoes/MovieDetailsViewController.swift | mit | 1 | //
// MovieDetailsViewController.swift
// Rotten Tomatoes
//
// Created by admin on 9/18/15.
// Copyright © 2015 mattmo. All rights reserved.
//
import UIKit
class MovieDetailsViewController: UIViewController {
var movieData: NSDictionary?
@IBOutlet weak var movieCoverView: UIImageView!
@IBOutlet weak var movieTitleLabel: UILabel!
@IBOutlet weak var movieDetailsLabel: UILabel!
@IBOutlet weak var movieRatingsLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
self.navigationController?.navigationBar.tintColor = UIColor.blackColor()
// Do any additional setup after loading the view.
UIView.animateWithDuration(2) { () -> Void in
self.movieCoverView.alpha = 1;
}
if self.movieData != nil {
RTAPISupport.setMovieCover(self.movieCoverView, movieData: self.movieData!);
if let title = RTAPISupport.getMovieTitle(self.movieData!) {
self.movieTitleLabel.text = title;
self.navigationItem.title = title;
}
if let ratings = RTAPISupport.getMovieRatings(self.movieData!) {
self.movieRatingsLabel.text = ratings;
}
if let description = RTAPISupport.getMovieSynopsis(self.movieData!) {
self.movieDetailsLabel.text = description;
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| 179938d694dfc766791c0c5c97770e4e | 30.72 | 88 | 0.631778 | false | false | false | false |
geekaurora/ReactiveListViewKit | refs/heads/master | ReactiveListViewKit/Supported Files/CZUtils/Sources/CZUtils/Extensions/String+.swift | mit | 1 | //
// NSString+Additions
//
// Created by Cheng Zhang on 1/5/16.
// Copyright © 2016 Cheng Zhang. All rights reserved.
//
import Foundation
public extension String {
/**
Search substrings that matches regex pattern
- parameter regex: the regex pattern
- parameter excludeRegEx: indicates whether returned substrings exclude regex pattern iteself
- returns: all matched substrings
*/
func search(regex: String, excludeRegEx: Bool = true) -> [String] {
guard let regex = try? NSRegularExpression(pattern: regex, options: []) else {
return []
}
let string = self as NSString
let results = regex.matches(in: self, options: [], range: NSMakeRange(0, string.length))
return results.compactMap { result in
guard result.numberOfRanges > 0 else {
return nil
}
let i = excludeRegEx ? (result.numberOfRanges - 1) : 0
return result.range(at: i).location != NSNotFound ? string.substring(with: result.range(at: i)) : nil
}
}
/**
URLHostAllowedCharacterSet "#%/<>?@\^`{|}
URLQueryAllowedCharacterSet "#%<>[\]^`{|}
URLFragmentAllowedCharacterSet "#%<>[\]^`{|}
URLPasswordAllowedCharacterSet "#%/:<>?@[\]^`{|}
URLPathAllowedCharacterSet "#%;<>?[\]^`{|}
URLUserAllowedCharacterSet "#%/:<>?@[\]^`
http://stackoverflow.com/questions/24551816/swift-encode-url
*/
func urlEncoded()-> String {
guard firstIndex(of: "%") == nil else { return self }
let mutableString = NSMutableString(string: self)
let urlEncoded = mutableString.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)
return urlEncoded ?? ""
}
var intValue: Int? {
return Int(self)
}
// public var cgFloatValue: CGFloat? {
// if let intValue = intValue {
// return CGFloat(intValue)
// }
// return nil
// }
}
| da2fa841a428925b9f1068274e8b7b1a | 31.52459 | 113 | 0.599798 | false | false | false | false |
brandonlee503/Fun-Facts | refs/heads/master | Fun Facts/ViewController.swift | mit | 1 | //
// ViewController.swift
// Fun Facts
//
// Created by Brandon Lee on 6/25/15.
// Copyright (c) 2015 Brandon Lee. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
//Outlets for button and label
@IBOutlet weak var funFactLabel: UILabel!
@IBOutlet weak var funFactButton: UIButton!
//Instance of data model
let factBook = FactBook()
let colorWheel = ColorWheel()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
funFactLabel.text = factBook.getRandomFact()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func showFunFact() {
//Get and display random color and a fact
var theRandomColor = colorWheel.getRandomColor()
view.backgroundColor = theRandomColor
funFactButton.tintColor = theRandomColor
funFactLabel.text = factBook.getRandomFact()
}
}
| 8dc50ffea9c1c819d64a0783555af16e | 24.25 | 80 | 0.657966 | false | false | false | false |
bazelbuild/tulsi | refs/heads/master | src/TulsiGenerator/TulsiProcessRunner.swift | apache-2.0 | 1 | // Copyright 2016 The Tulsi Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import Foundation
/// Wraps the standard ProcessRunner and injects Tulsi-specific environment variables.
public final class TulsiProcessRunner {
public typealias CompletionHandler = (ProcessRunner.CompletionInfo) -> Void
private static var defaultEnvironment: [String: String] = {
var environment = ProcessInfo.processInfo.environment
if let cfBundleVersion = Bundle.main.infoDictionary?["CFBundleVersion"] as? String {
environment["TULSI_VERSION"] = cfBundleVersion
}
return environment
}()
/// Prepares a Process using the given launch binary with the given arguments that will collect
/// output and passing it to a terminationHandler.
static func createProcess(_ launchPath: String,
arguments: [String],
environment: [String: String] = [:],
messageLogger: LocalizedMessageLogger? = nil,
loggingIdentifier: String? = nil,
terminationHandler: @escaping CompletionHandler) -> Process {
let env = environment.merging(defaultEnvironment) { (current, _) in
return current
}
return ProcessRunner.createProcess(launchPath,
arguments: arguments,
environment: env,
messageLogger: messageLogger,
loggingIdentifier: loggingIdentifier,
terminationHandler: terminationHandler)
}
}
| e46248f40dec5bc5096b0e04f9ee822a | 43.55102 | 97 | 0.642235 | false | false | false | false |
Ghosty141/MenuBarControls | refs/heads/master | MenuBarControls/PlayerPopoverViewController.swift | gpl-3.0 | 1 | //
// PlayerPopover.swift
// MenuBarControls
//
// Copyright © 2017 Ghostly. All rights reserved.
//
import Cocoa
import CoreImage
import ScriptingBridge
class PlayerPopoverViewController: NSViewController {
let appDel = NSApplication.shared.delegate as? AppDelegate
var lastURL: String?
var mouseoverIsActive = false
var updateTimer: Timer?
var settingsController: NSWindowController?
let spotify = SBApplication(bundleIdentifier: "com.spotify.client")! as SpotifyApplication
@IBOutlet weak var coverImage: NSImageView!
@IBOutlet weak var trackLabel: NSTextField!
@IBOutlet weak var albumLabel: NSTextField!
@IBOutlet weak var artistLabel: NSTextField!
@IBOutlet weak var trackTimeLabel: NSTextField!
@IBOutlet weak var cover: NSImageCell!
@IBOutlet weak var playPauseButton: NSButtonCell!
@IBOutlet weak var volumeSlider: NSSliderCell!
@IBOutlet weak var shuffleButton: NSButtonCell!
@IBOutlet weak var repeatButton: NSButtonCell!
@IBOutlet weak var track: NSTextFieldCell!
@IBOutlet weak var album: NSTextFieldCell!
@IBOutlet weak var artist: NSTextFieldCell!
func startTimer() {
if updateTimer == nil {
updateTimer = Timer.scheduledTimer(
timeInterval: UserDefaults.standard.double(forKey: "UpdateRate"),
target: self,
selector: #selector(self.checkAppStatus),
userInfo: nil,
repeats: true)
}
}
func stopTimer() {
if updateTimer != nil {
updateTimer?.invalidate()
updateTimer = nil
}
}
@objc func checkAppStatus() {
if appDel?.isSpotifyRunning() == false {
appDel?.closePopover(self)
} else {
if spotify.playerState == .playing {
if lastURL != spotify.currentTrack?.artworkUrl {
updateCover()
}
if mouseoverIsActive {
trackTimeLabel.stringValue =
"- \(formatTime(using: Int32(spotify.playerPosition!))) / \(formatTime(using: Int32((spotify.currentTrack?.duration)!/1000))) -"
}
updateShuffleButton()
updateRepeatButton()
updatePlayPauseButton()
volumeSlider.integerValue = spotify.soundVolume!
} else {
updatePlayPauseButton()
if appDel?.popover.isShown == false {
stopTimer()
}
}
}
}
func updatePlayPauseButton() {
if playPauseButton.state == NSControl.StateValue.off && spotify.playerState == .playing {
playPauseButton.state = NSControl.StateValue.on
} else if playPauseButton.state == NSControl.StateValue.on && spotify.playerState == .paused {
playPauseButton.state = NSControl.StateValue.off
}
}
func updateShuffleButton() {
if shuffleButton.state == NSControl.StateValue.off && spotify.shuffling == true {
shuffleButton.state = NSControl.StateValue.on
} else if shuffleButton.state == NSControl.StateValue.on && spotify.shuffling == false {
shuffleButton.state = NSControl.StateValue.off
}
}
func updateRepeatButton() {
if repeatButton.state == NSControl.StateValue.off && spotify.repeating == true {
repeatButton.state = NSControl.StateValue.on
} else if shuffleButton.state == NSControl.StateValue.on && spotify.repeating == false {
repeatButton.state = NSControl.StateValue.off
}
}
private func updateCover() {
let dataURL = spotify.currentTrack?.artworkUrl ?? lastURL!
let urlContent = try? Data(contentsOf: URL(string: dataURL)!)
if let coverArt = urlContent {
imageGroup.original = NSImage(data: coverArt)
imageGroup.processed = blurImage(imageGroup.original!)
cover.image = imageGroup.original
} else {
cover.image = NSImage(named: NSImage.Name(rawValue: "CoverError"))
}
if mouseoverIsActive {
mouseOverOn()
}
lastURL = spotify.currentTrack?.artworkUrl
}
// CABasicAnimation / Core Animation is suited for this
func blurImage(_ inputImage: NSImage) -> NSImage {
let context = CIContext(options: nil)
let image = CIImage(data: inputImage.tiffRepresentation!)
// Extends the borders of the image to infinity to avoid a white lining
let transform = AffineTransform.identity
let extendImage = CIFilter(name: "CIAffineClamp")
extendImage!.setValue(image, forKey: "inputImage")
extendImage!.setValue(NSAffineTransform(transform: transform), forKey: "inputTransform")
let extendedImage = extendImage?.outputImage
// Generates a black image with 0.5 alpha
let blackGenerator = CIFilter(name: "CIConstantColorGenerator")
blackGenerator!.setValue(CIColor.init(red: 0,
green: 0,
blue: 0,
alpha:
CGFloat(UserDefaults.standard.double(forKey: "brightnessValue")) / 100),
forKey: "inputColor")
let black = blackGenerator!.outputImage
// Crop the generated black image to the size of the input
let cropBlack = CIFilter(name: "CISourceInCompositing")
cropBlack!.setValue(black, forKey: "inputImage")
cropBlack!.setValue(image, forKey: "inputBackgroundImage")
let croppedBlack = cropBlack!.outputImage
// Blurs the input
let blurFilter = CIFilter(name: "CIGaussianBlur")
blurFilter!.setValue(extendedImage, forKey: kCIInputImageKey)
blurFilter!.setValue(CGFloat(UserDefaults.standard.integer(forKey: "blurValue")), forKey: kCIInputRadiusKey)
let blurredImage = blurFilter!.outputImage
// Lays the black image ontop of the original
let mixFilter = CIFilter(name: "CISourceAtopCompositing")
mixFilter!.setValue(croppedBlack, forKey: "inputImage")
mixFilter!.setValue(blurredImage, forKey: "inputBackgroundImage") //input change
let mixed = mixFilter!.outputImage
// Crops it again so there aren't any borders
let cropFilter = CIFilter(name: "CICrop")
cropFilter!.setValue(mixed, forKey: kCIInputImageKey)
cropFilter!.setValue(CIVector(cgRect: image!.extent), forKey: "inputRectangle")
let cropped = cropFilter!.outputImage
// Converts the CGImage to NSImage and returns it
let cgimg = context.createCGImage(cropped!, from: cropped!.extent)
let processedImage = NSImage(cgImage: cgimg!, size: NSSize(width: 0, height: 0))
return processedImage
}
func formatTime(using time: Int32) -> String {
let zeroPrefixFormatter = NumberFormatter()
zeroPrefixFormatter.minimumIntegerDigits = 2
return "\(time/60):\(zeroPrefixFormatter.string(from: NSNumber(value: (time-(time/60)*60)))!)"
}
func mouseOverOn() {
mouseoverIsActive = true
cover.image = imageGroup.processed
track.stringValue = (spotify.currentTrack?.name)!
album.stringValue = (spotify.currentTrack?.album)!
artist.stringValue = (spotify.currentTrack?.artist)!
trackTimeLabel.stringValue =
"- \(formatTime(using: Int32(spotify.playerPosition!))) / \(formatTime(using: Int32((spotify.currentTrack?.duration)!/1000))) -"
trackLabel.isHidden = !Bool(truncating: UserDefaults.standard.integer(forKey: "displayTrackTitle") as NSNumber)
albumLabel.isHidden = !Bool(truncating: UserDefaults.standard.integer(forKey: "displayAlbumTitle") as NSNumber)
artistLabel.isHidden = !Bool(truncating: UserDefaults.standard.integer(forKey: "displayArtistName") as NSNumber)
trackTimeLabel.isHidden = !Bool(truncating: UserDefaults.standard.integer(forKey: "displayTrackTime") as NSNumber)
}
func mouseOverOff() {
mouseoverIsActive = false
coverImage.image = imageGroup.original ?? NSImage(named: NSImage.Name("CoverError"))
trackLabel.isHidden = true
albumLabel.isHidden = true
artistLabel.isHidden = true
trackTimeLabel.isHidden = true
}
// IBActions for the player-popover
@IBAction func playPause(_ sender: Any) {
spotify.playpause!()
}
@IBAction func volumeSlider(_ sender: NSSlider) {
spotify.setSoundVolume!(sender.integerValue)
}
@IBAction func next(_ sender: NSButton) {
spotify.nextTrack!()
if UserDefaults.standard.integer(forKey: "trackInfoDelay") != 0 {
mouseOverOn()
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() +
UserDefaults.standard.double(forKey: "trackInfoDelay")) {
self.mouseOverOff()
}
}
}
@IBAction func previous(_ sender: NSButton) {
spotify.previousTrack!()
}
@IBAction func repeats(_ sender: NSButtonCell) {
spotify.setRepeating!(Bool(truncating: sender.intValue as NSNumber))
}
@IBAction func shuffle(_ sender: NSButtonCell) {
spotify.setShuffling!(Bool(truncating: sender.intValue as NSNumber))
}
@IBAction func openSettings(_ sender: NSButton) {
settingsController = NSStoryboard(
name: NSStoryboard.Name(rawValue: "Main"),
bundle: nil)
.instantiateController(
withIdentifier: NSStoryboard.SceneIdentifier(rawValue: "SettingsWindow")) as? NSWindowController
settingsController?.showWindow(self)
}
// Overrides
override func mouseEntered(with event: NSEvent) {
mouseOverOn()
}
override func mouseExited(with event: NSEvent) {
mouseOverOff()
}
override func viewDidLoad() {
super.viewDidLoad()
startTimer()
updatePlayPauseButton()
updateShuffleButton()
updateRepeatButton()
updateCover()
volumeSlider.integerValue = spotify.soundVolume!
let trackingArea = NSTrackingArea(rect: coverImage.bounds,
options: [NSTrackingArea.Options.mouseEnteredAndExited,
NSTrackingArea.Options.activeAlways],
owner: self,
userInfo: nil)
coverImage.addTrackingArea(trackingArea)
}
override func viewDidDisappear() {
super.viewDidDisappear()
updateTimer?.invalidate()
imageGroup = ImageMemory(originalImage: nil, processedImage: nil)
}
}
| a8e6955eea230c69a0057e91d11fde83 | 36.961672 | 128 | 0.62827 | false | false | false | false |
laurb9/PanoController-iOS | refs/heads/master | PanoController/MenuTableViewController.swift | mit | 1 | //
// MenuTableViewController.swift
// PanoController
//
// Created by Laurentiu Badea on 7/30/17.
// Copyright © 2017 Laurentiu Badea.
//
// This file may be redistributed under the terms of the MIT license.
// A copy of this license has been included with this distribution in the file LICENSE.
//
import UIKit
class MenuTableViewController: UITableViewController {
var menus: Menu!
override func viewDidLoad() {
super.viewDidLoad()
tableView.estimatedRowHeight = 24.0
tableView.rowHeight = UITableViewAutomaticDimension
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
}
override func viewWillAppear(_ animated: Bool) {
print("MenuTableViewControler: \(String(describing: menus))")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
return menus!.count
}
override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return menus![section].name
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return (menus![section] as! Menu).count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell: UITableViewCell
let menuItem = menus![indexPath]
switch menuItem {
case let listSelector as ListSelector:
cell = tableView.dequeueReusableCell(withIdentifier: "Select", for: indexPath)
let selectCell = cell as! SelectTableViewCell
selectCell.nameLabel?.text = listSelector.name
selectCell.valueLabel?.text = listSelector.currentOptionName()
case let switchControl as Switch:
cell = tableView.dequeueReusableCell(withIdentifier: "Toggle", for: indexPath)
let toggleCell = cell as! ToggleTableViewCell
toggleCell.nameLabel?.text = switchControl.name
toggleCell.switchView?.isOn = switchControl.currentState
case let rangeControl as RangeSelector:
cell = tableView.dequeueReusableCell(withIdentifier: "Range", for: indexPath)
let rangeCell = cell as! RangeTableViewCell
rangeCell.nameLabel?.text = rangeControl.name
rangeCell.valueLabel?.text = "\(Int(rangeControl.current))º"
rangeCell.slider.maximumValue = Float(rangeControl.max)
rangeCell.slider.minimumValue = Float(rangeControl.min) as Float
rangeCell.slider.setValue(Float(rangeControl.current), animated: false)
default:
cell = UITableViewCell()
print("Unknown menuItem \(menuItem) at \(indexPath)")
}
return cell
}
// MARK: - Save Settings
@IBAction func rangeUpdated(_ sender: UISlider) {
let switchPosition = sender.convert(CGPoint.zero, to: tableView)
if let indexPath = tableView.indexPathForRow(at: switchPosition),
let menuItem = menus![indexPath] as? RangeSelector {
menuItem.current = Int(sender.value)
}
}
@IBAction func toggleChanged(_ sender: UISwitch) {
let switchPosition = sender.convert(CGPoint.zero, to: tableView)
if let indexPath = tableView.indexPathForRow(at: switchPosition),
let menuItem = menus![indexPath] as? Switch {
menuItem.currentState = sender.isOn
}
}
// MARK: - Navigation
@IBAction func unwindToSettings(sender: UIStoryboardSegue){
//if let _ = sender.source as? OptionViewController,
//}
if let selectedIndexPath = tableView.indexPathForSelectedRow {
tableView.reloadRows(at: [selectedIndexPath], with: .none)
}
}
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let destinationController = segue.destination as? OptionViewController,
let listSelector = sender as? SelectTableViewCell,
let indexPath = tableView.indexPath(for: listSelector) {
destinationController.menuItem = menus![indexPath] as? ListSelector
destinationController.title = destinationController.menuItem?.name
}
}
}
| b452de68e8dcf5967e56ea55d3119d2a | 37.620968 | 113 | 0.674253 | false | false | false | false |
guowilling/iOSExamples | refs/heads/master | Swift/Socket/SocketClient/Pods/ProtocolBuffers-Swift/Source/GeneratedMessage.swift | mit | 2 | // 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 protocol GeneratedMessageProtocol: ProtocolBuffersMessage {
// associatedtype BuilderType:GeneratedMessageBuilderProtocol
static func parseFrom(data: Data) throws -> Self
static func parseFrom(data: Data, extensionRegistry:ExtensionRegistry) throws -> Self
static func parseFrom(inputStream:InputStream) throws -> Self
static func parseFrom(inputStream:InputStream, extensionRegistry:ExtensionRegistry) throws -> Self
static func parseFrom(codedInputStream:CodedInputStream) throws -> Self
static func parseFrom(codedInputStream:CodedInputStream, extensionRegistry:ExtensionRegistry) throws -> Self
// subscript(key: String) -> Any? { get }
}
public protocol GeneratedEnum:RawRepresentable, CustomDebugStringConvertible, CustomStringConvertible, Hashable {
func toString() -> String
static func fromString(_ str:String) throws -> Self
}
public protocol GeneratedMessageBuilderProtocol: ProtocolBuffersMessageBuilder {
subscript(key: String) -> Any? { get set }
}
open class GeneratedMessage:AbstractProtocolBuffersMessage
{
public var memoizedSerializedSize:Int32 = -1
required public init()
{
super.init()
self.unknownFields = UnknownFieldSet(fields: [:])
}
//Override
open class func className() -> String
{
return "GeneratedMessage"
}
open func className() -> String
{
return "GeneratedMessage"
}
open override class func classBuilder() -> ProtocolBuffersMessageBuilder
{
return GeneratedMessageBuilder()
}
open override func classBuilder() -> ProtocolBuffersMessageBuilder
{
return GeneratedMessageBuilder()
}
//
}
open class GeneratedMessageBuilder:AbstractProtocolBuffersMessageBuilder
{
open var internalGetResult:GeneratedMessage
{
get
{
return GeneratedMessage()
}
}
override open var unknownFields:UnknownFieldSet
{
get
{
return internalGetResult.unknownFields
}
set (fields)
{
internalGetResult.unknownFields = fields
}
}
public func checkInitialized() throws
{
let result = internalGetResult
guard result.isInitialized() else
{
throw ProtocolBuffersError.invalidProtocolBuffer("Uninitialized Message")
}
}
public func checkInitializedParsed() throws
{
let result = internalGetResult
guard result.isInitialized() else
{
throw ProtocolBuffersError.invalidProtocolBuffer("Uninitialized Message")
}
}
override open func isInitialized() -> Bool
{
return internalGetResult.isInitialized()
}
@discardableResult
override open func merge(unknownField: UnknownFieldSet) throws -> Self
{
let result:GeneratedMessage = internalGetResult
result.unknownFields = try UnknownFieldSet.builderWithUnknownFields(copyFrom: result.unknownFields).merge(unknownFields: unknownField).build()
return self
}
public func parse(codedInputStream:CodedInputStream ,unknownFields:UnknownFieldSet.Builder, extensionRegistry:ExtensionRegistry, tag:Int32) throws -> Bool {
return try unknownFields.mergeFieldFrom(tag: tag, input:codedInputStream)
}
}
extension GeneratedMessage:CustomDebugStringConvertible {
public var debugDescription:String {
return description
}
}
extension GeneratedMessage:CustomStringConvertible {
public var description:String {
get {
var output:String = ""
output += try! getDescription(indent: "")
return output
}
}
}
extension GeneratedMessageBuilder:CustomDebugStringConvertible {
public var debugDescription:String {
return internalGetResult.description
}
}
extension GeneratedMessageBuilder:CustomStringConvertible {
public var description:String {
get {
return internalGetResult.description
}
}
}
| 28098d429ad0be19acf38134095ec869 | 29.551282 | 160 | 0.695132 | false | false | false | false |
Bing0/ThroughWall | refs/heads/master | ThroughWall/RuleListTableViewController.swift | gpl-3.0 | 1 | //
// RuleListTableViewController.swift
// ThroughWall
//
// Created by Bin on 30/03/2017.
// Copyright © 2017 Wu Bin. All rights reserved.
//
import UIKit
class RuleListTableViewController: UITableViewController, UISearchResultsUpdating, UISearchControllerDelegate, UISearchBarDelegate {
var ruleItems = [[String]]()
var rewriteItems = [[String]]()
var filteredRuleItems = [[String]]()
var filteredRewriteItems = [[String]]()
var selectedIndex = -1
let searchController = UISearchController(searchResultsController: nil)
var filterText = ""
override func viewDidLoad() {
super.viewDidLoad()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
navigationController?.navigationBar.barTintColor = topUIColor
tableView.tableFooterView = UIView()
tableView.backgroundColor = UIColor.groupTableViewBackground
// self.edgesForExtendedLayout = UIRectEdge.all
self.extendedLayoutIncludesOpaqueBars = true
NotificationCenter.default.addObserver(self, selector: #selector(RuleListTableViewController.ruleSaved(notification:)), name: NSNotification.Name(rawValue: kRuleSaved), object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(RuleListTableViewController.ruleDeleted(notification:)), name: NSNotification.Name(rawValue: kRuleDeleted), object: nil)
searchController.searchResultsUpdater = self
searchController.dimsBackgroundDuringPresentation = false
searchController.delegate = self
// searchController.searchBar.scopeButtonTitles = ["All", "Rewrite", "Direct", "Proxy", "Reject"]
// searchController.searchBar.delegate = self
tableView.tableHeaderView = searchController.searchBar
definesPresentationContext = true
}
override var preferredStatusBarStyle: UIStatusBarStyle {
return .lightContent
}
deinit {
NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: kRuleSaved), object: nil)
NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: kRuleDeleted), object: nil)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
reloadItemsFromDisk()
}
func reloadItemsFromDisk() {
ruleItems = Rule.sharedInstance.getCurrentRuleItems()
rewriteItems = Rule.sharedInstance.getCurrentRewriteItems()
applyFilter(withText: filterText)
tableView.reloadData()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@objc func ruleSaved(notification: Notification) {
if let value = notification.userInfo?["ruleItem"] as? [String] {
if selectedIndex == -1 {
ruleItems.insert(value, at: 0)
} else {
ruleItems[selectedIndex - rewriteItems.count] = value
}
let content = makeRulesIntoContent()
RuleFileUpdateController().saveToCustomRuleFile(withContent: content)
} else if let value = notification.userInfo?["rewriteItem"] as? [String] {
if selectedIndex == -1 {
rewriteItems.insert(value, at: 0)
} else {
rewriteItems[selectedIndex] = value
}
let content = makeRulesIntoContent()
RuleFileUpdateController().saveToCustomRuleFile(withContent: content)
}
reloadItemsFromDisk()
}
@objc func ruleDeleted(notification: Notification) {
ruleDeleted()
}
func ruleDeleted() {
if selectedIndex == -1 {
return
}
if selectedIndex < rewriteItems.count {
rewriteItems.remove(at: selectedIndex)
} else {
ruleItems.remove(at: selectedIndex - rewriteItems.count)
}
selectedIndex = -1
let content = makeRulesIntoContent()
RuleFileUpdateController().saveToCustomRuleFile(withContent: content)
reloadItemsFromDisk()
}
func makeRulesIntoContent() -> String {
var content = "[URL Rewrite]\n"
for rewriteItem in rewriteItems {
let tmp = rewriteItem.joined(separator: " ")
content.append(tmp + "\n")
}
content.append("[Rule]\n")
for ruleItem in ruleItems {
let tmp = ruleItem.joined(separator: ",")
content.append(tmp + "\n")
}
return content
}
func applyFilter(withText text: String) {
filteredRuleItems.removeAll()
filteredRewriteItems.removeAll()
for ruleItem in ruleItems {
for item in ruleItem {
if item.lowercased().contains(text) {
filteredRuleItems.append(ruleItem)
break
}
}
}
for rewriteItem in rewriteItems {
for item in rewriteItem {
if item.lowercased().contains(text) {
filteredRewriteItems.append(rewriteItem)
break
}
}
}
tableView.reloadData()
}
// MARK: - UISearchControllerDelegate
// func willDismissSearchController(_ searchController: UISearchController) {
// let indexPath = IndexPath(row: 0, section: 0)
// tableView.scrollToRow(at: indexPath, at: .top, animated: false)
// }
// MARK: - UISearchResultsUpdating
func updateSearchResults(for searchController: UISearchController) {
if let text = searchController.searchBar.text {
filterText = text.lowercased()
applyFilter(withText: text.lowercased())
}
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
if searchController.isActive {
return filteredRewriteItems.count + filteredRuleItems.count
}
return rewriteItems.count + ruleItems.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "listCell", for: indexPath)
if searchController.isActive {
if indexPath.row < filteredRewriteItems.count {
let item = filteredRewriteItems[indexPath.row]
cell.textLabel?.attributedText = usingFilterTextTohightlight(item[0])
cell.detailTextLabel?.attributedText = usingFilterTextTohightlight(item[1])
} else {
let item = filteredRuleItems[indexPath.row - filteredRewriteItems.count]
// cell.textLabel?.attributedText = usingFilterTextTohightlight(item[1])
//
// //In fact, usingFilterTextTohightlight doesn't work now
// cell.detailTextLabel?.attributedText = usingFilterTextTohightlight(attributedText: makeAttributeDescription(withMatchRule: item[0], andProxyRule: item[2]))
cell.textLabel?.attributedText = nil
cell.detailTextLabel?.attributedText = nil
if item.count >= 3 {
cell.textLabel?.attributedText = usingFilterTextTohightlight(item[1])
cell.detailTextLabel?.attributedText = usingFilterTextTohightlight(attributedText: makeAttributeDescription(withMatchRule: item[0], andProxyRule: item[2]))
} else {
cell.textLabel?.text = ""
cell.detailTextLabel?.attributedText = usingFilterTextTohightlight(attributedText: makeAttributeDescription(withMatchRule: item[0], andProxyRule: item[1]))
}
}
} else {
if indexPath.row < rewriteItems.count {
let item = rewriteItems[indexPath.row]
cell.textLabel?.attributedText = nil
cell.detailTextLabel?.attributedText = nil
cell.textLabel?.text = item[0]
cell.detailTextLabel?.text = item[1]
} else {
let item = ruleItems[indexPath.row - rewriteItems.count]
cell.textLabel?.attributedText = nil
cell.detailTextLabel?.attributedText = nil
if item.count >= 3 {
cell.textLabel?.text = item[1]
cell.detailTextLabel?.attributedText = makeAttributeDescription(withMatchRule: item[0], andProxyRule: item[2])
} else {
cell.textLabel?.text = ""
cell.detailTextLabel?.attributedText = makeAttributeDescription(withMatchRule: item[0], andProxyRule: item[1])
}
}
}
return cell
}
func makeAttributeDescription(withMatchRule matchRule: String, andProxyRule proxyRule: String) -> NSAttributedString {
let attributeDescription = NSMutableAttributedString(string: "")
let attributeRequestType = NSAttributedString(string: matchRule, attributes: [NSAttributedStringKey.foregroundColor: UIColor.lightGray])
attributeDescription.append(attributeRequestType)
attributeDescription.append(NSAttributedString(string: " "))
switch proxyRule.lowercased() {
case "direct":
let attributeRule = NSAttributedString(string: proxyRule, attributes: [NSAttributedStringKey.foregroundColor: UIColor.init(red: 0.24, green: 0.545, blue: 0.153, alpha: 1.0)])
attributeDescription.append(attributeRule)
case "proxy":
let attributeRule = NSAttributedString(string: proxyRule, attributes: [NSAttributedStringKey.foregroundColor: UIColor.orange])
attributeDescription.append(attributeRule)
default:
let attributeRule = NSAttributedString(string: proxyRule, attributes: [NSAttributedStringKey.foregroundColor: UIColor.red])
attributeDescription.append(attributeRule)
}
return attributeDescription
}
func usingFilterTextTohightlight(_ text: String) -> NSAttributedString {
let attributedText = NSAttributedString(string: text)
return usingFilterTextTohightlight(attributedText: attributedText)
}
func usingFilterTextTohightlight(attributedText attributeText: NSAttributedString) -> NSAttributedString {
let mutableAttText = NSMutableAttributedString(attributedString: attributeText)
let text = attributeText.string
for range in searchRangesOfFilterText(inString: text) {
mutableAttText.addAttribute(.backgroundColor, value: UIColor.yellow, range: NSRange(range, in: text))
}
return mutableAttText
}
func searchRangesOfFilterText(inString str: String) -> [Range<String.Index>] {
var endRange = str.endIndex
var ranges = [Range<String.Index>]()
while true {
let subString = str[..<endRange]
if let range = subString.range(of: filterText, options: [.literal, .backwards]) {
ranges.append(range)
endRange = range.lowerBound
} else {
break
}
}
return ranges
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: false)
selectedIndex = indexPath.row
performSegue(withIdentifier: "showRuleDetail", sender: nil)
}
override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
return true
}
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
let alertController = UIAlertController(title: "Delete Rule", message: nil, preferredStyle: .alert)
let deleteAction = UIAlertAction(title: "Delete", style: .destructive, handler: { (_) in
DispatchQueue.main.async {
if self.searchController.isActive {
if indexPath.row < self.filteredRewriteItems.count {
let item = self.filteredRewriteItems[indexPath.row]
let index = self.rewriteItems.index(where: { strs -> Bool in
return strs == item
})
self.selectedIndex = index!
} else {
let item = self.filteredRuleItems[indexPath.row - self.filteredRewriteItems.count]
let index = self.ruleItems.index(where: { strs -> Bool in
return strs == item
})
self.selectedIndex = index! + self.rewriteItems.count
}
} else {
self.selectedIndex = indexPath.row
}
self.ruleDeleted()
}
})
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)
alertController.addAction(cancelAction)
alertController.addAction(deleteAction)
self.present(alertController, animated: true, completion: nil)
}
}
@IBAction func addNewRule(_ sender: UIBarButtonItem) {
selectedIndex = -1
performSegue(withIdentifier: "showRuleDetail", sender: nil)
}
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
if segue.identifier == "showRuleDetail" {
if let desti = segue.destination as? RuleDetailTableViewController {
if selectedIndex != -1 {
let item: [String]
if searchController.isActive {
if selectedIndex < filteredRewriteItems.count {
item = filteredRewriteItems[selectedIndex]
desti.rewriteItem = item
} else {
item = filteredRuleItems[selectedIndex - filteredRewriteItems.count]
desti.ruleItem = item
}
} else {
if selectedIndex < rewriteItems.count {
item = rewriteItems[selectedIndex]
desti.rewriteItem = item
} else {
item = ruleItems[selectedIndex - rewriteItems.count]
desti.ruleItem = item
}
}
desti.showDelete = true
} else {
desti.showDelete = false
}
}
}
}
}
| 99701446993982d4b56c5769bfa3a43d | 39.02799 | 193 | 0.613883 | false | false | false | false |
i-schuetz/tableview_infinite | refs/heads/master | AsyncTableView/ViewController.swift | apache-2.0 | 1 | //
// ViewController.swift
// AsyncTableView
//
// Created by ischuetz on 27/06/2014.
// Copyright (c) 2014 ivanschuetz. All rights reserved.
//
import UIKit
struct MyItem {
let name: String
init(name: String) {
self.name = name
}
}
class MyDataProvider {
static var instance: MyDataProvider {
return MyDataProvider()
}
func requestData(offset: Int, size: Int, listener: [MyItem] -> Void) {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {
// simulate delay
sleep(2)
// generate items
let items = (offset...(offset + size)).map {
MyItem(name: "Item \($0)")
}
// call listener in main thread
dispatch_async(dispatch_get_main_queue()) {
listener(items)
}
}
}
}
class ViewController: UITableViewController {
@IBOutlet var tableViewFooter: MyFooter!
private let pageSize = 20
private var items: [MyItem] = []
private var loading = false {
didSet {
tableViewFooter.hidden = !loading
}
}
override func scrollViewDidScroll(scrollView: UIScrollView) {
let currentOffset = scrollView.contentOffset.y
let maximumOffset = scrollView.contentSize.height - scrollView.frame.size.height
if (maximumOffset - currentOffset) <= 40 {
loadSegment(items.count, size: pageSize)
}
}
override func viewDidLoad() {
super.viewDidLoad()
tableViewFooter.hidden = true
loadSegment(0, size: pageSize)
}
func loadSegment(offset: Int, size: Int) {
if (!loading) {
loading = true
MyDataProvider.instance.requestData(offset, size: size) {[weak self] items in
for item in items {
self?.items.append(item)
}
self?.tableView.reloadData()
self?.loading = false
}
}
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return items.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath)
let item = items[indexPath.row]
cell.textLabel?.text = item.name
return cell
}
}
| cf81c350ea2c27de5ee9d805c27f0bd5 | 24.119266 | 118 | 0.565741 | false | false | false | false |
Meru-Interactive/iOSC | refs/heads/master | swiftOSC/Addresses/OSCAddressPattern.swift | mit | 1 | //
// OSCAddressPattern.swift
// SwiftOSC
//
// Created by Devin Roth on 6/26/16.
// Copyright © 2016 Devin Roth Music. All rights reserved.
//
import Foundation
public struct OSCAddressPattern {
//MARK: Properties
public var string: String {
didSet {
if !valid(self.string) {
NSLog("\"\(self.string)\" is an invalid address")
self.string = oldValue
} else {
self.regex = makeRegex(from: self.string)
self.regexPath = makeRegexPath(from: self.regex)
}
}
}
internal var regex = ""
internal var regexPath = ""
internal var data: Data {
get {
var data = self.string.data(using: String.Encoding.utf8)!
//make sure data is base 32 null terminated
var null:UInt8 = 0
for _ in 1...4-data.count%4 {
data.append(&null, count: 1)
}
return data
}
}
//MARK: Initializers
public init(){
self.string = "/"
self.regex = "^/$"
self.regexPath = "^/$"
}
public init(_ addressPattern: String) {
self.string = "/"
self.regex = "^/$"
self.regexPath = "^/$"
if valid(addressPattern) {
self.string = addressPattern
self.regex = makeRegex(from: self.string)
self.regex = makeRegexPath(from: self.regex)
}
}
//MARK: Methods
internal func makeRegex(from addressPattern: String) -> String {
var addressPattern = addressPattern
//escapes characters: \ + ( ) . ^ $ |
addressPattern = addressPattern.replacingOccurrences(of: "\\", with: "\\\\")
addressPattern = addressPattern.replacingOccurrences(of: "+", with: "\\+")
addressPattern = addressPattern.replacingOccurrences(of: "(", with: "\\(")
addressPattern = addressPattern.replacingOccurrences(of: ")", with: "\\)")
addressPattern = addressPattern.replacingOccurrences(of: ".", with: "\\.")
addressPattern = addressPattern.replacingOccurrences(of: "^", with: "\\^")
addressPattern = addressPattern.replacingOccurrences(of: "$", with: "\\$")
addressPattern = addressPattern.replacingOccurrences(of: "|", with: "\\|")
//replace characters with regex equivalents
addressPattern = addressPattern.replacingOccurrences(of: "*", with: "[^/]*")
addressPattern = addressPattern.replacingOccurrences(of: "//", with: ".*/")
addressPattern = addressPattern.replacingOccurrences(of: "?", with: "[^/]")
addressPattern = addressPattern.replacingOccurrences(of: "[!", with: "[^")
addressPattern = addressPattern.replacingOccurrences(of: "{", with: "(")
addressPattern = addressPattern.replacingOccurrences(of: "}", with: ")")
addressPattern = addressPattern.replacingOccurrences(of: ",", with: "|")
addressPattern = "^" + addressPattern //matches beginning of string
addressPattern.append("$") //matches end of string
return addressPattern
}
internal func makeRegexPath(from regex: String) -> String {
var regex = regex
regex = String(regex.characters.dropLast())
regex = String(regex.characters.dropFirst())
regex = String(regex.characters.dropFirst())
var components = regex.components(separatedBy: "/")
var regexContainer = "^/$|"
for x in 0 ..< components.count {
regexContainer += "^"
for y in 0 ... x {
regexContainer += "/" + components[y]
}
regexContainer += "$|"
}
regexContainer = String(regexContainer.characters.dropLast())
return regexContainer
}
internal func valid(_ address: String) ->Bool {
//no empty strings
if address == "" {
return false
}
//must start with "/"
if address.characters.first != "/" {
return false
}
//no more than two "/" in a row
if address.range(of: "/{3,}", options: .regularExpression) != nil {
return false
}
//no spaces
if address.range(of: "\\s", options: .regularExpression) != nil {
return false
}
//[ must be closed, no invalid characters inside
if address.range(of: "\\[(?![^\\[\\{\\},?\\*/]+\\])", options: .regularExpression) != nil {
return false
}
var open = address.components(separatedBy: "[").count
var close = address.components(separatedBy: "]").count
if open != close {
return false
}
//{ must be closed, no invalid characters inside
if address.range(of: "\\{(?![^\\{\\[\\]?\\*/]+\\})", options: .regularExpression) != nil {
return false
}
open = address.components(separatedBy: "{").count
close = address.components(separatedBy: "}").count
if open != close {
return false
}
//"," only inside {}
if address.range(of: ",(?![^\\{\\[\\]?\\*/]+\\})", options: .regularExpression) != nil {
return false
}
if address.range(of: ",(?<!\\{[^\\{\\[\\]?\\*/]+)", options: .regularExpression) != nil {
return false
}
//passed all the tests
return true
}
public func matches(_ address: OSCAddress)->Bool{
if address.string.range(of: self.regex, options: .regularExpression) == nil {
return false
} else {
return true
}
}
public func matches(path: OSCAddress)->Bool{
if path.string.range(of: self.regexPath, options: .regularExpression) == nil {
return false
} else {
return true
}
}
}
| acf17544c0c66887750468a020729993 | 33.196629 | 99 | 0.528503 | false | false | false | false |
lethianqt94/Swift-DropdownMenu-ParallaxTableView | refs/heads/master | ModuleDemo/ModuleDemo/Classes/AppDelegate/AppDelegate.swift | mit | 1 | //
// AppDelegate.swift
// ModuleDemo
//
// Created by Le Thi An on 3/1/16.
// Copyright © 2016 Le Thi An. All rights reserved.
//
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
var startVC: MenuVC?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
var nav:UINavigationController?
startVC = MenuVC()
window = UIWindow()
// window = UIWindow(frame: CGRect(x: 0, y: 0, width: UIScreen.mainScreen().bounds.size.width, height: UIScreen.mainScreen().bounds.size.height))
// window?.backgroundColor = UIColor.clearColor()
nav = UINavigationController(rootViewController: startVC!)
window!.rootViewController = nav
window?.makeKeyAndVisible()
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.gg.ModuleDemo" 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("ModuleDemo", 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()
}
}
}
}
| c044073be99b3934ab5186036ee1aa12 | 52.617886 | 291 | 0.711296 | false | false | false | false |
CodaFi/swift | refs/heads/main | test/SILGen/function_conversion_se0110.swift | apache-2.0 | 25 |
// RUN: %target-swift-emit-silgen -module-name function_conversion -primary-file %s | %FileCheck %s
// Check SILGen against various FunctionConversionExprs emitted by Sema.
// SE-0110 allows 'tuple splat' in a few narrow cases. Make sure SILGen supports them.
func takesTwo(_: ((Int, Int)) -> ()) {}
func givesTwo(_ fn: (Any, Any) -> ()) {
takesTwo(fn)
}
// reabstraction thunk helper from @callee_guaranteed (@in_guaranteed Any, @in_guaranteed Any) -> () to @escaping @callee_guaranteed (@unowned Swift.Int, @unowned Swift.Int) -> ()
// CHECK-LABEL: sil shared [transparent] [serializable] [reabstraction_thunk] [ossa] @$sypypIgnn_S2iIegyy_TR : $@convention(thin) (Int, Int, @noescape @callee_guaranteed (@in_guaranteed Any, @in_guaranteed Any) -> ()) -> ()
func takesTwoGeneric<T>(_: (T) -> ()) -> T {}
func givesTwoGeneric(_ fn: (Int, Int) -> ()) {
_ = takesTwoGeneric(fn)
}
// reabstraction thunk helper from @callee_guaranteed (@unowned Swift.Int, @unowned Swift.Int) -> () to @escaping @callee_guaranteed (@in_guaranteed (Swift.Int, Swift.Int)) -> ()
// CHECK-LABEL: sil shared [transparent] [serializable] [reabstraction_thunk] [ossa] @$sS2iIgyy_Si_SitIegn_TR : $@convention(thin) (@in_guaranteed (Int, Int), @noescape @callee_guaranteed (Int, Int) -> ()) -> ()
// Use a silly trick to bind T := (Int, Int) here
func givesTwoGenericAny(_ fn: (Any, Any) -> ()) -> (Int, Int) {
return takesTwoGeneric(fn)
}
func givesNoneGeneric(_ fn: () -> ()) {
_ = takesTwoGeneric(fn)
}
// reabstraction thunk helper from @callee_guaranteed () -> () to @escaping @callee_guaranteed (@in_guaranteed ()) -> ()
// CHECK-LABEL: sil shared [transparent] [serializable] [reabstraction_thunk] [ossa] @$sIg_ytIegn_TR : $@convention(thin) (@in_guaranteed (), @noescape @callee_guaranteed () -> ()) -> ()
// "Tuple splat" still works if there are __owned parameters.
// Make sure the memory management is correct also.
// CHECK-LABEL: sil hidden [ossa] @$s19function_conversion17takesTwoAnyObjectyyyyXl_yXlt_tXEF : $@convention(thin) (@noescape @callee_guaranteed (@guaranteed AnyObject, @guaranteed AnyObject) -> ()) -> ()
func takesTwoAnyObject(_: ((AnyObject, AnyObject)) -> ()) {}
// CHECK-LABEL: sil hidden [ossa] @$s19function_conversion22givesTwoAnyObjectOwnedyyyyXln_yXlntXEF : $@convention(thin) (@noescape @callee_guaranteed (@owned AnyObject, @owned AnyObject) -> ()) -> ()
func givesTwoAnyObjectOwned(_ fn: (__owned AnyObject, __owned AnyObject) -> ()) {
takesTwoAnyObject(fn)
}
// CHECK-LABEL: sil shared [transparent] [serializable] [reabstraction_thunk] [ossa] @$syXlyXlIgxx_yXlyXlIeggg_TR : $@convention(thin) (@guaranteed AnyObject, @guaranteed AnyObject, @noescape @callee_guaranteed (@owned AnyObject, @owned AnyObject) -> ()) -> () {
// CHECK: bb0(%0 : @guaranteed $AnyObject, %1 : @guaranteed $AnyObject, %2 : $@noescape @callee_guaranteed (@owned AnyObject, @owned AnyObject) -> ()):
// CHECK-NEXT: [[FIRST:%.*]] = copy_value %0
// CHECK-NEXT: [[SECOND:%.*]] = copy_value %1
// CHECK-NEXT: apply %2([[FIRST]], [[SECOND]]) : $@noescape @callee_guaranteed (@owned AnyObject, @owned AnyObject) -> ()
// CHECK-NEXT: [[RESULT:%.*]] = tuple ()
// CHECK-NEXT: return [[RESULT]] : $()
// CHECK-NEXT: }
| c846fac955db5ce0c9f906025c397851 | 53.677966 | 262 | 0.676069 | false | false | false | false |
ephread/Instructions | refs/heads/main | Examples/Example/Sources/Core/Custom Views/CustomCoachMarkArrowView.swift | mit | 1 | // Copyright (c) 2015-present Frédéric Maquin <[email protected]> and contributors.
// Licensed under the terms of the MIT License.
import UIKit
import Instructions
// Custom coach mark body (with the secret-like arrow)
internal class CustomCoachMarkArrowView: UIView, CoachMarkArrowView {
// MARK: - Internal properties
var topPlateImage = UIImage(named: "coach-mark-top-plate")
var bottomPlateImage = UIImage(named: "coach-mark-bottom-plate")
var plate = UIImageView()
var isHighlighted: Bool = false
// MARK: - Private properties
private var column = UIView()
// MARK: - Initialization
init(orientation: CoachMarkArrowOrientation) {
super.init(frame: CGRect.zero)
if orientation == .top {
self.plate.image = topPlateImage
} else {
self.plate.image = bottomPlateImage
}
self.translatesAutoresizingMaskIntoConstraints = false
self.column.translatesAutoresizingMaskIntoConstraints = false
self.plate.translatesAutoresizingMaskIntoConstraints = false
self.addSubview(plate)
self.addSubview(column)
plate.backgroundColor = UIColor.clear
column.backgroundColor = UIColor.white
plate.fillSuperviewHorizontally()
NSLayoutConstraint.activate([
column.widthAnchor.constraint(equalToConstant: 3),
column.centerXAnchor.constraint(equalTo: centerXAnchor)
])
if orientation == .top {
NSLayoutConstraint.activate(
NSLayoutConstraint.constraints(
withVisualFormat: "V:|[plate(==5)][column(==10)]|",
options: NSLayoutConstraint.FormatOptions(rawValue: 0),
metrics: nil,
views: ["plate": plate, "column": column]
)
)
} else {
NSLayoutConstraint.activate(
NSLayoutConstraint.constraints(
withVisualFormat: "V:|[column(==10)][plate(==5)]|",
options: NSLayoutConstraint.FormatOptions(rawValue: 0),
metrics: nil,
views: ["plate": plate, "column": column]
)
)
}
}
required init(coder aDecoder: NSCoder) {
fatalError("This class does not support NSCoding.")
}
}
| 3c655782dd3e7cc4754add418ccecd30 | 33.26087 | 82 | 0.60956 | false | false | false | false |
dduan/swift | refs/heads/master | benchmark/single-source/RGBHistogram.swift | apache-2.0 | 1 | //===--- RGBHistogram.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 http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
// Performance benchmark for creating RGB histograms
// rdar://problem/18539486
//
// Description:
// Create a sorted sparse RGB histogram from an array of 300 RGB values.
import Foundation
import TestsUtils
@inline(never)
public func run_RGBHistogram(N: Int) {
var histogram = [(key: rrggbb_t, value: Int)]()
for _ in 1...100*N {
histogram = createSortedSparseRGBHistogram(samples)
if !isCorrectHistogram(histogram) {
break
}
}
CheckResults(isCorrectHistogram(histogram),
"Incorrect results in histogram")
}
typealias rrggbb_t = UInt32
let samples: [rrggbb_t] = [
0x00808080, 0x00808080, 0x00808080, 0x00808080, 0x00808080, 0x00808080,
0x00FF0000, 0x00FF0000, 0x000000FF, 0x000000FF, 0x000000FF, 0x000000FF,
0x00000000, 0x00555555, 0x00AAAAAA, 0x00FFFFFF, 0x00AAAAAA, 0x00FFFFFF,
0x00808080, 0x00808080, 0x00808080, 0x00808080, 0x00808080, 0x00808080,
0x00FF0000, 0x00FF0000, 0x000000FF, 0x000000FF, 0x000000FF, 0x000000FF,
0x00000000, 0x00555555, 0x00AAAAAA, 0x00FFFFFF, 0x00AAAAAA, 0x00FFFFFF,
0x00808080, 0x00808080, 0x00808080, 0x00808080, 0x00808080, 0x00808080,
0x00FF0000, 0x00FF0000, 0x000000FF, 0x000000FF, 0x000000FF, 0x000000FF,
0x00000000, 0x00555555, 0x00AAAAAA, 0x00FFFFFF, 0x00AAAAAA, 0x00FFFFFF,
0x00808080, 0x00808080, 0x00808080, 0x00808080, 0x00808080, 0x00808080,
0x00FF0000, 0x00FF0000, 0x000000FF, 0x000000FF, 0x000000FF, 0x000000FF,
0x00000000, 0x00555555, 0x00AAAAAA, 0x00FFFFFF, 0x00AAAAAA, 0x00FFFFFF,
0x00808080, 0x00808080, 0x00808080, 0x00808080, 0x00808080, 0x00808080,
0x00FF0000, 0x00FF0000, 0x000000FF, 0x000000FF, 0x000000FF, 0x000000FF,
0x00000000, 0x00555555, 0x00AAAAAA, 0x00FFFFFF, 0x00AAAAAA, 0x00FFFFFF,
0x00808080, 0x00808080, 0x00808080, 0x00808080, 0x00808080, 0x00808080,
0x00FF0000, 0x00FF0000, 0x000000FF, 0x000000FF, 0x000000FF, 0x000000FF,
0x00000000, 0x00555555, 0x00AAAAAA, 0x00FFFFFF, 0x00AAAAAA, 0x00FFFFFF,
0x00808080, 0x00808080, 0x00808080, 0x00808080, 0x00808080, 0x00808080,
0x00FF0000, 0x00FF0000, 0x000000FF, 0x000000FF, 0x000000FF, 0x000000FF,
0x00000000, 0x00555555, 0x00AAAAAA, 0x00FFFFFF, 0x00AAAAAA, 0x00FFFFFF,
0x00808080, 0x00808080, 0x00808080, 0x00808080, 0x00808080, 0x00808080,
0x00FF0000, 0x00FF0000, 0x000000FF, 0x000000FF, 0x000000FF, 0x000000FF,
0x00000000, 0x00555555, 0x00AAAAAA, 0x00FFFFFF, 0x00AAAAAA, 0x00FFFFFF,
0x00808080, 0x00808080, 0x00808080, 0x00808080, 0x00808080, 0x00808080,
0xCCD45FBC, 0xA56F39E4, 0x8C08DBA7, 0xDA4413D7, 0x43926C6B, 0x592975FE,
0xC77E47ED, 0xB28F427D, 0x90D7C464, 0x805A003A, 0xAB79B390, 0x49D859B3,
0x2419213A, 0x69E8C61D, 0xC4BE948F, 0x896CC6D0, 0xE4F3DFF1, 0x466B68FA,
0xC8084E2A, 0x3FC1F2C4, 0x0E0D47F4, 0xB268BFE6, 0x9F990E6A, 0x7389F2F8,
0x0720FD81, 0x65388005, 0xD8307612, 0xEC75B9B0, 0xB0C51360, 0x29647EB4,
0x6E8B02E6, 0xEFE9F0F4, 0xFEF0EB89, 0x41BBD587, 0xCD19E510, 0x6A710BBD,
0xFF146228, 0xFB34AD0C, 0x2AEB5588, 0x71993821, 0x9FC8CA5C, 0xF99E969B,
0x8DF78241, 0x21ADFB7C, 0x4DE5E465, 0x0C171D2F, 0x2C08CECF, 0x3318440A,
0xEC8F8D1C, 0x6CAFD68E, 0xCA35F571, 0x68A37E1A, 0x3047F87F, 0x50CC39DE,
0x776CF5CB, 0x75DC4595, 0x77E32288, 0x14899C0D, 0x14835CF6, 0x0A732F76,
0xA4B05790, 0x34CBED42, 0x5A6964CE, 0xEA4CA5F7, 0x3DECB0F1, 0x5015D419,
0x84EBC299, 0xC656B381, 0xFA2840C5, 0x618D754E, 0x003B8D96, 0xCE91AA8E,
0xBD9784DB, 0x9372E919, 0xC138BEA6, 0xF0B3E3AD, 0x4E4F60BF, 0xC1598ABE,
0x930873DB, 0x0F029E3A, 0xBEFC0125, 0x10645D6D, 0x1FF93547, 0xA7069CB5,
0xCF0B7E06, 0xE33EDC17, 0x8C5E1F48, 0x2FB345E1, 0x3B0070E0, 0x0421E568,
0xB39A42A0, 0xB935DA8B, 0x281C30F0, 0xB2E48677, 0x277A9A45, 0x52AF9FC6,
0xBBDF4048, 0xC668137A, 0xF39020D1, 0x71BEE810, 0x5F2B3825, 0x25C863FB,
0x876144E8, 0x9B4108C3, 0xF735CB08, 0x8B77DEEC, 0x0185A067, 0xB964F42B,
0xA2EC236B, 0x3C08646F, 0xB514C4BE, 0x37EE9689, 0xACF97317, 0x1EA4F7C6,
0x453A6F13, 0x01C25E42, 0xA052BB3B, 0x71A699CB, 0xC728AE88, 0x128A656F,
0x78F64E55, 0x045967E0, 0xC5DC4125, 0xDA39F6FE, 0x873785B9, 0xB6BB446A,
0xF4F5093F, 0xAF05A4EC, 0xB5DB854B, 0x7ADA6A37, 0x9EA218E3, 0xCCCC9316,
0x86A133F8, 0x8AF47795, 0xCBA235D4, 0xBB9101CC, 0xBCC8C8A3, 0x02BAC911,
0x45C17A8C, 0x896C81FC, 0x4974FA22, 0xEA7CD629, 0x103ED364, 0x4C644503,
0x607F4D9F, 0x9733E55E, 0xA360439D, 0x1DB568FD, 0xB7A5C3A1, 0xBE84492D
]
func isCorrectHistogram(histogram: [(key: rrggbb_t, value: Int)]) -> Bool {
return histogram.count == 157 &&
histogram[0].0 == 0x00808080 && histogram[0].1 == 54 &&
histogram[156].0 == 0x003B8D96 && histogram[156].1 == 1
}
func createSortedSparseRGBHistogram
<S: Sequence where S.Iterator.Element == rrggbb_t>
(samples: S) -> [(key: rrggbb_t, value: Int)] {
var histogram = Dictionary<rrggbb_t, Int>()
for sample in samples {
let i = histogram.index(forKey: sample)
histogram[sample] = ((i != nil) ? histogram[i!].1 : 0) + 1
}
return histogram.sorted() {
if $0.1 == $1.1 {
return $0.0 > $1.0
} else {
return $0.1 > $1.1
}
}
}
class Box<T : Hashable where T : Equatable> : Hashable {
var value: T
init(_ v: T) {
value = v
}
var hashValue : Int {
return value.hashValue
}
}
extension Box : Equatable {
}
func ==<T: Equatable>(lhs: Box<T>, rhs: Box<T>) -> Bool {
return lhs.value == rhs.value
}
func isCorrectHistogramOfObjects(histogram: [(key: Box<rrggbb_t>, value: Box<Int>)]) -> Bool {
return histogram.count == 157 &&
histogram[0].0.value == 0x00808080 && histogram[0].1.value == 54 &&
histogram[156].0.value == 0x003B8D96 && histogram[156].1.value == 1
}
func createSortedSparseRGBHistogramOfObjects
<S: Sequence where S.Iterator.Element == rrggbb_t>
(samples: S) -> [(key: Box<rrggbb_t>, value: Box<Int>)] {
var histogram = Dictionary<Box<rrggbb_t>, Box<Int>>()
for sample in samples {
let boxedSample = Box(sample)
let i = histogram.index(forKey: boxedSample)
histogram[boxedSample] = Box(((i != nil) ? histogram[i!].1.value : 0) + 1)
}
return histogram.sorted() {
if $0.1 == $1.1 {
return $0.0.value > $1.0.value
} else {
return $0.1.value > $1.1.value
}
}
}
@inline(never)
public func run_RGBHistogramOfObjects(N: Int) {
var histogram = [(key: Box<rrggbb_t>, value: Box<Int>)]()
for _ in 1...100*N {
histogram = createSortedSparseRGBHistogramOfObjects(samples)
if !isCorrectHistogramOfObjects(histogram) {
break
}
}
CheckResults(isCorrectHistogramOfObjects(histogram),
"Incorrect results in histogram")
}
| f5b738cb5d3d46f75d010d3844a66013 | 41.55814 | 94 | 0.693716 | false | false | false | false |
TigerWolf/LoginKit | refs/heads/master | LoginKit/AppearanceController.swift | bsd-3-clause | 1 | //
// Appearance.swift
// LoginKit
//
// Created by Kieran Andrews on 14/02/2016.
// Copyright © 2016 CocoaPods. All rights reserved.
//
import UIKit
import SVProgressHUD
public let Appearance = AppearanceController.sharedInstance
open class AppearanceController {
static let sharedInstance = AppearanceController()
open var backgroundColor = UIColor.blue
open var whiteColor = UIColor.white
open var buttonColor = UIColor.red
open var buttonBorderColor = UIColor.white
}
| 9b19b687fa4e22700a37317ff0bfe5b5 | 20.125 | 59 | 0.739645 | false | false | false | false |
miguelgutierrez/Curso-iOS-Swift-Programming-Netmind | refs/heads/master | newsApp 1.7/newsApp/Articulo.swift | mit | 1 | //
// Articulo.swift
// newsApp
//
// Created by Miguel Gutiérrez Moreno on 2/2/15.
// Copyright (c) 2015 MGM. All rights reserved.
//
import Foundation
import CoreData
@objc(Articulo)
class Articulo: NSManagedObject {
// MARK: properties
@NSManaged var fecha: NSDate
@NSManaged var nombre: String
@NSManaged var texto: String
// MARK: métodos de ayuda
class func entityName() -> String {
return "Articulo"
}
class func articulos() -> [Articulo]? {
let request = NSFetchRequest()
let model = StoreNewsApp.defaultStore().model
let entidad = model.entitiesByName[Articulo.entityName()]
request.entity = entidad
let sd = NSSortDescriptor(key: "nombre", ascending: true)
request.sortDescriptors = [sd]
let context = StoreNewsApp.defaultStore().context
var error : NSError?
let result: [AnyObject]?
do {
result = try context.executeFetchRequest(request)
} catch let error1 as NSError {
error = error1
result = nil
}
if result == nil {
NSException.raise(MensajesErrorCoreData.fetchFailed, format: MensajesErrorCoreData.errorFetchObjectFormat, arguments:getVaList([error!]))
return nil
}
else {
return result as? [Articulo]
}
}
}
| 4648b46293f2da255ac0a3dd08a61532 | 24.052632 | 149 | 0.594538 | false | false | false | false |
zhihuitang/Apollo | refs/heads/master | Apollo/DeviceKit.swift | apache-2.0 | 1 | //
// DeviceKit.swift
// Apollo
//
// Created by Zhihui Tang on 2017-09-05.
// Copyright © 2017 Zhihui Tang. All rights reserved.
//
import Foundation
class DeviceKit {
/**
https://stackoverflow.com/questions/31220371/detect-hotspot-enabling-in-ios-with-private-apis
https://stackoverflow.com/questions/30748480/swift-get-devices-ip-address
*/
class func getNetWorkInfo() -> [String:String]? {
var address : String?
var networkInfo = [String:String]()
// Get list of all interfaces on the local machine:
var ifaddr : UnsafeMutablePointer<ifaddrs>?
guard getifaddrs(&ifaddr) == 0 else { return nil }
guard let firstAddr = ifaddr else { return nil }
// For each interface ...
for ifptr in sequence(first: firstAddr, next: { $0.pointee.ifa_next }) {
let interface = ifptr.pointee
// Check for IPv4 or IPv6 interface:
let addrFamily = interface.ifa_addr.pointee.sa_family
if addrFamily == UInt8(AF_INET) || addrFamily == UInt8(AF_INET6) {
// Check interface name:
let name = String(cString: interface.ifa_name)
//print("network name: \(name)")
//if name == "en0" {
// Convert interface address to a human readable string:
var hostname = [CChar](repeating: 0, count: Int(NI_MAXHOST))
getnameinfo(interface.ifa_addr, socklen_t(interface.ifa_addr.pointee.sa_len),
&hostname, socklen_t(hostname.count),
nil, socklen_t(0), NI_NUMERICHOST)
address = String(cString: hostname)
networkInfo[name] = address
//}
}
}
freeifaddrs(ifaddr)
return networkInfo
}
class func getWifiAddr() -> String? {
return getNetWorkInfo()?["en0"]
}
}
| b4b73c97efcf9591df3c4d9e5383097a | 33.288136 | 98 | 0.549184 | false | false | false | false |
rudkx/swift | refs/heads/main | test/decl/var/result_builders.swift | apache-2.0 | 1 | // RUN: %target-typecheck-verify-swift
@resultBuilder // expected-error {{'@resultBuilder' attribute cannot be applied to this declaration}}
var globalBuilder: Int
@resultBuilder // expected-error {{'@resultBuilder' attribute cannot be applied to this declaration}}
func globalBuilderFunction() -> Int { return 0 }
@resultBuilder
struct Maker {} // expected-error {{result builder must provide at least one static 'buildBlock' method}}
@resultBuilder
class Inventor {} // expected-error {{result builder must provide at least one static 'buildBlock' method}}
@Maker // expected-error {{result builder attribute 'Maker' can only be applied to a parameter, function, or computed property}}
typealias typename = Inventor
@Maker // expected-error {{result builder attribute 'Maker' can only be applied to a variable if it defines a getter}}
var global: Int
// FIXME: should this be allowed?
@Maker
var globalWithEmptyImplicitGetter: Int {}
// expected-error@-1 {{missing return in accessor expected to return 'Int'}}
// expected-error@-3 {{result builder attribute 'Maker' can only be applied to a variable if it defines a getter}}
@Maker
var globalWithEmptyExplicitGetter: Int { get {} } // expected-error{{type 'Maker' has no member 'buildBlock'}}
@Maker
var globalWithSingleGetter: Int { 0 } // expected-error {{ype 'Maker' has no member 'buildBlock'}}
@Maker
var globalWithMultiGetter: Int { 0; 0 } // expected-error {{ype 'Maker' has no member 'buildBlock'}}
@Maker
func globalFunction() {} // expected-error {{ype 'Maker' has no member 'buildBlock'}}
@Maker
func globalFunctionWithFunctionParam(fn: () -> ()) {} // expected-error {{ype 'Maker' has no member 'buildBlock'}}
func makerParam(@Maker
fn: () -> ()) {}
// FIXME: these diagnostics are reversed?
func makerParamRedundant(@Maker // expected-error {{only one result builder attribute can be attached to a parameter}}
@Maker // expected-note {{previous result builder specified here}}
fn: () -> ()) {}
func makerParamConflict(@Maker // expected-error {{only one result builder attribute can be attached to a parameter}}
@Inventor // expected-note {{previous result builder specified here}}
fn: () -> ()) {}
func makerParamMissing1(@Missing // expected-error {{unknown attribute 'Missing'}}
@Maker
fn: () -> ()) {}
func makerParamMissing2(@Maker
@Missing // expected-error {{unknown attribute 'Missing'}}
fn: () -> ()) {}
func makerParamExtra(@Maker(5) // expected-error {{result builder attributes cannot have arguments}}
fn: () -> ()) {}
func makerParamAutoclosure(@Maker // expected-error {{result builder attribute 'Maker' cannot be applied to an autoclosure parameter}}
fn: @autoclosure () -> ()) {}
@resultBuilder
struct GenericMaker<T> {} // expected-note {{generic type 'GenericMaker' declared here}} expected-error {{result builder must provide at least one static 'buildBlock' method}}
struct GenericContainer<T> { // expected-note {{generic type 'GenericContainer' declared here}}
@resultBuilder
struct Maker {} // expected-error {{result builder must provide at least one static 'buildBlock' method}}
}
func makeParamUnbound(@GenericMaker // expected-error {{reference to generic type 'GenericMaker' requires arguments}}
fn: () -> ()) {}
func makeParamBound(@GenericMaker<Int>
fn: () -> ()) {}
func makeParamNestedUnbound(@GenericContainer.Maker // expected-error {{reference to generic type 'GenericContainer' requires arguments}}
fn: () -> ()) {}
func makeParamNestedBound(@GenericContainer<Int>.Maker
fn: () -> ()) {}
protocol P { }
@resultBuilder
struct ConstrainedGenericMaker<T: P> {} // expected-error {{result builder must provide at least one static 'buildBlock' method}}
struct WithinGeneric<U> {
func makeParamBoundInContext(@GenericMaker<U> fn: () -> ()) {}
// expected-error@+1{{type 'U' does not conform to protocol 'P'}}
func makeParamBoundInContextBad(@ConstrainedGenericMaker<U>
fn: () -> ()) {}
}
@resultBuilder
struct ValidBuilder1 {
static func buildBlock(_ exprs: Any...) -> Int { return exprs.count }
}
protocol BuilderFuncHelper {}
extension BuilderFuncHelper {
static func buildBlock(_ exprs: Any...) -> Int { return exprs.count }
}
@resultBuilder
struct ValidBuilder2: BuilderFuncHelper {}
class BuilderFuncBase {
static func buildBlock(_ exprs: Any...) -> Int { return exprs.count }
}
@resultBuilder
class ValidBuilder3: BuilderFuncBase {}
@resultBuilder
struct ValidBuilder4 {}
extension ValidBuilder4 {
static func buildBlock(_ exprs: Any...) -> Int { return exprs.count }
}
@resultBuilder
struct ValidBuilder5 {
static func buildBlock() -> Int { 0 }
}
@resultBuilder
struct InvalidBuilder1 {} // expected-error {{result builder must provide at least one static 'buildBlock' method}}
@resultBuilder
struct InvalidBuilder2 { // expected-error {{result builder must provide at least one static 'buildBlock' method}}
func buildBlock(_ exprs: Any...) -> Int { return exprs.count } // expected-note {{did you mean to make instance method 'buildBlock' static?}} {{3-3=static }}
}
@resultBuilder
struct InvalidBuilder3 { // expected-error {{result builder must provide at least one static 'buildBlock' method}}
var buildBlock: (Any...) -> Int = { return $0.count } // expected-note {{potential match 'buildBlock' is not a static method}}
}
@resultBuilder
struct InvalidBuilder4 {} // expected-error {{result builder must provide at least one static 'buildBlock' method}}
extension InvalidBuilder4 {
func buildBlock(_ exprs: Any...) -> Int { return exprs.count } // expected-note {{did you mean to make instance method 'buildBlock' static?}} {{3-3=static }}
}
protocol InvalidBuilderHelper {}
extension InvalidBuilderHelper {
func buildBlock(_ exprs: Any...) -> Int { return exprs.count } // expected-note {{potential match 'buildBlock' is not a static method}}
}
@resultBuilder
struct InvalidBuilder5: InvalidBuilderHelper {} // expected-error {{result builder must provide at least one static 'buildBlock' method}}
@resultBuilder
struct InvalidBuilder6 { // expected-error {{result builder must provide at least one static 'buildBlock' method}}
static var buildBlock: Int = 0 // expected-note {{potential match 'buildBlock' is not a static method}}
}
struct Callable {
func callAsFunction(_ exprs: Any...) -> Int { return exprs.count }
}
@resultBuilder
struct InvalidBuilder7 { // expected-error {{result builder must provide at least one static 'buildBlock' method}}
static var buildBlock = Callable() // expected-note {{potential match 'buildBlock' is not a static method}}
}
class BuilderVarBase {
static var buildBlock: (Any...) -> Int = { return $0.count } // expected-note {{potential match 'buildBlock' is not a static method}}
}
@resultBuilder
class InvalidBuilder8: BuilderVarBase {} // expected-error {{result builder must provide at least one static 'buildBlock' method}}
protocol BuilderVarHelper {}
extension BuilderVarHelper {
static var buildBlock: (Any...) -> Int { { return $0.count } } // expected-note {{potential match 'buildBlock' is not a static method}}
}
@resultBuilder
struct InvalidBuilder9: BuilderVarHelper {} // expected-error {{result builder must provide at least one static 'buildBlock' method}}
@resultBuilder
struct InvalidBuilder10 { // expected-error {{result builder must provide at least one static 'buildBlock' method}}
static var buildBlock: (Any...) -> Int = { return $0.count } // expected-note {{potential match 'buildBlock' is not a static method}}
}
@resultBuilder
enum InvalidBuilder11 { // expected-error {{result builder must provide at least one static 'buildBlock' method}}
case buildBlock(Any) // expected-note {{enum case 'buildBlock' cannot be used to satisfy the result builder requirement}}
}
struct S {
@ValidBuilder1 var v1: Int { 1 }
@ValidBuilder2 var v2: Int { 1 }
@ValidBuilder3 var v3: Int { 1 }
@ValidBuilder4 var v4: Int { 1 }
@ValidBuilder5 func v5() -> Int {}
@InvalidBuilder1 var i1: Int { 1 } // expected-error {{type 'InvalidBuilder1' has no member 'buildBlock'}}
@InvalidBuilder2 var i2: Int { 1 } // expected-error {{instance member 'buildBlock' cannot be used on type 'InvalidBuilder2'; did you mean to use a value of this type instead?}}
@InvalidBuilder3 var i3: Int { 1 } // expected-error {{instance member 'buildBlock' cannot be used on type 'InvalidBuilder3'; did you mean to use a value of this type instead?}}
@InvalidBuilder4 var i4: Int { 1 } // expected-error {{instance member 'buildBlock' cannot be used on type 'InvalidBuilder4'; did you mean to use a value of this type instead?}}
@InvalidBuilder5 var i5: Int { 1 } // expected-error {{instance member 'buildBlock' cannot be used on type 'InvalidBuilder5'; did you mean to use a value of this type instead?}}
@InvalidBuilder6 var i6: Int { 1 } // expected-error {{cannot call value of non-function type 'Int'}}
@InvalidBuilder7 var i7: Int { 1 }
@InvalidBuilder8 var i8: Int { 1 }
@InvalidBuilder9 var i9: Int { 1 }
@InvalidBuilder10 var i10: Int { 1 }
@InvalidBuilder11 var i11: InvalidBuilder11 { 1 }
}
| 12125e1d24c03b909d37c0ee1ae3345a | 42.082192 | 179 | 0.697933 | false | false | false | false |
JerrySir/YCOA | refs/heads/master | YCOA/Main/Apply/Controller/OnBusinessCreatViewController.swift | mit | 1 | //
// OnBusinessCreatViewController.swift
// YCOA
//
// Created by Jerry on 2016/12/22.
// Copyright © 2016年 com.baochunsteel. All rights reserved.
//
// 出差
import UIKit
class OnBusinessCreatViewController: UIViewController {
@IBOutlet weak var selectTypeButton: UIButton! //外出类型
@IBOutlet weak var selectStartTimeButton: UIButton! //开始时间
@IBOutlet weak var selectEndTimeButton: UIButton! //预计回岗时间
@IBOutlet weak var addressTextFiled: UITextField! //地址
@IBOutlet weak var reasonTextFiled: UITextField! //事由
@IBOutlet weak var otherInfoTextView: UITextView! //说明
@IBOutlet weak var submitButton: UIButton! //提交
@IBOutlet weak var backGroundView: UIScrollView! //背景View
//同步的数据
//Private
private var selectedType : String? //选择的类型
private var selectedStartTime : String? //外出时间
private var selectedEndTime : String? //回岗时间
override func viewDidLoad() {
super.viewDidLoad()
self.title = "出差"
self.UIConfigure()
self.ActionConfigure()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//MARK: - Action
//绑定控件Action
func ActionConfigure() {
//外出类型
self.selectTypeButton.rac_signal(for: .touchUpInside).subscribeNext { (_) in
let type = ["外出", "出差"]
UIPickerView.showDidSelectView(SingleColumnDataSource: type, onView: self.navigationController!.view, selectedTap: { (index) in
self.selectedType = type[index]
self.selectTypeButton.setTitle(self.selectedType!, for: .normal)
})
}
//外出时间
self.selectStartTimeButton.rac_signal(for: .touchUpInside).subscribeNext { (_) in
self.view.endEditing(true)
UIDatePicker.showDidSelectView(minDate: Date(), maxDate: nil, onView: self.navigationController!.view, datePickerMode: .dateAndTime, tap: { (date) in
self.selectedStartTime = (date as NSDate).string(withFormat: "yyyy-MM-dd HH:mm:00")
self.selectStartTimeButton.setTitle(self.selectedStartTime!, for: .normal)
})
}
//回岗时间
self.selectEndTimeButton.rac_signal(for: .touchUpInside).subscribeNext { (_) in
self.view.endEditing(true)
UIDatePicker.showDidSelectView(minDate: Date(), maxDate: nil, onView: self.navigationController!.view, datePickerMode: .dateAndTime, tap: { (date) in
self.selectedEndTime = (date as NSDate).string(withFormat: "yyyy-MM-dd HH:mm:00")
self.selectEndTimeButton.setTitle(self.selectedEndTime!, for: .normal)
})
}
//提交
self.submitButton.rac_signal(for: .touchUpInside).subscribeNext { (sender) in
self.didSubmit()
}
//backGroundView
self.backGroundView.isUserInteractionEnabled = true
let tapGestureRecognizer = UITapGestureRecognizer { (sender) in
self.view.endEditing(true)
}
self.backGroundView.addGestureRecognizer(tapGestureRecognizer)
}
//提交
private func didSubmit() {
guard let atype_ : String = self.selectedType else {
self.navigationController?.view.jrShow(withTitle: "请选择外出类型!")
return
}
guard let outtime_ : String = self.selectedStartTime else {
self.navigationController?.view.jrShow(withTitle: "请选择外出时间")
return
}
guard let intime_ : String = self.selectedEndTime else {
self.navigationController?.view.jrShow(withTitle: "请选择回岗时间")
return
}
let address_ = self.addressTextFiled.text
if(!(address_ != nil && address_!.utf8.count > 0)){
self.navigationController?.view.jrShow(withTitle: "请填写地址!")
return
}
let reason_ = self.reasonTextFiled.text
if(!(reason_ != nil && reason_!.utf8.count > 0)){
self.navigationController?.view.jrShow(withTitle: "请填写外出事由!")
return
}
var parameters: [String : Any] = ["atype" : atype_,
"outtime" : outtime_,
"intime" : intime_,
"address" : address_!,
"reason" : reason_!]
//可选
let explain_ : String = self.otherInfoTextView.text
if(explain_.utf8.count > 0){
parameters["explain"] = explain_
}
let url = "/index.php?d=taskrun&m=flow_waichu|appapi&a=save&ajaxbool=true&adminid=\(UserCenter.shareInstance().uid!)&timekey=\(NSDate.nowTimeToTimeStamp())&token=\(UserCenter.shareInstance().token!)&cfrom=appiphone&appapikey=\(UserCenter.shareInstance().apikey!)"
YCOA_NetWork.post(url: url, parameters: parameters) {
(error, returnValue) in
if(error != nil){
self.navigationController?.view.jrShow(withTitle: error!.domain)
return
}
self.navigationController?.view.jrShow(withTitle: "提交成功!")
}
}
//MARK: - UI
//配置控件UI
func UIConfigure() {
self.makeTextFieldStyle(sender: self.selectTypeButton)
self.makeTextFieldStyle(sender: self.selectStartTimeButton)
self.makeTextFieldStyle(sender: self.selectEndTimeButton)
self.makeTextFieldStyle(sender: self.otherInfoTextView)
self.makeTextFieldStyle(sender: self.submitButton)
}
///设置控件成为TextField一样的样式
func makeTextFieldStyle(sender: UIView) {
sender.layer.masksToBounds = true
sender.layer.cornerRadius = 10/2
sender.layer.borderWidth = 0.3
sender.layer.borderColor = UIColor.lightGray.cgColor
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| f869e3150c760ae6a7209b16e3583f07 | 35.3125 | 271 | 0.603974 | false | false | false | false |
hackersatcambridge/hac-website | refs/heads/master | Sources/HaCWebsiteLib/Views/Page.swift | mit | 2 | import HaCTML
import Foundation
struct Page: Nodeable {
let title: String
let postFixElements: Nodeable
let content: Nodeable
init(title: String = defaultTitle, postFixElements: Nodeable = Fragment(), content: Nodeable) {
self.title = title
self.postFixElements = postFixElements
self.content = content
}
public var node: Node {
return Fragment(
El.Doctype,
El.Html[Attr.lang => "en"].containing(
El.Head.containing(
El.Meta[Attr.charset => "UTF-8"],
El.Meta[Attr.name => "viewport", Attr.content => "width=device-width, initial-scale=1"],
El.Link[Attr.rel => "icon", Attr.type => "favicon/png", Attr.href => Assets.publicPath("/images/favicon.png")],
El.Title.containing(title),
Page.stylesheet(forUrl: Assets.publicPath("/styles/main.css")),
postFixElements
)
),
El.Body.containing(
errorReport,
content,
GAScript()
)
)
}
func render() -> String {
return node.render()
}
/// Get a view of the `swift build` output if it didn't exit with exit code zero
private var errorReport: Node? {
if let errorData = try? Data(contentsOf: URL(fileURLWithPath: "swift_build.log")) {
return Fragment(
El.Pre.containing(
El.Code[Attr.className => "BuildOutput__Error"].containing(String(data: errorData, encoding: String.Encoding.utf8) as String!)
)
)
} else {
return nil
}
}
private static let defaultTitle = "Cambridge's student tech society | Hackers at Cambridge"
public static func stylesheet(forUrl urlString: String) -> Node {
return El.Link[Attr.rel => "stylesheet", Attr.type => "text/css", Attr.href => urlString]
}
}
| bbfeea59c76b9b2a4b68d271e775b940 | 29.431034 | 136 | 0.631161 | false | false | false | false |
Sharelink/Bahamut | refs/heads/master | Bahamut/BahamutRFKit/File/AliOSSFile.swift | mit | 1 | //
// AliOSSFile.swift
// Bahamut
//
// Created by AlexChow on 15/11/25.
// Copyright © 2015年 GStudio. All rights reserved.
//
import Foundation
/*
POST /AliOSSFiles (fileType,fileSize) : get a new send file key for upload task
*/
open class NewAliOSSFileAccessInfoRequest : BahamutRFRequestBase
{
public override init()
{
super.init()
self.api = "/AliOSSFiles"
self.method = .post
}
open override func getMaxRequestCount() -> Int32 {
return BahamutRFRequestBase.maxRequestNoLimitCount
}
open var fileType:FileType! = .noType{
didSet{
self.paramenters["fileType"] = "\(fileType!.rawValue)"
}
}
open var fileSize:Int = 512 * 1024{ //byte
didSet{
self.paramenters["fileSize"] = "\(fileSize)"
}
}
}
/*
POST /AliOSSFiles/List (fileTypes,fileSizes) : get a new send files key for upload task
*/
open class NewAliOSSFileAccessInfoListRequest : BahamutRFRequestBase
{
public override init()
{
super.init()
self.api = "/AliOSSFiles/List"
self.method = .post
}
open var fileTypes:[FileType]!{
didSet{
if fileTypes != nil && fileTypes.count > 0
{
self.paramenters["fileTypes"] = fileTypes.map{"\($0.rawValue)"}.joined(separator: "#")
}
}
}
open var fileSizes:[Int]!{ //byte
didSet{
if fileSizes != nil && fileSizes.count > 0
{
self.paramenters["fileSizes"] = fileSizes.map{"\($0)"}.joined(separator: "#")
}
}
}
open override func getMaxRequestCount() -> Int32 {
return BahamutRFRequestBase.maxRequestNoLimitCount
}
}
| 10ab44b54c53b0573c4cab6d03ac91cc | 23.273973 | 102 | 0.575056 | false | false | false | false |
kaideyi/KDYSample | refs/heads/master | Charting/Charting/Charts/PieChart/PieChartView.swift | mit | 1 | //
// PieChartView.swift
// Charting
//
// Created by mac on 17/3/6.
// Copyright © 2017年 kaideyi.com. All rights reserved.
//
import UIKit
/// 饼状图
class PieChartView: UIView {
var pieLayer: CAShapeLayer!
override init(frame: CGRect) {
super.init(frame: frame)
self.backgroundColor = .clear
drawPiesView()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func drawPiesView() {
let data: [CGFloat] = [25.0, 40.0, 35.0]
var startA: CGFloat = 0.0
var endA: CGFloat = 0.0
pieLayer = CAShapeLayer()
self.layer.addSublayer(pieLayer)
let innnerRadius = self.width / 6.0
let outerRadius = self.width / 2.0
let lineWidth = outerRadius - innnerRadius
let radius = (outerRadius + innnerRadius) * 0.5
for value in data {
endA = CGFloat(value / 100) + startA
let path = UIBezierPath()
let centerPos = self.center
path.addArc(withCenter: centerPos, radius: radius, startAngle: -(CGFloat)(M_PI_2), endAngle: CGFloat(M_PI_2) * 3, clockwise: true)
let layer = CAShapeLayer()
layer.path = path.cgPath
layer.lineWidth = lineWidth
layer.strokeColor = UIColor(red: CGFloat(drand48()), green: CGFloat(drand48()), blue: CGFloat(drand48()), alpha: 1.0).cgColor
layer.fillColor = UIColor.clear.cgColor
layer.strokeStart = startA
layer.strokeEnd = endA
pieLayer.addSublayer(layer)
startA = endA
}
let maskLayer = drawPie()
pieLayer.mask = maskLayer
let animation = CABasicAnimation(keyPath: "strokeEnd")
animation.fromValue = 0.0
animation.toValue = 1.0
animation.duration = 1.5
animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
pieLayer.mask?.add(animation, forKey: nil)
}
func drawPie() -> CAShapeLayer {
let innnerRadius = self.width / 6.0
let outerRadius = self.width / 2.0
let lineWidth = outerRadius - innnerRadius
let radius = (outerRadius + innnerRadius) * 0.5
let path = UIBezierPath()
let centerPos = self.center
path.addArc(withCenter: centerPos, radius: radius, startAngle: -(CGFloat)(M_PI_2), endAngle: CGFloat(M_PI_2) * 3, clockwise: true)
let layer = CAShapeLayer()
layer.path = path.cgPath
layer.lineWidth = lineWidth
layer.strokeColor = UIColor.red.cgColor
layer.fillColor = UIColor.clear.cgColor
layer.strokeStart = 0.0
layer.strokeEnd = 1.0
return layer
}
}
| b6018b044af59f36fac07f1c4cac44c5 | 30.478261 | 142 | 0.579765 | false | false | false | false |
dpskvn/PhotoBombersSwift | refs/heads/master | Photo Bombers/DetailViewController.swift | mit | 1 | //
// DetailViewController.swift
// Photo Bombers
//
// Created by Dino Paskvan on 09/06/14.
// Copyright (c) 2014 Dino Paskvan. All rights reserved.
//
import UIKit
class DetailViewController: UIViewController {
var photo: NSDictionary?
var imageView: UIImageView?
var animator: UIDynamicAnimator?
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor(white: 1.0, alpha: 0.95)
imageView = UIImageView(frame: CGRectMake(0.0, -320.0, 320.0, 320.0))
view.addSubview(imageView)
PhotoController.imageForPhoto(photo!, size: "standard_resolution", completion: {
image in
self.imageView!.image = image
})
let tap = UITapGestureRecognizer(target: self, action: "close")
view.addGestureRecognizer(tap)
animator = UIDynamicAnimator(referenceView: view)
}
override func viewDidAppear(animated: Bool) {
let snap = UISnapBehavior(item: imageView, snapToPoint: view.center)
animator!.addBehavior(snap)
}
func close () {
animator!.removeAllBehaviors()
let snap = UISnapBehavior(item: imageView, snapToPoint: CGPointMake(CGRectGetMidX(view.bounds), CGRectGetMaxY(view.bounds) + 180.0))
animator!.addBehavior(snap)
self.dismissViewControllerAnimated(true, completion: {})
}
}
| da3d07c20ef503e279133ef0f4319fab | 30.217391 | 140 | 0.641365 | false | false | false | false |
KaneCheshire/Communicator | refs/heads/main | Example/WatchExample Extension/InterfaceController.swift | mit | 1 | //
// InterfaceController.swift
// WatchExample Extension
//
// Created by Kane Cheshire on 19/07/2017.
// Copyright © 2017 CocoaPods. All rights reserved.
//
import WatchKit
import Communicator
class InterfaceController: WKInterfaceController {
@IBAction func sendMessageTapped() {
let message = ImmediateMessage(identifier: "message", content: ["hello": "world"])
Communicator.shared.send(message)
}
@IBAction func sendInteractiveMessageTapped() {
let message = InteractiveImmediateMessage(identifier: "interactive_message", content: ["hello": "world"]) { reply in
print("Received reply from message: \(reply)")
}
Communicator.shared.send(message)
}
@IBAction func sendGuaranteedMessageTapped() {
let message = GuaranteedMessage(identifier: "guaranteed_message", content: ["hello": "world"])
Communicator.shared.send(message) { result in
switch result {
case .failure(let error):
print("Error transferring blob: \(error.localizedDescription)")
case .success:
print("Successfully transferred guaranteed message to phone")
}
}
}
@IBAction func transferBlobTapped() {
let data = Data("hello world".utf8)
let blob = Blob(identifier: "blob", content: data)
Communicator.shared.transfer(blob) { result in
switch result {
case .failure(let error):
print("Error transferring blob: \(error.localizedDescription)")
case .success:
print("Successfully transferred blob to phone")
}
}
}
@IBAction func syncContextTapped() {
let context = Context(content: ["hello" : "world"])
do {
try Communicator.shared.sync(context)
print("Synced context to phone")
} catch let error {
print("Error syncing context to phone: \(error.localizedDescription)")
}
}
}
| 142b1d337f38c44339d0fc9c68cdd47a | 32.580645 | 124 | 0.598463 | false | false | false | false |
JaSpa/swift | refs/heads/master | test/SILGen/objc_dealloc.swift | apache-2.0 | 2 | // RUN: %target-swift-frontend -Xllvm -new-mangling-for-tests -sdk %S/Inputs -I %S/Inputs -enable-source-import %s -emit-silgen | %FileCheck %s
// REQUIRES: objc_interop
import gizmo
class X { }
func onDestruct() { }
@requires_stored_property_inits
class SwiftGizmo : Gizmo {
var x = X()
// CHECK-LABEL: sil hidden [transparent] @_T012objc_dealloc10SwiftGizmoC1xAA1XCvfi : $@convention(thin) () -> @owned X
// CHECK: [[FN:%.*]] = function_ref @_T012objc_dealloc1XCACycfC : $@convention(method) (@thick X.Type) -> @owned X
// CHECK-NEXT: [[METATYPE:%.*]] = metatype $@thick X.Type
// CHECK-NEXT: [[RESULT:%.*]] = apply [[FN]]([[METATYPE]]) : $@convention(method) (@thick X.Type) -> @owned X
// CHECK-NEXT: return [[RESULT]] : $X
// CHECK-LABEL: sil hidden @_T012objc_dealloc10SwiftGizmoC{{[_0-9a-zA-Z]*}}fc
// CHECK: bb0([[SELF_PARAM:%[0-9]+]] : $SwiftGizmo):
override init() {
// CHECK: [[SELF_UNINIT:%[0-9]+]] = mark_uninitialized [derivedselfonly]
// CHECK-NOT: ref_element_addr
// CHECK: upcast
// CHECK-NEXT: super_method
// CHECK: return
super.init()
}
// CHECK-LABEL: sil hidden @_T012objc_dealloc10SwiftGizmoCfD : $@convention(method) (@owned SwiftGizmo) -> ()
deinit {
// CHECK: bb0([[SELF:%[0-9]+]] : $SwiftGizmo):
// Call onDestruct()
// CHECK: [[ONDESTRUCT_REF:%[0-9]+]] = function_ref @_T012objc_dealloc10onDestructyyF : $@convention(thin) () -> ()
// CHECK: [[ONDESTRUCT_RESULT:%[0-9]+]] = apply [[ONDESTRUCT_REF]]() : $@convention(thin) () -> ()
onDestruct()
// Note: don't destroy instance variables
// CHECK-NOT: ref_element_addr
// Call super -dealloc.
// CHECK: [[SUPER_DEALLOC:%[0-9]+]] = super_method [[SELF]] : $SwiftGizmo, #Gizmo.deinit!deallocator.foreign : (Gizmo) -> () -> () , $@convention(objc_method) (Gizmo) -> ()
// CHECK: [[SUPER:%[0-9]+]] = upcast [[SELF]] : $SwiftGizmo to $Gizmo
// CHECK: [[SUPER_DEALLOC_RESULT:%[0-9]+]] = apply [[SUPER_DEALLOC]]([[SUPER]]) : $@convention(objc_method) (Gizmo) -> ()
// CHECK: [[RESULT:%[0-9]+]] = tuple ()
// CHECK: return [[RESULT]] : $()
}
// Objective-C deallocation deinit thunk (i.e., -dealloc).
// CHECK-LABEL: sil hidden [thunk] @_T012objc_dealloc10SwiftGizmoCfDTo : $@convention(objc_method) (SwiftGizmo) -> ()
// CHECK: bb0([[SELF:%[0-9]+]] : $SwiftGizmo):
// CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]]
// CHECK: [[GIZMO_DTOR:%[0-9]+]] = function_ref @_T012objc_dealloc10SwiftGizmoCfD : $@convention(method) (@owned SwiftGizmo) -> ()
// CHECK: [[RESULT:%[0-9]+]] = apply [[GIZMO_DTOR]]([[SELF_COPY]]) : $@convention(method) (@owned SwiftGizmo) -> ()
// CHECK: return [[RESULT]] : $()
// Objective-C IVar initializer (i.e., -.cxx_construct)
// CHECK-LABEL: sil hidden @_T012objc_dealloc10SwiftGizmoCfeTo : $@convention(objc_method) (@owned SwiftGizmo) -> @owned SwiftGizmo
// CHECK: bb0([[SELF_PARAM:%[0-9]+]] : $SwiftGizmo):
// CHECK-NEXT: debug_value [[SELF_PARAM]] : $SwiftGizmo, let, name "self"
// CHECK-NEXT: [[SELF:%[0-9]+]] = mark_uninitialized [rootself] [[SELF_PARAM]] : $SwiftGizmo
// CHECK: [[XINIT:%[0-9]+]] = function_ref @_T012objc_dealloc10SwiftGizmoC1xAA1XCvfi
// CHECK-NEXT: [[XOBJ:%[0-9]+]] = apply [[XINIT]]() : $@convention(thin) () -> @owned X
// CHECK-NEXT: [[X:%[0-9]+]] = ref_element_addr [[SELF]] : $SwiftGizmo, #SwiftGizmo.x
// CHECK-NEXT: assign [[XOBJ]] to [[X]] : $*X
// CHECK-NEXT: return [[SELF]] : $SwiftGizmo
// Objective-C IVar destroyer (i.e., -.cxx_destruct)
// CHECK-LABEL: sil hidden @_T012objc_dealloc10SwiftGizmoCfETo : $@convention(objc_method) (SwiftGizmo) -> ()
// CHECK: bb0([[SELF:%[0-9]+]] : $SwiftGizmo):
// CHECK-NEXT: debug_value [[SELF]] : $SwiftGizmo, let, name "self"
// CHECK-NEXT: [[X:%[0-9]+]] = ref_element_addr [[SELF]] : $SwiftGizmo, #SwiftGizmo.x
// CHECK-NEXT: destroy_addr [[X]] : $*X
// CHECK-NEXT: [[RESULT:%[0-9]+]] = tuple ()
// CHECK-NEXT: return [[RESULT]] : $()
}
// CHECK-NOT: sil hidden [thunk] @_T0So11SwiftGizmo2CfETo : $@convention(objc_method) (SwiftGizmo2) -> ()
class SwiftGizmo2 : Gizmo {
}
| ff8f61f160d2c8811b676602452e9916 | 49.926829 | 178 | 0.603209 | false | false | false | false |
webninjamobile/marys-rosary | refs/heads/master | controllers/PrayerSingleViewController.swift | gpl-2.0 | 1 | //
// PrayerSingleViewController.swift
// PrayerBook
//
// Created by keithics on 8/12/15.
// Copyright (c) 2015 Web Ninja Technologies. All rights reserved.
//
import UIKit
import AVFoundation
class PrayerSingleViewController: UIViewController , AVAudioPlayerDelegate{
var myTitle: String = ""
var mysteryIndex: Int = 0
var currentProgress: Int = 0
@IBOutlet weak var scrollView: UIScrollView!
@IBOutlet weak var prayerTitle: UILabel!
@IBOutlet weak var prayer: UILabel!
@IBOutlet weak var btnToggleBgMusic: UIButton!
@IBOutlet weak var btnPlay: UIButton!
@IBOutlet weak var btnNext: UIButton!
@IBOutlet weak var btnPrev: UIButton!
let beads = [("Start",12.5),("I",20),("II",20),("III",20),("IV",20),("V",20),("End",12.5)]
let beadsIndex = [8,22,36,50,64,78,86]
let beadsNumPrayers = [8,14,14,14,14,13,8]
var currentBead = 0;
var beadsArray : [CircleProgress] = []
var beadsTap: UITapGestureRecognizer?
var rosary : [(String,String,String,Int)] = []
var mp3:AVAudioPlayer = AVAudioPlayer()
var backgroundMusic:AVAudioPlayer = AVAudioPlayer()
var autoPlay = false
var hasLoadedMp3 = false
var isPlaying = false // has the user clicked the play button?
var nextDelay = 0; //
var isDonePlaying = false //check if the music has done playing, for pause/play
let userDefaults = NSUserDefaults.standardUserDefaults()
var saveDefaults = false;
var isBackgroundPlaying = false
override func viewDidLoad() {
super.viewDidLoad()
let rosary = Rosary();
self.rosary = rosary.prayRosary(self.mysteryIndex);
// prepare rosary audio
checkMp3(rosary)
let screenSize: CGRect = UIScreen.mainScreen().bounds
let screenWidth = screenSize.width
let fullWidth = screenWidth/7;
let pad = 4;
let dimen = CGFloat(Int(fullWidth) - pad);
self.title = self.myTitle;
_ = 10;
//create beads
for i in 0...6 {
let newX = CGFloat((i * Int(fullWidth)) + pad);
let beadsProgress = CircleProgress(frame: CGRectMake(newX, 80, dimen, dimen))
let (title,size) = beads[i]
beadsProgress.tag = i
beadsProgress.progressLabel.text = title
beadsProgress.progressLabel.font = UIFont(name: "KefaIIPro-Regular", size: CGFloat(size))
beadsTap = UITapGestureRecognizer(target: self , action: Selector("gotoBead:"))
beadsTap!.numberOfTapsRequired = 1
beadsProgress.addGestureRecognizer(beadsTap!)
self.view.addSubview(beadsProgress)
beadsArray.append(beadsProgress)
//DynamicView.animateProgressView()
}
//println(rosary.prayRosary(mysteryIndex))
self.prayer.sizeToFit()
self.btnPrev.setTitle("\u{f04a}",forState: UIControlState.Normal)
self.btnNext.setTitle("\u{f04e}",forState: UIControlState.Normal)
self.btnPlay.setTitle("\u{f04b}",forState: UIControlState.Normal)
self.btnToggleBgMusic.setTitle("\u{f001}",forState: UIControlState.Normal)
// self.navigationItem.title = "asd";
//self.parentViewController.view.backgroundColor = UIColor.redColor();
//restore bead
var lastProgress = 0;
if self.mysteryIndex == userDefaults.integerForKey("lastMystery") {
self.currentBead = userDefaults.integerForKey("lastBead");
lastProgress = userDefaults.integerForKey("lastProgress")
}
pray(lastProgress,recite:false)
checkControls()
// swipes
let leftSwipe = UISwipeGestureRecognizer(target: self, action: Selector("handleSwipes:"))
let rightSwipe = UISwipeGestureRecognizer(target: self, action: Selector("handleSwipes:"))
leftSwipe.direction = .Left
rightSwipe.direction = .Right
view.addGestureRecognizer(leftSwipe)
view.addGestureRecognizer(rightSwipe)
let pathBackground = NSBundle.mainBundle().pathForResource("avemaria", ofType: "mp3")
backgroundMusic = try! AVAudioPlayer(contentsOfURL: NSURL(fileURLWithPath: pathBackground!))
backgroundMusic.volume = 0.1
backgroundMusic.numberOfLoops = -1;
backgroundMusic.prepareToPlay()
}
func back(){
self.navigationController?.popViewControllerAnimated(true)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func pray(currentIndex : Int,direction : String = "forward",recite: Bool = false){
self.prayer.fadeOut()
self.prayerTitle.fadeOut()
let (title,content,mp3,delay) = self.rosary[currentIndex]
self.prayer.text = content
self.prayerTitle.text = title
self.nextDelay = delay
if(recite){ //do not play if last prayer
playMp3(mp3,delay:delay)
}
self.prayer.fadeIn()
self.prayerTitle.fadeIn()
if(currentIndex >= self.beadsIndex[self.currentBead]){
//next bead
self.currentBead++
}
showHideBeadProgress(self.currentBead)
let mulcrement : CGFloat = CGFloat((100/self.beadsNumPrayers[self.currentBead]))/100
let currentProgress = currentIndex < self.beadsNumPrayers[0] ? currentIndex : (currentIndex - self.beadsIndex[self.currentBead - 1])
let nextcrement : CGFloat = CGFloat(Double(currentProgress) + 1.00)
if (direction == "forward"){
beadsArray[self.currentBead].animateProgressView(mulcrement * CGFloat(Double(currentProgress)) , to: mulcrement * nextcrement)
}else{
//back
beadsArray[self.currentBead].animateProgressView( (mulcrement * nextcrement) + mulcrement, to: mulcrement * nextcrement)
}
self.currentProgress = currentIndex
checkControls()
//save current progress
if(self.saveDefaults){
userDefaults.setInteger(self.currentProgress,forKey: "lastProgress")
userDefaults.setInteger(self.currentBead,forKey: "lastBead")
userDefaults.setInteger(self.mysteryIndex,forKey: "lastMystery")
}
}
@IBAction func onNext(sender: AnyObject) {
self.autoPlay = false
nextPrayer(false, willPause: true)
}
func nextPrayer(autoplay : Bool = false , willPause: Bool = false){
if willPause {
pauseMp3()
}
userMoved()
pray(self.currentProgress.maxcrement(self.rosary.count - 1),recite:autoplay)
}
@IBAction func onPrev(sender: AnyObject) {
userMoved()
pauseMp3()
let currentIndex = self.currentProgress.mincrement
//println(currentIndex)
if(currentIndex <= self.beadsIndex[self.currentBead ]){
//clear prev bead
beadsArray[self.currentBead].hideProgressView()
//prev bead
self.currentBead = self.currentBead.mincrement
}
pray(currentIndex,direction: "back")
}
@IBAction func onPlay(sender: AnyObject) {
self.saveDefaults = true
if self.hasLoadedMp3 && !isDonePlaying && !self.isPlaying {
//mp3 is paused
mp3.play() // play the old one
playBackground()
self.autoPlay = true
isDonePlaying = false
isPlaying = true
// pray(self.currentProgress,recite:false)
self.btnPlay.setTitle("\u{f04c}",forState: UIControlState.Normal)
} else
if !isPlaying {
playBackground()
self.autoPlay = true
pray(self.currentProgress,recite:true)
self.btnPlay.setTitle("\u{f04c}",forState: UIControlState.Normal)
}else {
self.btnToggleBgMusic.alpha = 1
pauseBackground()
pauseMp3()
}
}
@IBAction func toggleBgMusic(sender: AnyObject) {
//TODO , set to userdefaults
if(isBackgroundPlaying){
pauseBackground()
}else{
playBackground()
}
}
func playBackground(){
backgroundMusic.play()
btnToggleBgMusic.alpha = 0.5
isBackgroundPlaying = true
}
func pauseBackground(){
backgroundMusic.pause()
btnToggleBgMusic.alpha = 1
isBackgroundPlaying = false
}
func checkControls(){
if(self.currentProgress == 0){
btnPrev.alpha = 0.5
btnPrev.enabled = false
}else{
btnPrev.alpha = 1.0
btnPrev.enabled = true
}
if(self.currentProgress >= self.rosary.count - 1){
btnNext.alpha = 0.5
btnNext.enabled = false
}else{
btnNext.alpha = 1.0
btnNext.enabled = true
}
}
func gotoBead(sender: UITapGestureRecognizer!){
if sender.state == .Ended {
let currentBead = sender.view!.tag
self.currentBead = currentBead
let currentPrayer = currentBead > 0 ? self.beadsIndex[currentBead - 1] : 0;
// let playmp3 = currentBead > 0 ? true : false
userMoved()
pauseMp3()
pray(currentPrayer,recite:false)
}
}
func showHideBeadProgress(currentBead : Int){
for i in 0..<currentBead {
//println(i)
beadsArray[i].showProgressView()
}
for i in currentBead ..< beadsArray.count {
// println(currentBead)
beadsArray[i].hideProgressView()
}
}
func handleSwipes(sender:UISwipeGestureRecognizer) {
if (sender.direction == .Left) {
btnNext.sendActionsForControlEvents(UIControlEvents.TouchUpInside)
}
if (sender.direction == .Right) {
btnPrev.sendActionsForControlEvents(UIControlEvents.TouchUpInside)
}
}
func playMp3(file : String, delay : Int) {
if(delay == 0){
mp3 = try! AVAudioPlayer(contentsOfURL: NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource(file, ofType: "mp3")!))
}else{
//play processed audio instead
let paths = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
let documentsURL = paths[0]
let processedAudio = documentsURL.URLByAppendingPathComponent(file.m4a)
try! AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
mp3 = try! AVAudioPlayer(contentsOfURL: processedAudio)
}
mp3.prepareToPlay()
self.hasLoadedMp3 = true
mp3.delegate = self
mp3.play()
isDonePlaying = false
isPlaying = true
}
func userMoved(){ //triggered if user taps on prev,next or beads
self.isDonePlaying = true
self.isPlaying = false
}
func pauseMp3(){
if(self.hasLoadedMp3){
self.isPlaying = false
self.autoPlay = false
self.mp3.pause();
self.btnPlay.setTitle("\u{f04b}",forState: UIControlState.Normal)
}
}
/* Prepare audio and delete if audio is already processed
*/
func toggleControls(enable : Bool , alpha : Double){
self.btnNext.enabled = enable
self.btnNext.alpha = CGFloat(alpha)
self.btnPlay.enabled = enable
self.btnPlay.alpha = CGFloat(alpha)
}
func prepareAudio(rosary : Rosary){
var status : [Bool] = []
for (_, subJson): (String, JSON) in JSON(data:rosary.rosaryJson) {
if subJson["delay"] > 0 {
let isOkay = Audio().merge(subJson["mp3"].stringValue,silence: Double(subJson["delay"].intValue))
status.append(isOkay)
}
};
for index in rosary.mysteries{
let isOkay = Audio().merge(index + "mystery",silence: 3)
status.append(isOkay)
}
let isOK = !status.contains(true)
if !isOK {
notifyUserError()
}
userDefaults.setBool(isOK, forKey: "hasProcessed")
}
func checkMp3(rosary :Rosary){
if !userDefaults.boolForKey("hasProcessed"){
let qualityOfServiceClass = QOS_CLASS_BACKGROUND
let backgroundQueue = dispatch_get_global_queue(qualityOfServiceClass, 0)
dispatch_async(backgroundQueue, {
self.toggleControls(false,alpha: 0.5)
self.prepareAudio(rosary)
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.toggleControls(true,alpha: 1)
})
})
}else{
var audiofiles : [String] = [];
//check if mp3 files exists, just in case :)
for (_, subJson): (String, JSON) in JSON(data:rosary.rosaryJson) {
if subJson["delay"] > 0 {
audiofiles.append(subJson["mp3"].stringValue)
}
};
for index in rosary.mysteries{
audiofiles.append(index + "mystery")
}
let docPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0]
let checkValidation = NSFileManager.defaultManager()
for eachAudio in audiofiles{
let exportPath = (docPath as NSString).stringByAppendingPathComponent(eachAudio.m4a)
if (!checkValidation.fileExistsAtPath(exportPath)) {
notifyUserError()
break
}
}
}
}
func notifyUserError(){
let refreshAlert = UIAlertController(title: "Error", message: "Error saving audio files. ", preferredStyle: UIAlertControllerStyle.Alert)
refreshAlert.addAction(UIAlertAction(title: "Retry", style: .Default, handler: { (action: UIAlertAction) in
NSUserDefaults.standardUserDefaults().setBool(false, forKey: "hasProcessed")
self.back()
}))
self.presentViewController(refreshAlert, animated: true, completion: nil)
}
// delegates
func audioPlayerDidFinishPlaying(player: AVAudioPlayer, successfully flag: Bool) {
isDonePlaying = true
if(self.autoPlay && self.currentProgress < self.rosary.count - 1){
self.nextPrayer(true)
}
if(self.currentProgress == self.rosary.count - 1){ // last item
//change play button
self.btnPlay.setTitle("\u{f04b}",forState: UIControlState.Normal)
let fader = iiFaderForAvAudioPlayer(player: backgroundMusic)
fader.volumeAlterationsPerSecond = 10
fader.fadeOut(7, velocity: 1)
// backgroundMusic.fadeOut()
}
}
}
| e417e39d055a6f527b5b96534e492054 | 30.760479 | 145 | 0.568942 | false | false | false | false |
plus44/mhml-2016 | refs/heads/master | app/Helmo/Helmo/WebServiceManager.swift | gpl-3.0 | 1 | //
// WebServiceManager.swift
// Helmo
//
// Created by Mihnea Rusu on 10/03/17.
// Copyright © 2017 Mihnea Rusu. All rights reserved.
//
import Foundation
import Alamofire
import SwiftyJSON
class WebServiceManager: NSObject {
static let sharedInstance = WebServiceManager()
let baseFallQueryURL = "http://123wedonthaveaservercuzshawnisaslacker.com/falls.php"
/**
Get 10 falls starting from an offset down the long list of falls.
- Parameters:
- offset: Integer offset down the list of falls from which to start fetching data
- onCompletion: User-registered on-complete handler that gets called once the request has returned, with the falls in a JSON objects.
*/
func getFalls(offset: Int, onCompletion: @escaping (JSON) -> Void) {
let parameters = ["offset" : offset] as Parameters
sendGetRequest(path: baseFallQueryURL, parameters: parameters, onCompletion: onCompletion)
}
/**
Get the total number of falls available for the authenticated user in the database.
- Parameter onCompletion: A user-registered handler that will give the caller access to the returned 'count' parameter as an integer.
*/
func getFallCount(onCompletion: @escaping (Int) -> Void) {
let parameters = ["count" : ""] as Parameters
var count = 0
sendGetRequest(path: baseFallQueryURL, parameters: parameters) {
json in
if json != JSON.null {
count = json["count"].intValue
onCompletion(count)
}
}
}
/**
Send a get request to the path, with given parameters encoded in the URL.
- Parameters:
- path: The URL path to which to send the request to.
- parameters: What parameters to URL encode
- onCompletion: Handler that gets called with the returned server JSON response, on the same thread as the request. If an invalid reponse is received, JSON.null will be returned as the argument
*/
private func sendGetRequest(path: String, parameters: Parameters, onCompletion: @escaping (JSON) -> Void) {
Alamofire.request(path, method: .get, parameters: parameters, encoding: URLEncoding.default, headers: nil)
.response { response in
if let responseJSON = response.data {
onCompletion(JSON(data: responseJSON))
} else {
print("\(#file): responseJSON nil")
onCompletion(JSON.null)
}
} // end of response closure
} // end of func sendGetRequest
}
| ad7f6be77a6d4ca2bb198cc79e366eb3 | 38.028986 | 205 | 0.627553 | false | false | false | false |
markedwardmurray/Starlight | refs/heads/master | Starlight/Starlight/Controllers/AboutTableViewController.swift | mit | 1 | //
// AboutTableViewController.swift
// Starlight
//
// Created by Mark Murray on 11/20/16.
// Copyright © 2016 Mark Murray. All rights reserved.
//
import UIKit
import MessageUI
import Down
enum AboutTVCIndex: Int {
case database, sunlight, oss, github, contact
}
class AboutTableViewController: UITableViewController, MFMailComposeViewControllerDelegate {
static let navConStoryboardId = "AboutNavigationController"
@IBOutlet var menuBarButton: UIBarButtonItem!
@IBOutlet var tableHeaderViewLabel: UILabel!
@IBOutlet var tableFooterViewLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
if self.revealViewController() != nil {
self.menuBarButton.target = self.revealViewController()
self.menuBarButton.action = Selector(("revealToggle:"))
self.view.addGestureRecognizer(self.revealViewController().panGestureRecognizer())
}
let appVersion = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString")!
let build = Bundle.main.object(forInfoDictionaryKey: "CFBundleVersion")!
self.tableFooterViewLabel.text =
"Made in USA\n" +
"v\(appVersion) (\(build))"
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let index = AboutTVCIndex(rawValue: indexPath.row)!
switch index {
case .database:
self.usCongressDatabaseCellSelected()
break;
case .sunlight:
self.sunlightCellSelected()
break
case .oss:
self.openSourceCellSelected()
break
case .github:
self.githubCellSelected()
break
case .contact:
self.contactCellSelected()
break
}
tableView.deselectRow(at: indexPath, animated: true)
}
func usCongressDatabaseCellSelected() {
guard let url = URL(string: "https://github.com/unitedstates/congress-legislators") else { return }
UIApplication.shared.open(url, options: [:], completionHandler: nil)
}
func sunlightCellSelected() {
guard let url = URL(string: "https://sunlightlabs.github.io/congress") else { return }
UIApplication.shared.open(url, options: [:], completionHandler: nil)
}
func openSourceCellSelected() {
let url_str = Bundle.main.path(forResource: "Pods-Starlight-acknowledgements", ofType: "markdown")!
let url = URL(fileURLWithPath: url_str)
var markdown = ""
do {
markdown = try String.init(contentsOf: url, encoding: .utf8)
}
catch {
print(error)
return
}
let ossVC = UIViewController()
ossVC.title = "Acknowledgements"
let downView = try? DownView(frame: self.view.frame, markdownString: markdown)
if let downView = downView {
ossVC.view.addSubview(downView)
downView.translatesAutoresizingMaskIntoConstraints = false
downView.leadingAnchor.constraint(equalTo: ossVC.view.leadingAnchor).isActive = true
downView.topAnchor.constraint(equalTo: ossVC.view.topAnchor).isActive = true
downView.trailingAnchor.constraint(equalTo: ossVC.view.trailingAnchor).isActive = true
downView.bottomAnchor.constraint(equalTo: ossVC.view.bottomAnchor).isActive = true
self.navigationController?.pushViewController(ossVC, animated: true);
}
}
func githubCellSelected() {
guard let url = URL(string: "https://github.com/markedwardmurray/starlight") else { return }
UIApplication.shared.open(url, options: [:], completionHandler: nil)
}
func contactCellSelected() {
let mailComposeViewController = configuredMailComposeViewController()
if MFMailComposeViewController.canSendMail() {
self.present(mailComposeViewController, animated: true, completion: nil)
} else {
self.showAlertWithTitle(title: "Error!", message: "Email is not configured on this device.")
}
}
func configuredMailComposeViewController() -> MFMailComposeViewController {
let mailComposerVC = MFMailComposeViewController()
mailComposerVC.mailComposeDelegate = self
mailComposerVC.setToRecipients(["[email protected]"])
mailComposerVC.setSubject("iOS In-App Email")
let appVersion = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString")!
let build = Bundle.main.object(forInfoDictionaryKey: "CFBundleVersion")!
let systemVersion = UIDevice.current.systemVersion
let model = UIDevice.current.model
let firstLanguage = NSLocale.preferredLanguages.first!
let messageBody = "\n\n\n" +
"v\(appVersion) (\(build))\n" +
"iOS \(systemVersion), \(model)\n" +
"\(firstLanguage)"
mailComposerVC.setMessageBody(messageBody, isHTML: false)
return mailComposerVC
}
// MARK: MFMailComposeViewControllerDelegate
func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) {
if error != nil {
self.showAlertWithTitle(title: "Failed to Send", message: error!.localizedDescription)
} else {
controller.dismiss(animated: true, completion: nil)
}
}
}
| 997f911e0ce405dc432b792ba9b1f6e6 | 36.891892 | 133 | 0.645685 | false | false | false | false |
RocketChat/Rocket.Chat.iOS | refs/heads/develop | Rocket.Chat/Controllers/Preferences/PreferencesViewModel.swift | mit | 1 | //
// PreferencesViewModel.swift
// Rocket.Chat
//
// Created by Rafael Ramos on 31/03/17.
// Copyright © 2017 Rocket.Chat. All rights reserved.
//
import UIKit
internal enum BundleInfoKey: String {
case version = "CFBundleShortVersionString"
case build = "CFBundleVersion"
}
final class PreferencesViewModel {
internal let title = localized("myaccount.settings.title")
internal let profile = localized("myaccount.settings.profile")
internal let administration = localized("myaccount.settings.administration")
internal let contactus = localized("myaccount.settings.contactus")
internal let license = localized("myaccount.settings.license")
internal let language = localized("myaccount.settings.language")
internal let webBrowser = localized("myaccount.settings.web_browser")
internal let appicon = localized("myaccount.settings.appicon")
internal let review = localized("myaccount.settings.review")
internal let share = localized("myaccount.settings.share")
internal let theme = localized("theme.settings.title")
internal let licenseURL = URL(string: "https://github.com/RocketChat/Rocket.Chat.iOS/blob/develop/LICENSE")
internal let shareURL = URL(string: "https://itunes.apple.com/app/rocket-chat/id1148741252?ls=1&mt=8")
internal let reviewURL = URL(string: "itms-apps://itunes.apple.com/app/id1148741252?action=write-review&mt=8")
internal let trackingTitle = localized("myaccount.settings.tracking.title")
internal var trackingFooterText = localized("myaccount.settings.tracking.footer")
internal var serverName: String {
var serverName = "Rocket.Chat"
if let authServerName = AuthSettingsManager.settings?.serverName {
serverName = authServerName
} else if let serverURL = AuthManager.isAuthenticated()?.serverURL {
if let host = URL(string: serverURL)?.host {
serverName = host
} else {
serverName = serverURL
}
}
return serverName
}
internal var logout: String {
return String(format: localized("myaccount.settings.logout"), serverName)
}
internal var trackingValue: Bool {
return !AnalyticsCoordinator.isUsageDataLoggingDisabled
}
internal var formattedVersion: String {
return String(format: localized("myaccount.settings.version"), version, build)
}
internal var formattedServerVersion: String {
let serverVersion = AuthManager.isAuthenticated()?.serverVersion ?? "?"
return String(format: localized("myaccount.settings.server_version"), serverVersion)
}
internal var serverAddress: String {
return AuthManager.isAuthenticated()?.apiHost?.host ?? ""
}
internal var user: User? {
return AuthManager.currentUser()
}
internal var userName: String {
return AuthManager.currentUser()?.displayName() ?? ""
}
internal var userStatus: String {
guard let user = AuthManager.currentUser() else {
return localized("user_menu.invisible")
}
switch user.status {
case .online: return localized("status.online")
case .offline: return localized("status.invisible")
case .busy: return localized("status.busy")
case .away: return localized("status.away")
}
}
internal var version: String {
return appInfo(.version)
}
internal var build: String {
return appInfo(.build)
}
internal let supportEmail = "Rocket.Chat Support <[email protected]>"
internal let supportEmailSubject = "Support on iOS native application"
internal var supportEmailBody: String {
return """
<br /><br />
<b>Device information</b><br />
<b>System name</b>: \(UIDevice.current.systemName)<br />
<b>System version</b>: \(UIDevice.current.systemVersion)<br />
<b>System model</b>: \(UIDevice.current.model)<br />
<b>Application version</b>: \(version) (\(build))
"""
}
internal var canChangeAppIcon: Bool {
return UIApplication.shared.supportsAlternateIcons
}
internal var canViewAdministrationPanel: Bool {
return user?.canViewAdminPanel() ?? false
}
#if DEBUG || BETA || TEST
internal let canOpenFLEX = true
#else
internal let canOpenFLEX = false
#endif
internal let numberOfSections = 7
internal func numberOfRowsInSection(_ section: Int) -> Int {
switch section {
case 0: return 1
case 1: return canChangeAppIcon ? 7 : 6
case 2: return canViewAdministrationPanel ? 1 : 0
case 3: return 3
case 4: return 1
case 5: return 1
case 6: return canOpenFLEX ? 1 : 0
default: return 0
}
}
// MARK: Helpers
internal func appInfo(_ info: BundleInfoKey) -> String {
return Bundle.main.infoDictionary?[info.rawValue] as? String ?? ""
}
}
| b7af5c45ef5ea8f0b4cc796177018c42 | 31.927632 | 114 | 0.66014 | false | false | false | false |
drmohundro/Quick | refs/heads/master | Quick/Quick/Example.swift | mit | 2 | //
// Example.swift
// Quick
//
// Created by Brian Ivan Gesiak on 6/5/14.
// Copyright (c) 2014 Brian Ivan Gesiak. All rights reserved.
//
import XCTest
var _numberOfExamplesRun = 0
@objc public class Example {
weak var group: ExampleGroup?
var _description: String
var _closure: () -> ()
public var isSharedExample = false
public var callsite: Callsite
public var name: String { get { return group!.name + ", " + _description } }
init(_ description: String, _ callsite: Callsite, _ closure: () -> ()) {
self._description = description
self._closure = closure
self.callsite = callsite
}
public func run() {
if _numberOfExamplesRun == 0 {
World.sharedWorld().runBeforeSpec()
}
for before in group!.befores {
before()
}
_closure()
for after in group!.afters {
after()
}
++_numberOfExamplesRun
if _numberOfExamplesRun >= World.sharedWorld().exampleCount {
World.sharedWorld().runAfterSpec()
}
}
}
| b161cd2a7084637996712d8d89764aef | 21.06 | 80 | 0.576609 | false | false | false | false |
Athlee/ATHKit | refs/heads/master | Example/Pods/Material/Sources/iOS/Grid.swift | agpl-3.0 | 3 | /*
* Copyright (C) 2015 - 2016, Daniel Dahan and CosmicMind, Inc. <http://cosmicmind.com>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* * Neither the name of CosmicMind nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import UIKit
@objc(GridAxisDirection)
public enum GridAxisDirection: Int {
case any
case horizontal
case vertical
}
public struct GridAxis {
/// The direction the grid lays its views out.
public var direction = GridAxisDirection.horizontal
/// The rows size.
public var rows: Int
/// The columns size.
public var columns: Int
/**
Initializer.
- Parameter rows: The number of rows, vertical axis the grid will use.
- Parameter columns: The number of columns, horizontal axis the grid will use.
*/
internal init(rows: Int = 12, columns: Int = 12) {
self.rows = rows
self.columns = columns
}
}
public struct GridOffset {
/// The rows size.
public var rows: Int
/// The columns size.
public var columns: Int
/**
Initializer.
- Parameter rows: The number of rows, vertical axis the grid will use.
- Parameter columns: The number of columns, horizontal axis the grid will use.
*/
internal init(rows: Int = 0, columns: Int = 0) {
self.rows = rows
self.columns = columns
}
}
public struct Grid {
/// Context view.
internal weak var context: UIView?
/// Defer the calculation.
public var deferred = false
/// Number of rows.
public var rows: Int {
didSet {
reload()
}
}
/// Number of columns.
public var columns: Int {
didSet {
reload()
}
}
/// Offsets for rows and columns.
public var offset = GridOffset() {
didSet {
reload()
}
}
/// The axis in which the Grid is laying out its views.
public var axis = GridAxis() {
didSet {
reload()
}
}
/// Preset inset value for grid.
public var layoutEdgeInsetsPreset = EdgeInsetsPreset.none {
didSet {
layoutEdgeInsets = EdgeInsetsPresetToValue(preset: contentEdgeInsetsPreset)
}
}
/// Insets value for grid.
public var layoutEdgeInsets = EdgeInsets.zero {
didSet {
reload()
}
}
/// Preset inset value for grid.
public var contentEdgeInsetsPreset = EdgeInsetsPreset.none {
didSet {
contentEdgeInsets = EdgeInsetsPresetToValue(preset: contentEdgeInsetsPreset)
}
}
/// Insets value for grid.
public var contentEdgeInsets = EdgeInsets.zero {
didSet {
reload()
}
}
/// A preset wrapper for interim space.
public var interimSpacePreset = InterimSpacePreset.none {
didSet {
interimSpace = InterimSpacePresetToValue(preset: interimSpacePreset)
}
}
/// The space between grid rows and columnss.
public var interimSpace: InterimSpace {
didSet {
reload()
}
}
/// An Array of UIButtons.
public var views = [UIView]() {
didSet {
for v in oldValue {
v.removeFromSuperview()
}
reload()
}
}
/**
Initializer.
- Parameter rows: The number of rows, vertical axis the grid will use.
- Parameter columns: The number of columns, horizontal axis the grid will use.
- Parameter interimSpace: The interim space between rows or columns.
*/
internal init(context: UIView?, rows: Int = 0, columns: Int = 0, interimSpace: InterimSpace = 0) {
self.context = context
self.rows = rows
self.columns = columns
self.interimSpace = interimSpace
}
/// Begins a deferred block.
public mutating func begin() {
deferred = true
}
/// Completes a deferred block.
public mutating func commit() {
deferred = false
reload()
}
/// Reload the button layout.
public func reload() {
guard !deferred else {
return
}
guard let canvas = context else {
return
}
for v in views {
if canvas != v.superview {
v.removeFromSuperview()
canvas.addSubview(v)
}
}
let count = views.count
guard 0 < count else {
return
}
guard 0 < canvas.width && 0 < canvas.height else {
return
}
var n = 0
var i = 0
for v in views {
// Forces the view to adjust accordingly to size changes, ie: UILabel.
(v as? UILabel)?.sizeToFit()
switch axis.direction {
case .horizontal:
let c = 0 == v.grid.columns ? axis.columns / count : v.grid.columns
let co = v.grid.offset.columns
let w = (canvas.bounds.width - contentEdgeInsets.left - contentEdgeInsets.right - layoutEdgeInsets.left - layoutEdgeInsets.right + interimSpace) / CGFloat(axis.columns)
v.x = CGFloat(i + n + co) * w + contentEdgeInsets.left + layoutEdgeInsets.left
v.y = contentEdgeInsets.top + layoutEdgeInsets.top
v.width = w * CGFloat(c) - interimSpace
v.height = canvas.bounds.height - contentEdgeInsets.top - contentEdgeInsets.bottom - layoutEdgeInsets.top - layoutEdgeInsets.bottom
n += c + co - 1
case .vertical:
let r = 0 == v.grid.rows ? axis.rows / count : v.grid.rows
let ro = v.grid.offset.rows
let h = (canvas.bounds.height - contentEdgeInsets.top - contentEdgeInsets.bottom - layoutEdgeInsets.top - layoutEdgeInsets.bottom + interimSpace) / CGFloat(axis.rows)
v.x = contentEdgeInsets.left + layoutEdgeInsets.left
v.y = CGFloat(i + n + ro) * h + contentEdgeInsets.top + layoutEdgeInsets.top
v.width = canvas.bounds.width - contentEdgeInsets.left - contentEdgeInsets.right - layoutEdgeInsets.left - layoutEdgeInsets.right
v.height = h * CGFloat(r) - interimSpace
n += r + ro - 1
case .any:
let r = 0 == v.grid.rows ? axis.rows / count : v.grid.rows
let ro = v.grid.offset.rows
let c = 0 == v.grid.columns ? axis.columns / count : v.grid.columns
let co = v.grid.offset.columns
let w = (canvas.bounds.width - contentEdgeInsets.left - contentEdgeInsets.right - layoutEdgeInsets.left - layoutEdgeInsets.right + interimSpace) / CGFloat(axis.columns)
let h = (canvas.bounds.height - contentEdgeInsets.top - contentEdgeInsets.bottom - layoutEdgeInsets.top - layoutEdgeInsets.bottom + interimSpace) / CGFloat(axis.rows)
v.x = CGFloat(co) * w + contentEdgeInsets.left + layoutEdgeInsets.left
v.y = CGFloat(ro) * h + contentEdgeInsets.top + layoutEdgeInsets.top
v.width = w * CGFloat(c) - interimSpace
v.height = h * CGFloat(r) - interimSpace
}
i += 1
}
}
}
/// A memory reference to the Grid instance for UIView extensions.
private var GridKey: UInt8 = 0
/// Grid extension for UIView.
extension UIView {
/// Grid reference.
public var grid: Grid {
get {
return AssociatedObject(base: self, key: &GridKey) {
return Grid(context: self)
}
}
set(value) {
AssociateObject(base: self, key: &GridKey, value: value)
}
}
/// A reference to grid's layoutEdgeInsetsPreset.
open var layoutEdgeInsetsPreset: EdgeInsetsPreset {
get {
return grid.layoutEdgeInsetsPreset
}
set(value) {
grid.layoutEdgeInsetsPreset = value
}
}
/// A reference to grid's layoutEdgeInsets.
@IBInspectable
open var layoutEdgeInsets: EdgeInsets {
get {
return grid.layoutEdgeInsets
}
set(value) {
grid.layoutEdgeInsets = value
}
}
}
| f018d71c3d5850ae19b2d3dda6b1dfc9 | 31.44918 | 184 | 0.587855 | false | false | false | false |
Molbie/Outlaw-SpriteKit | refs/heads/master | Sources/OutlawSpriteKit/Nodes/Display/SKLabelNode+Outlaw.swift | mit | 1 | //
// SKLabelNode+Outlaw.swift
// OutlawSpriteKit
//
// Created by Brian Mullen on 12/16/16.
// Copyright © 2016 Molbie LLC. All rights reserved.
//
import SpriteKit
import Outlaw
import OutlawCoreGraphics
import OutlawAppKit
import OutlawUIKit
// NOTE: Swift doesn't allow methods to be overriden
// within extensions, so we are defining
// explicit methods for each SKNode subclass
public extension SKLabelNode {
struct LabelNodeExtractableKeys {
public static let verticalAlignmentMode = "verticalAlignmentMode"
public static let horizontalAlignmentMode = "horizontalAlignmentMode"
public static let fontName = "fontName"
public static let text = "text"
public static let fontSize = "fontSize"
public static let fontColor = "fontColor"
public static let colorBlendFactor = "colorBlendFactor"
public static let color = "color"
public static let blendMode = "blendMode"
}
private typealias keys = SKLabelNode.LabelNodeExtractableKeys
}
public extension SKLabelNode { /* Serializable */
func serializedLabelNode(withChildren: Bool) -> [String: Any] {
var result = self.serializedNode(withChildren: withChildren)
result[keys.verticalAlignmentMode] = self.verticalAlignmentMode.stringValue
result[keys.horizontalAlignmentMode] = self.horizontalAlignmentMode.stringValue
result[keys.fontName] = self.fontName ?? ""
result[keys.text] = self.text ?? ""
result[keys.fontSize] = self.fontSize
if let fontColor = self.fontColor {
result[keys.fontColor] = fontColor.serialized()
}
else {
result[keys.fontColor] = SKColor.white.serialized()
}
result[keys.colorBlendFactor] = self.colorBlendFactor
if let color = self.color {
result[keys.color] = color.serialized()
}
result[keys.blendMode] = self.blendMode.stringValue
return result
}
}
public extension SKLabelNode { /* Updatable */
func updateLabelNode(with object: Extractable) throws {
try self.updateNode(with: object)
if let stringValue: String = object.optional(for: keys.verticalAlignmentMode), let verticalAlignmentMode = SKLabelVerticalAlignmentMode(stringValue: stringValue) {
self.verticalAlignmentMode = verticalAlignmentMode
}
if let stringValue: String = object.optional(for: keys.horizontalAlignmentMode), let horizontalAlignmentMode = SKLabelHorizontalAlignmentMode(stringValue: stringValue) {
self.horizontalAlignmentMode = horizontalAlignmentMode
}
if let fontName: String = object.optional(for: keys.fontName), !fontName.isEmpty {
self.fontName = fontName
}
if let text: String = object.optional(for: keys.text) {
self.text = text
}
if let fontSize: CGFloat = object.optional(for: keys.fontSize) {
self.fontSize = fontSize
}
if let fontColor: SKColor = object.optional(for: keys.fontColor) {
self.fontColor = fontColor
}
if let colorBlendFactor: CGFloat = object.optional(for: keys.colorBlendFactor) {
self.colorBlendFactor = colorBlendFactor
}
if let color: SKColor = object.optional(for: keys.color) {
self.color = color
}
if let stringValue: String = object.optional(for: keys.blendMode), let blendMode = SKBlendMode(stringValue: stringValue) {
self.blendMode = blendMode
}
}
}
| 5debe465a1e391f03b29ec1fea8413cb | 38.866667 | 177 | 0.670569 | false | false | false | false |
esttorhe/SwiftSSH2 | refs/heads/swift-2.0 | SwiftSSH2Tests/Supporting Files/SwiftSSH2.playground/Contents.swift | mit | 1 |
// Native Frameworks
import CFNetwork
import Foundation
//let hostaddr = "google.com"
//let host = CFHostCreateWithName(kCFAllocatorDefault, hostaddr)
//host.autorelease()
//let error = UnsafeMutablePointer<CFStreamError>.alloc(1)
//let tHost: CFHost! = host.takeRetainedValue()
//if CFHostStartInfoResolution(tHost, CFHostInfoType.Addresses, error) {
// let hbr = UnsafeMutablePointer<Boolean>()
// addresses = CFHostGetAddressing(host, hbr)
//}
//
//error.dealloc(1)
| 94210df69302e23583007c658efc798e | 28.5625 | 72 | 0.758985 | false | false | false | false |
ryuichis/swift-ast | refs/heads/master | Tests/ParserTests/Declaration/ParserConstantDeclarationTests.swift | apache-2.0 | 2 | /*
Copyright 2017-2018 Ryuichi Intellectual Property and the Yanagiba project contributors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import XCTest
@testable import AST
@testable import Parser
class ParserConstantDeclarationTests: XCTestCase {
func testDefineConstant() {
parseDeclarationAndTest("let foo", "let foo", testClosure: { decl in
guard let constDecl = decl as? ConstantDeclaration else {
XCTFail("Failed in getting a constant declaration.")
return
}
XCTAssertTrue(constDecl.attributes.isEmpty)
XCTAssertTrue(constDecl.modifiers.isEmpty)
XCTAssertEqual(constDecl.initializerList.count, 1)
XCTAssertEqual(constDecl.initializerList[0].textDescription, "foo")
XCTAssertTrue(constDecl.initializerList[0].pattern is IdentifierPattern)
XCTAssertNil(constDecl.initializerList[0].initializerExpression)
})
}
func testDefineConstantWithTypeAnnotation() {
parseDeclarationAndTest("let foo: Foo", "let foo: Foo", testClosure: { decl in
guard let constDecl = decl as? ConstantDeclaration else {
XCTFail("Failed in getting a constant declaration.")
return
}
XCTAssertTrue(constDecl.attributes.isEmpty)
XCTAssertTrue(constDecl.modifiers.isEmpty)
XCTAssertEqual(constDecl.initializerList.count, 1)
XCTAssertEqual(constDecl.initializerList[0].textDescription, "foo: Foo")
XCTAssertTrue(constDecl.initializerList[0].pattern is IdentifierPattern)
XCTAssertNil(constDecl.initializerList[0].initializerExpression)
})
}
func testDefineConstantWithInitializer() {
parseDeclarationAndTest("let foo: Foo = bar", "let foo: Foo = bar", testClosure: { decl in
guard let constDecl = decl as? ConstantDeclaration else {
XCTFail("Failed in getting a constant declaration.")
return
}
XCTAssertTrue(constDecl.attributes.isEmpty)
XCTAssertTrue(constDecl.modifiers.isEmpty)
XCTAssertEqual(constDecl.initializerList.count, 1)
XCTAssertEqual(constDecl.initializerList[0].textDescription, "foo: Foo = bar")
XCTAssertTrue(constDecl.initializerList[0].pattern is IdentifierPattern)
XCTAssertNotNil(constDecl.initializerList[0].initializerExpression)
})
}
func testMultipleDecls() {
parseDeclarationAndTest("let foo = bar, a, x = y",
"let foo = bar, a, x = y",
testClosure: { decl in
guard let constDecl = decl as? ConstantDeclaration else {
XCTFail("Failed in getting a constant declaration.")
return
}
XCTAssertTrue(constDecl.attributes.isEmpty)
XCTAssertTrue(constDecl.modifiers.isEmpty)
XCTAssertEqual(constDecl.initializerList.count, 3)
XCTAssertEqual(constDecl.initializerList[0].textDescription, "foo = bar")
XCTAssertTrue(constDecl.initializerList[0].pattern is IdentifierPattern)
XCTAssertNotNil(constDecl.initializerList[0].initializerExpression)
XCTAssertEqual(constDecl.initializerList[1].textDescription, "a")
XCTAssertTrue(constDecl.initializerList[1].pattern is IdentifierPattern)
XCTAssertNil(constDecl.initializerList[1].initializerExpression)
XCTAssertEqual(constDecl.initializerList[2].textDescription, "x = y")
XCTAssertTrue(constDecl.initializerList[2].pattern is IdentifierPattern)
XCTAssertNotNil(constDecl.initializerList[2].initializerExpression)
})
}
func testAttributes() {
parseDeclarationAndTest("@a let foo", "@a let foo", testClosure: { decl in
guard let constDecl = decl as? ConstantDeclaration else {
XCTFail("Failed in getting a constant declaration.")
return
}
XCTAssertEqual(constDecl.attributes.count, 1)
ASTTextEqual(constDecl.attributes[0].name, "a")
XCTAssertTrue(constDecl.modifiers.isEmpty)
XCTAssertEqual(constDecl.initializerList.count, 1)
XCTAssertEqual(constDecl.initializerList[0].textDescription, "foo")
XCTAssertTrue(constDecl.initializerList[0].pattern is IdentifierPattern)
XCTAssertNil(constDecl.initializerList[0].initializerExpression)
})
}
func testModifiers() {
parseDeclarationAndTest(
"private nonmutating static final let foo = bar",
"private nonmutating static final let foo = bar",
testClosure: { decl in
guard let constDecl = decl as? ConstantDeclaration else {
XCTFail("Failed in getting a constant declaration.")
return
}
XCTAssertTrue(constDecl.attributes.isEmpty)
XCTAssertEqual(constDecl.modifiers.count, 4)
XCTAssertEqual(constDecl.modifiers[0], .accessLevel(.private))
XCTAssertEqual(constDecl.modifiers[1], .mutation(.nonmutating))
XCTAssertEqual(constDecl.modifiers[2], .static)
XCTAssertEqual(constDecl.modifiers[3], .final)
XCTAssertEqual(constDecl.initializerList.count, 1)
XCTAssertEqual(constDecl.initializerList[0].textDescription, "foo = bar")
XCTAssertTrue(constDecl.initializerList[0].pattern is IdentifierPattern)
XCTAssertNotNil(constDecl.initializerList[0].initializerExpression)
})
}
func testAttributeAndModifiers() {
parseDeclarationAndTest("@a fileprivate let foo", "@a fileprivate let foo", testClosure: { decl in
guard let constDecl = decl as? ConstantDeclaration else {
XCTFail("Failed in getting a constant declaration.")
return
}
XCTAssertEqual(constDecl.attributes.count, 1)
ASTTextEqual(constDecl.attributes[0].name, "a")
XCTAssertEqual(constDecl.modifiers.count, 1)
XCTAssertEqual(constDecl.modifiers[0], .accessLevel(.fileprivate))
XCTAssertEqual(constDecl.initializerList.count, 1)
XCTAssertEqual(constDecl.initializerList[0].textDescription, "foo")
XCTAssertTrue(constDecl.initializerList[0].pattern is IdentifierPattern)
XCTAssertNil(constDecl.initializerList[0].initializerExpression)
})
}
func testFollowedByTrailingClosure() {
parseDeclarationAndTest(
"let foo = bar { $0 == 0 }",
"let foo = bar { $0 == 0 }",
testClosure: { decl in
guard let constDecl = decl as? ConstantDeclaration else {
XCTFail("Failed in getting a constant declaration.")
return
}
XCTAssertTrue(constDecl.attributes.isEmpty)
XCTAssertTrue(constDecl.modifiers.isEmpty)
XCTAssertEqual(constDecl.initializerList.count, 1)
XCTAssertEqual(constDecl.initializerList[0].textDescription, "foo = bar { $0 == 0 }")
XCTAssertTrue(constDecl.initializerList[0].pattern is IdentifierPattern)
XCTAssertTrue(constDecl.initializerList[0].initializerExpression is FunctionCallExpression)
})
parseDeclarationAndTest(
"let foo = bar { $0 = 0 }, a = b { _ in true }, x = y { t -> Int in t^2 }",
"let foo = bar { $0 = 0 }, a = b { _ in\ntrue\n}, x = y { t -> Int in\nt ^ 2\n}")
parseDeclarationAndTest(
"let foo = bar { $0 == 0 }.joined()",
"let foo = bar { $0 == 0 }.joined()")
}
func testFollowedBySemicolon() {
parseDeclarationAndTest("let issue = 61;", "let issue = 61")
}
func testSourceRange() {
parseDeclarationAndTest("let foo", "let foo", testClosure: { decl in
XCTAssertEqual(decl.sourceRange, getRange(1, 1, 1, 8))
})
parseDeclarationAndTest("@a let foo = bar, a, x = y", "@a let foo = bar, a, x = y", testClosure: { decl in
XCTAssertEqual(decl.sourceRange, getRange(1, 1, 1, 27))
})
parseDeclarationAndTest("private let foo, bar", "private let foo, bar", testClosure: { decl in
XCTAssertEqual(decl.sourceRange, getRange(1, 1, 1, 21))
})
parseDeclarationAndTest("let foo = bar { $0 == 0 }", "let foo = bar { $0 == 0 }", testClosure: { decl in
XCTAssertEqual(decl.sourceRange, getRange(1, 1, 1, 26))
})
}
static var allTests = [
("testDefineConstant", testDefineConstant),
("testDefineConstantWithTypeAnnotation", testDefineConstantWithTypeAnnotation),
("testDefineConstantWithInitializer", testDefineConstantWithInitializer),
("testMultipleDecls", testMultipleDecls),
("testAttributes", testAttributes),
("testModifiers", testModifiers),
("testAttributeAndModifiers", testAttributeAndModifiers),
("testFollowedByTrailingClosure", testFollowedByTrailingClosure),
("testFollowedBySemicolon", testFollowedBySemicolon),
("testSourceRange", testSourceRange),
]
}
| 48ab47f47676e9c6dfadd815fae33ca6 | 41.607656 | 110 | 0.71151 | false | true | false | false |
fredfoc/OpenWit | refs/heads/master | OpenWit/Classes/OpenWit.swift | mit | 1 | //
// OpenWit.swift
// OpenWit
//
// Created by fauquette fred on 22/11/16.
// Copyright © 2016 Fred Fauquette. All rights reserved.
//
import Foundation
import Moya
import Alamofire
import ObjectMapper
import CoreAudio
/// potential OpenWit Errors
///
/// - tokenIsUndefined: Wit token is not defined
/// - serverTokenIsUndefined: server Wit token is not defined
/// - noError: no Error (used to handle the statuscode of an answer
/// - jsonMapping: jsonMapping failed
/// - serialize: serializing failed
/// - networkError: network error
/// - underlying: underlying moya error
/// - internalError: internal server error (500...)
/// - authentication: authentication error (400...)
/// - progress: progress statuscode (this is considered as an error but that should probably not be... pobody's nerfect)
/// - redirection: redirection statuscode (this is considered as an error but that should probably not be... pobody's nerfect)
/// - messageNotEncodedCorrectly: encoding of message was not possible
/// - messageTooLong: message can not be more than 256 characters
/// - unknown: something strange happened and it can not be described... aliens, anarchie, utopia...
public enum OpenWitError: Swift.Error {
case tokenIsUndefined
case serverTokenIsUndefined
case noError
case jsonMapping(Moya.Response?)
case serialize(Moya.Response?)
case networkError(Moya.Response?)
case underlying(Moya.Error)
case internalError(Int)
case authentication(Int)
case progress
case redirection(Int)
case messageNotEncodedCorrectly
case messageTooLong
case unknown
}
enum OpenWitJsonKey: String {
case entities = "entities"
case quickreplies = "quickreplies"
case type = "type"
case confidence = "confidence"
case text = "_text"
case messageId = "msg_id"
case mainValue = "value"
case suggested = "suggested"
}
/// some error to handle the parsing of wit entities
///
/// - unknownEntity: the entity is not known
/// - mappingFailed: mapping failed (we could not parse the json to the mappable class you requested
public enum OpenWitEntityError: Swift.Error {
case unknownEntity
case mappingFailed
}
///See extension to get specific functionalities
/// the OpenWit singleton class
public class OpenWit {
/// the sharedInstance as this is a Singleton
public static let sharedInstance = OpenWit()
/// WIT Token access, for public calls like message, speech, converse (should be set in AppDelegate or when needed)
public var WITTokenAcces: String?
/// WIT Server access (used in some calls - to get all entities for example)
public var WITServerTokenAcces: String?
/// a value used if you want to mock all the answers
public var isMocked = false
/// the api version (see WIT documentation to change it - at the time this was done it was: 20160526)
public var apiVersion = "20160526"
private init(){
}
}
| 4672be139c70433b06ced3a51173660b | 31.888889 | 126 | 0.716892 | false | false | false | false |
ikesyo/swift-corelibs-foundation | refs/heads/master | Foundation/NumberFormatter.swift | apache-2.0 | 1 | // This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
import CoreFoundation
#if os(OSX) || os(iOS)
internal let kCFNumberFormatterNoStyle = CFNumberFormatterStyle.noStyle
internal let kCFNumberFormatterDecimalStyle = CFNumberFormatterStyle.decimalStyle
internal let kCFNumberFormatterCurrencyStyle = CFNumberFormatterStyle.currencyStyle
internal let kCFNumberFormatterPercentStyle = CFNumberFormatterStyle.percentStyle
internal let kCFNumberFormatterScientificStyle = CFNumberFormatterStyle.scientificStyle
internal let kCFNumberFormatterSpellOutStyle = CFNumberFormatterStyle.spellOutStyle
internal let kCFNumberFormatterOrdinalStyle = CFNumberFormatterStyle.ordinalStyle
internal let kCFNumberFormatterCurrencyISOCodeStyle = CFNumberFormatterStyle.currencyISOCodeStyle
internal let kCFNumberFormatterCurrencyPluralStyle = CFNumberFormatterStyle.currencyPluralStyle
internal let kCFNumberFormatterCurrencyAccountingStyle = CFNumberFormatterStyle.currencyAccountingStyle
#endif
extension NumberFormatter {
public enum Style : UInt {
case none
case decimal
case currency
case percent
case scientific
case spellOut
case ordinal
case currencyISOCode
case currencyPlural
case currencyAccounting
}
public enum PadPosition : UInt {
case beforePrefix
case afterPrefix
case beforeSuffix
case afterSuffix
}
public enum RoundingMode : UInt {
case ceiling
case floor
case down
case up
case halfEven
case halfDown
case halfUp
}
}
open class NumberFormatter : Formatter {
typealias CFType = CFNumberFormatter
private var _currentCfFormatter: CFType?
private var _cfFormatter: CFType {
if let obj = _currentCfFormatter {
return obj
} else {
#if os(OSX) || os(iOS)
let numberStyle = CFNumberFormatterStyle(rawValue: CFIndex(self.numberStyle.rawValue))!
#else
let numberStyle = CFNumberFormatterStyle(self.numberStyle.rawValue)
#endif
let obj = CFNumberFormatterCreate(kCFAllocatorSystemDefault, locale._cfObject, numberStyle)!
_setFormatterAttributes(obj)
if let format = _format {
CFNumberFormatterSetFormat(obj, format._cfObject)
}
_currentCfFormatter = obj
return obj
}
}
// this is for NSUnitFormatter
open var formattingContext: Context = .unknown // default is NSFormattingContextUnknown
// Report the used range of the string and an NSError, in addition to the usual stuff from Formatter
/// - Experiment: This is a draft API currently under consideration for official import into Foundation as a suitable alternative
/// - Note: Since this API is under consideration it may be either removed or revised in the near future
open func objectValue(_ string: String, range: inout NSRange) throws -> Any? { NSUnimplemented() }
open override func string(for obj: Any) -> String? {
//we need to allow Swift's numeric types here - Int, Double et al.
guard let number = _SwiftValue.store(obj) as? NSNumber else { return nil }
return string(from: number)
}
// Even though NumberFormatter responds to the usual Formatter methods,
// here are some convenience methods which are a little more obvious.
open func string(from number: NSNumber) -> String? {
return CFNumberFormatterCreateStringWithNumber(kCFAllocatorSystemDefault, _cfFormatter, number._cfObject)._swiftObject
}
open func number(from string: String) -> NSNumber? {
var range = CFRange(location: 0, length: string.length)
let number = withUnsafeMutablePointer(to: &range) { (rangePointer: UnsafeMutablePointer<CFRange>) -> NSNumber? in
#if os(OSX) || os(iOS)
let parseOption = allowsFloats ? 0 : CFNumberFormatterOptionFlags.parseIntegersOnly.rawValue
#else
let parseOption = allowsFloats ? 0 : CFOptionFlags(kCFNumberFormatterParseIntegersOnly)
#endif
let result = CFNumberFormatterCreateNumberFromString(kCFAllocatorSystemDefault, _cfFormatter, string._cfObject, rangePointer, parseOption)
return result?._nsObject
}
return number
}
open class func localizedString(from num: NSNumber, number nstyle: Style) -> String {
let numberFormatter = NumberFormatter()
numberFormatter.numberStyle = nstyle
return numberFormatter.string(for: num)!
}
internal func _reset() {
_currentCfFormatter = nil
}
internal func _setFormatterAttributes(_ formatter: CFNumberFormatter) {
_setFormatterAttribute(formatter, attributeName: kCFNumberFormatterCurrencyCode, value: _currencyCode?._cfObject)
_setFormatterAttribute(formatter, attributeName: kCFNumberFormatterDecimalSeparator, value: _decimalSeparator?._cfObject)
_setFormatterAttribute(formatter, attributeName: kCFNumberFormatterCurrencyDecimalSeparator, value: _currencyDecimalSeparator?._cfObject)
_setFormatterAttribute(formatter, attributeName: kCFNumberFormatterAlwaysShowDecimalSeparator, value: _alwaysShowsDecimalSeparator._cfObject)
_setFormatterAttribute(formatter, attributeName: kCFNumberFormatterGroupingSeparator, value: _groupingSeparator?._cfObject)
_setFormatterAttribute(formatter, attributeName: kCFNumberFormatterUseGroupingSeparator, value: _usesGroupingSeparator._cfObject)
_setFormatterAttribute(formatter, attributeName: kCFNumberFormatterPercentSymbol, value: _percentSymbol?._cfObject)
_setFormatterAttribute(formatter, attributeName: kCFNumberFormatterZeroSymbol, value: _zeroSymbol?._cfObject)
_setFormatterAttribute(formatter, attributeName: kCFNumberFormatterNaNSymbol, value: _notANumberSymbol?._cfObject)
_setFormatterAttribute(formatter, attributeName: kCFNumberFormatterInfinitySymbol, value: _positiveInfinitySymbol._cfObject)
_setFormatterAttribute(formatter, attributeName: kCFNumberFormatterMinusSign, value: _minusSign?._cfObject)
_setFormatterAttribute(formatter, attributeName: kCFNumberFormatterPlusSign, value: _plusSign?._cfObject)
_setFormatterAttribute(formatter, attributeName: kCFNumberFormatterCurrencySymbol, value: _currencySymbol?._cfObject)
_setFormatterAttribute(formatter, attributeName: kCFNumberFormatterExponentSymbol, value: _exponentSymbol?._cfObject)
_setFormatterAttribute(formatter, attributeName: kCFNumberFormatterMinIntegerDigits, value: _minimumIntegerDigits._bridgeToObjectiveC()._cfObject)
_setFormatterAttribute(formatter, attributeName: kCFNumberFormatterMaxIntegerDigits, value: _maximumIntegerDigits._bridgeToObjectiveC()._cfObject)
_setFormatterAttribute(formatter, attributeName: kCFNumberFormatterMinFractionDigits, value: _minimumFractionDigits._bridgeToObjectiveC()._cfObject)
if _minimumFractionDigits <= 0 {
_setFormatterAttribute(formatter, attributeName: kCFNumberFormatterMaxFractionDigits, value: _maximumFractionDigits._bridgeToObjectiveC()._cfObject)
}
_setFormatterAttribute(formatter, attributeName: kCFNumberFormatterGroupingSize, value: _groupingSize._bridgeToObjectiveC()._cfObject)
_setFormatterAttribute(formatter, attributeName: kCFNumberFormatterSecondaryGroupingSize, value: _secondaryGroupingSize._bridgeToObjectiveC()._cfObject)
_setFormatterAttribute(formatter, attributeName: kCFNumberFormatterRoundingMode, value: _roundingMode.rawValue._bridgeToObjectiveC()._cfObject)
_setFormatterAttribute(formatter, attributeName: kCFNumberFormatterRoundingIncrement, value: _roundingIncrement?._cfObject)
_setFormatterAttribute(formatter, attributeName: kCFNumberFormatterFormatWidth, value: _formatWidth._bridgeToObjectiveC()._cfObject)
_setFormatterAttribute(formatter, attributeName: kCFNumberFormatterPaddingCharacter, value: _paddingCharacter?._cfObject)
_setFormatterAttribute(formatter, attributeName: kCFNumberFormatterPaddingPosition, value: _paddingPosition.rawValue._bridgeToObjectiveC()._cfObject)
_setFormatterAttribute(formatter, attributeName: kCFNumberFormatterMultiplier, value: _multiplier?._cfObject)
_setFormatterAttribute(formatter, attributeName: kCFNumberFormatterPositivePrefix, value: _positivePrefix?._cfObject)
_setFormatterAttribute(formatter, attributeName: kCFNumberFormatterPositiveSuffix, value: _positiveSuffix?._cfObject)
_setFormatterAttribute(formatter, attributeName: kCFNumberFormatterNegativePrefix, value: _negativePrefix?._cfObject)
_setFormatterAttribute(formatter, attributeName: kCFNumberFormatterNegativeSuffix, value: _negativeSuffix?._cfObject)
_setFormatterAttribute(formatter, attributeName: kCFNumberFormatterPerMillSymbol, value: _percentSymbol?._cfObject)
_setFormatterAttribute(formatter, attributeName: kCFNumberFormatterInternationalCurrencySymbol, value: _internationalCurrencySymbol?._cfObject)
_setFormatterAttribute(formatter, attributeName: kCFNumberFormatterCurrencyGroupingSeparator, value: _currencyGroupingSeparator?._cfObject)
_setFormatterAttribute(formatter, attributeName: kCFNumberFormatterIsLenient, value: _lenient._cfObject)
_setFormatterAttribute(formatter, attributeName: kCFNumberFormatterUseSignificantDigits, value: _usesSignificantDigits._cfObject)
if _usesSignificantDigits {
_setFormatterAttribute(formatter, attributeName: kCFNumberFormatterMinSignificantDigits, value: _minimumSignificantDigits._bridgeToObjectiveC()._cfObject)
_setFormatterAttribute(formatter, attributeName: kCFNumberFormatterMaxSignificantDigits, value: _maximumSignificantDigits._bridgeToObjectiveC()._cfObject)
}
}
internal func _setFormatterAttribute(_ formatter: CFNumberFormatter, attributeName: CFString, value: AnyObject?) {
if let value = value {
CFNumberFormatterSetProperty(formatter, attributeName, value)
}
}
// Attributes of a NumberFormatter
internal var _numberStyle: Style = .none
open var numberStyle: Style {
get {
return _numberStyle
}
set {
switch newValue {
case .none, .ordinal, .spellOut:
_usesSignificantDigits = false
case .currency, .currencyPlural, .currencyISOCode, .currencyAccounting:
_usesSignificantDigits = false
_usesGroupingSeparator = true
_minimumFractionDigits = 2
case .decimal:
_usesGroupingSeparator = true
_maximumFractionDigits = 3
if _minimumIntegerDigits == 0 {
_minimumIntegerDigits = 1
}
if _groupingSize == 0 {
_groupingSize = 3
}
default:
_usesSignificantDigits = true
_usesGroupingSeparator = true
}
_reset()
_numberStyle = newValue
}
}
internal var _locale: Locale = Locale.current
/*@NSCopying*/ open var locale: Locale! {
get {
return _locale
}
set {
_reset()
_locale = newValue
}
}
internal var _generatesDecimalNumbers: Bool = false
open var generatesDecimalNumbers: Bool {
get {
return _generatesDecimalNumbers
}
set {
_reset()
_generatesDecimalNumbers = newValue
}
}
internal var _negativeFormat: String!
open var negativeFormat: String! {
get {
return _negativeFormat
}
set {
_reset()
_negativeFormat = newValue
}
}
internal var _textAttributesForNegativeValues: [String : Any]?
open var textAttributesForNegativeValues: [String : Any]? {
get {
return _textAttributesForNegativeValues
}
set {
_reset()
_textAttributesForNegativeValues = newValue
}
}
internal var _positiveFormat: String!
open var positiveFormat: String! {
get {
return _positiveFormat
}
set {
_reset()
_positiveFormat = newValue
}
}
internal var _textAttributesForPositiveValues: [String : Any]?
open var textAttributesForPositiveValues: [String : Any]? {
get {
return _textAttributesForPositiveValues
}
set {
_reset()
_textAttributesForPositiveValues = newValue
}
}
internal var _allowsFloats: Bool = true
open var allowsFloats: Bool {
get {
return _allowsFloats
}
set {
_reset()
_allowsFloats = newValue
}
}
internal var _decimalSeparator: String!
open var decimalSeparator: String! {
get {
return _decimalSeparator
}
set {
_reset()
_decimalSeparator = newValue
}
}
internal var _alwaysShowsDecimalSeparator: Bool = false
open var alwaysShowsDecimalSeparator: Bool {
get {
return _alwaysShowsDecimalSeparator
}
set {
_reset()
_alwaysShowsDecimalSeparator = newValue
}
}
internal var _currencyDecimalSeparator: String!
open var currencyDecimalSeparator: String! {
get {
return _currencyDecimalSeparator
}
set {
_reset()
_currencyDecimalSeparator = newValue
}
}
internal var _usesGroupingSeparator: Bool = false
open var usesGroupingSeparator: Bool {
get {
return _usesGroupingSeparator
}
set {
_reset()
_usesGroupingSeparator = newValue
}
}
internal var _groupingSeparator: String!
open var groupingSeparator: String! {
get {
return _groupingSeparator
}
set {
_reset()
_groupingSeparator = newValue
}
}
//
internal var _zeroSymbol: String?
open var zeroSymbol: String? {
get {
return _zeroSymbol
}
set {
_reset()
_zeroSymbol = newValue
}
}
internal var _textAttributesForZero: [String : Any]?
open var textAttributesForZero: [String : Any]? {
get {
return _textAttributesForZero
}
set {
_reset()
_textAttributesForZero = newValue
}
}
internal var _nilSymbol: String = ""
open var nilSymbol: String {
get {
return _nilSymbol
}
set {
_reset()
_nilSymbol = newValue
}
}
internal var _textAttributesForNil: [String : Any]?
open var textAttributesForNil: [String : Any]? {
get {
return _textAttributesForNil
}
set {
_reset()
_textAttributesForNil = newValue
}
}
internal var _notANumberSymbol: String!
open var notANumberSymbol: String! {
get {
return _notANumberSymbol
}
set {
_reset()
_notANumberSymbol = newValue
}
}
internal var _textAttributesForNotANumber: [String : Any]?
open var textAttributesForNotANumber: [String : Any]? {
get {
return _textAttributesForNotANumber
}
set {
_reset()
_textAttributesForNotANumber = newValue
}
}
internal var _positiveInfinitySymbol: String = "+∞"
open var positiveInfinitySymbol: String {
get {
return _positiveInfinitySymbol
}
set {
_reset()
_positiveInfinitySymbol = newValue
}
}
internal var _textAttributesForPositiveInfinity: [String : Any]?
open var textAttributesForPositiveInfinity: [String : Any]? {
get {
return _textAttributesForPositiveInfinity
}
set {
_reset()
_textAttributesForPositiveInfinity = newValue
}
}
internal var _negativeInfinitySymbol: String = "-∞"
open var negativeInfinitySymbol: String {
get {
return _negativeInfinitySymbol
}
set {
_reset()
_negativeInfinitySymbol = newValue
}
}
internal var _textAttributesForNegativeInfinity: [String : Any]?
open var textAttributesForNegativeInfinity: [String : Any]? {
get {
return _textAttributesForNegativeInfinity
}
set {
_reset()
_textAttributesForNegativeInfinity = newValue
}
}
//
internal var _positivePrefix: String!
open var positivePrefix: String! {
get {
return _positivePrefix
}
set {
_reset()
_positivePrefix = newValue
}
}
internal var _positiveSuffix: String!
open var positiveSuffix: String! {
get {
return _positiveSuffix
}
set {
_reset()
_positiveSuffix = newValue
}
}
internal var _negativePrefix: String!
open var negativePrefix: String! {
get {
return _negativePrefix
}
set {
_reset()
_negativePrefix = newValue
}
}
internal var _negativeSuffix: String!
open var negativeSuffix: String! {
get {
return _negativeSuffix
}
set {
_reset()
_negativeSuffix = newValue
}
}
internal var _currencyCode: String!
open var currencyCode: String! {
get {
return _currencyCode
}
set {
_reset()
_currencyCode = newValue
}
}
internal var _currencySymbol: String!
open var currencySymbol: String! {
get {
return _currencySymbol
}
set {
_reset()
_currencySymbol = newValue
}
}
internal var _internationalCurrencySymbol: String!
open var internationalCurrencySymbol: String! {
get {
return _internationalCurrencySymbol
}
set {
_reset()
_internationalCurrencySymbol = newValue
}
}
internal var _percentSymbol: String!
open var percentSymbol: String! {
get {
return _percentSymbol
}
set {
_reset()
_percentSymbol = newValue
}
}
internal var _perMillSymbol: String!
open var perMillSymbol: String! {
get {
return _perMillSymbol
}
set {
_reset()
_perMillSymbol = newValue
}
}
internal var _minusSign: String!
open var minusSign: String! {
get {
return _minusSign
}
set {
_reset()
_minusSign = newValue
}
}
internal var _plusSign: String!
open var plusSign: String! {
get {
return _plusSign
}
set {
_reset()
_plusSign = newValue
}
}
internal var _exponentSymbol: String!
open var exponentSymbol: String! {
get {
return _exponentSymbol
}
set {
_reset()
_exponentSymbol = newValue
}
}
//
internal var _groupingSize: Int = 0
open var groupingSize: Int {
get {
return _groupingSize
}
set {
_reset()
_groupingSize = newValue
}
}
internal var _secondaryGroupingSize: Int = 0
open var secondaryGroupingSize: Int {
get {
return _secondaryGroupingSize
}
set {
_reset()
_secondaryGroupingSize = newValue
}
}
internal var _multiplier: NSNumber?
/*@NSCopying*/ open var multiplier: NSNumber? {
get {
return _multiplier
}
set {
_reset()
_multiplier = newValue
}
}
internal var _formatWidth: Int = 0
open var formatWidth: Int {
get {
return _formatWidth
}
set {
_reset()
_formatWidth = newValue
}
}
internal var _paddingCharacter: String!
open var paddingCharacter: String! {
get {
return _paddingCharacter
}
set {
_reset()
_paddingCharacter = newValue
}
}
//
internal var _paddingPosition: PadPosition = .beforePrefix
open var paddingPosition: PadPosition {
get {
return _paddingPosition
}
set {
_reset()
_paddingPosition = newValue
}
}
internal var _roundingMode: RoundingMode = .halfEven
open var roundingMode: RoundingMode {
get {
return _roundingMode
}
set {
_reset()
_roundingMode = newValue
}
}
internal var _roundingIncrement: NSNumber! = 0
/*@NSCopying*/ open var roundingIncrement: NSNumber! {
get {
return _roundingIncrement
}
set {
_reset()
_roundingIncrement = newValue
}
}
internal var _minimumIntegerDigits: Int = 0
open var minimumIntegerDigits: Int {
get {
return _minimumIntegerDigits
}
set {
_reset()
_minimumIntegerDigits = newValue
}
}
internal var _maximumIntegerDigits: Int = 42
open var maximumIntegerDigits: Int {
get {
return _maximumIntegerDigits
}
set {
_reset()
_maximumIntegerDigits = newValue
}
}
internal var _minimumFractionDigits: Int = 0
open var minimumFractionDigits: Int {
get {
return _minimumFractionDigits
}
set {
_reset()
_minimumFractionDigits = newValue
}
}
internal var _maximumFractionDigits: Int = 0
open var maximumFractionDigits: Int {
get {
return _maximumFractionDigits
}
set {
_reset()
_maximumFractionDigits = newValue
}
}
internal var _minimum: NSNumber?
/*@NSCopying*/ open var minimum: NSNumber? {
get {
return _minimum
}
set {
_reset()
_minimum = newValue
}
}
internal var _maximum: NSNumber?
/*@NSCopying*/ open var maximum: NSNumber? {
get {
return _maximum
}
set {
_reset()
_maximum = newValue
}
}
internal var _currencyGroupingSeparator: String!
open var currencyGroupingSeparator: String! {
get {
return _currencyGroupingSeparator
}
set {
_reset()
_currencyGroupingSeparator = newValue
}
}
internal var _lenient: Bool = false
open var isLenient: Bool {
get {
return _lenient
}
set {
_reset()
_lenient = newValue
}
}
internal var _usesSignificantDigits: Bool = false
open var usesSignificantDigits: Bool {
get {
return _usesSignificantDigits
}
set {
_reset()
_usesSignificantDigits = newValue
}
}
internal var _minimumSignificantDigits: Int = 1
open var minimumSignificantDigits: Int {
get {
return _minimumSignificantDigits
}
set {
_reset()
_usesSignificantDigits = true
_minimumSignificantDigits = newValue
}
}
internal var _maximumSignificantDigits: Int = 6
open var maximumSignificantDigits: Int {
get {
return _maximumSignificantDigits
}
set {
_reset()
_usesSignificantDigits = true
_maximumSignificantDigits = newValue
}
}
internal var _partialStringValidationEnabled: Bool = false
open var isPartialStringValidationEnabled: Bool {
get {
return _partialStringValidationEnabled
}
set {
_reset()
_partialStringValidationEnabled = newValue
}
}
//
internal var _hasThousandSeparators: Bool = false
open var hasThousandSeparators: Bool {
get {
return _hasThousandSeparators
}
set {
_reset()
_hasThousandSeparators = newValue
}
}
internal var _thousandSeparator: String!
open var thousandSeparator: String! {
get {
return _thousandSeparator
}
set {
_reset()
_thousandSeparator = newValue
}
}
//
internal var _localizesFormat: Bool = true
open var localizesFormat: Bool {
get {
return _localizesFormat
}
set {
_reset()
_localizesFormat = newValue
}
}
//
internal var _format: String?
open var format: String {
get {
return _format ?? "#;0;#"
}
set {
_reset()
_format = newValue
}
}
//
internal var _attributedStringForZero: NSAttributedString = NSAttributedString(string: "0")
/*@NSCopying*/ open var attributedStringForZero: NSAttributedString {
get {
return _attributedStringForZero
}
set {
_reset()
_attributedStringForZero = newValue
}
}
internal var _attributedStringForNil: NSAttributedString = NSAttributedString(string: "")
/*@NSCopying*/ open var attributedStringForNil: NSAttributedString {
get {
return _attributedStringForNil
}
set {
_reset()
_attributedStringForNil = newValue
}
}
internal var _attributedStringForNotANumber: NSAttributedString = NSAttributedString(string: "NaN")
/*@NSCopying*/ open var attributedStringForNotANumber: NSAttributedString {
get {
return _attributedStringForNotANumber
}
set {
_reset()
_attributedStringForNotANumber = newValue
}
}
internal var _roundingBehavior: NSDecimalNumberHandler = NSDecimalNumberHandler.default
/*@NSCopying*/ open var roundingBehavior: NSDecimalNumberHandler {
get {
return _roundingBehavior
}
set {
_reset()
_roundingBehavior = newValue
}
}
}
| f1c9cce994786a90a09add536a543627 | 29.594743 | 166 | 0.598181 | false | false | false | false |
nathantannar4/InputBarAccessoryView | refs/heads/master | Example/Sources/InputBar Examples/GitHawkInputBar.swift | mit | 1 | //
// GitHawkInputBar.swift
// Example
//
// Created by Nathan Tannar on 2018-06-06.
// Copyright © 2018 Nathan Tannar. All rights reserved.
//
import UIKit
import InputBarAccessoryView
final class GitHawkInputBar: InputBarAccessoryView {
private let githawkImages: [UIImage] = [#imageLiteral(resourceName: "ic_eye"), #imageLiteral(resourceName: "ic_bold"), #imageLiteral(resourceName: "ic_italic"), #imageLiteral(resourceName: "ic_at"), #imageLiteral(resourceName: "ic_list"), #imageLiteral(resourceName: "ic_code"), #imageLiteral(resourceName: "ic_link"), #imageLiteral(resourceName: "ic_hashtag"), #imageLiteral(resourceName: "ic_upload")]
override init(frame: CGRect) {
super.init(frame: frame)
configure()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func configure() {
inputTextView.placeholder = "Leave a comment"
sendButton.contentEdgeInsets = UIEdgeInsets(top: 5, left: 5, bottom: 5, right: 5)
sendButton.setSize(CGSize(width: 36, height: 36), animated: false)
sendButton.image = #imageLiteral(resourceName: "ic_send").withRenderingMode(.alwaysTemplate)
sendButton.title = nil
sendButton.tintColor = tintColor
let layout = UICollectionViewFlowLayout()
layout.scrollDirection = .horizontal
layout.itemSize = CGSize(width: 20, height: 20)
layout.sectionInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 20)
let collectionView = AttachmentCollectionView(frame: .zero, collectionViewLayout: layout)
collectionView.intrinsicContentHeight = 20
collectionView.dataSource = self
collectionView.showsHorizontalScrollIndicator = false
collectionView.register(ImageCell.self, forCellWithReuseIdentifier: ImageCell.reuseIdentifier)
bottomStackView.addArrangedSubview(collectionView)
collectionView.reloadData()
}
}
extension GitHawkInputBar: UICollectionViewDataSource {
func numberOfSections(in collectionView: UICollectionView) -> Int {
return githawkImages.count
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: ImageCell.reuseIdentifier, for: indexPath) as! ImageCell
cell.imageView.image = githawkImages[indexPath.section].withRenderingMode(.alwaysTemplate)
cell.imageView.tintColor = .black
return cell
}
}
| e41d3bc91bd2fad675f236216276a76d | 40.666667 | 407 | 0.703636 | false | false | false | false |
skedgo/tripkit-ios | refs/heads/main | Sources/TripKit/server/TKError.swift | apache-2.0 | 1 | //
// TKUserError.swift
// TripKit
//
// Created by Adrian Schoenig on 20/10/2015.
// Copyright © 2015 SkedGo Pty Ltd. All rights reserved.
//
import Foundation
enum TKErrorCode: Int {
case unsupportedRegionCombination = 1001
case unsupportedOriginRegion = 1002
case unsupportedDestinationRegion = 1003
case destinationTooCloseToOrigin = 1101
case noOrigin = 1102
case noDestination = 1103
case timeTooOld = 1201
case departureTimeTooOld = 1202
case arrivalTimeTooOld = 1203
case userError = 30051
case internalError = 30052
}
class TKUserError: TKError {
override var isUserError: Bool {
return true
}
}
class TKServerError: TKError {
}
public class TKError: NSError {
@objc public var title: String?
public var details: TKAPI.ServerError?
@objc
public class func error(withCode code: Int, userInfo dict: [String: Any]?) -> TKError {
return TKError(domain: "com.skedgo.serverkit", code: code, userInfo: dict)
}
public class func error(from data: Data?, statusCode: Int) -> TKError? {
if let data = data {
// If there was a response body, we used that to see if it's an error
// returned from the API.
return TKError.error(from: data, domain: "com.skedgo.serverkit")
} else {
// Otherwise we check if the status code is indicating an error
switch statusCode {
case 404, 500...599:
return TKError.error(withCode: statusCode, userInfo: nil)
default:
return nil
}
}
}
class func error(from data: Data, domain: String) -> TKError? {
guard let parsed = try? JSONDecoder().decode(TKAPI.ServerError.self, from: data) else { return nil }
var code = Int(parsed.isUserError ? TKErrorCode.userError.rawValue : TKErrorCode.internalError.rawValue)
if let errorCode = parsed.errorCode {
code = errorCode
}
let userInfo: [String: Any] = [
NSLocalizedDescriptionKey: parsed.errorMessage ?? parsed.title ?? Loc.ServerError,
"TKIsUserError": parsed.isUserError
]
let error: TKError
if parsed.isUserError {
error = TKUserError(domain: domain, code: code, userInfo: userInfo)
} else {
error = TKServerError(domain: domain, code: code, userInfo: userInfo)
}
error.title = parsed.title
error.details = parsed
return error
}
@objc
public var isUserError: Bool {
if let userError = userInfo["TKIsUserError"] as? Bool {
return userError
} else {
return code >= 400 && code < 500
}
}
}
extension TKAPI {
public struct ServerError: Codable {
public let errorMessage: String?
public let isUserError: Bool
public let errorCode: Int?
public let title: String?
public let recovery: String?
public let url: URL?
public let option: Option?
public enum Option: String, Codable {
case back = "BACK"
case retry = "RETRY"
case abort = "ABORT"
}
enum CodingKeys: String, CodingKey {
case errorMessage = "error"
case isUserError = "usererror"
case errorCode
case title
case recovery = "recoveryTitle"
case url
case option = "recovery"
}
}
}
| 0d07e5de69c98cda0a17d8abcc5fb1d0 | 26.360656 | 108 | 0.633313 | false | false | false | false |
huangboju/Moots | refs/heads/master | UICollectionViewLayout/wwdc_demo/ImageFeed/Layouts/ColumnFlowLayout.swift | mit | 1 | /*
See LICENSE folder for this sample’s licensing information.
Abstract:
Custom view flow layout for single column or multiple columns.
*/
import UIKit
class ColumnFlowLayout: UICollectionViewFlowLayout {
private let minColumnWidth: CGFloat = 300.0
private let cellHeight: CGFloat = 70.0
private var deletingIndexPaths = [IndexPath]()
private var insertingIndexPaths = [IndexPath]()
// MARK: Layout Overrides
/// - Tag: ColumnFlowExample
override func prepare() {
super.prepare()
guard let collectionView = collectionView else { return }
let availableWidth = collectionView.bounds.inset(by: collectionView.layoutMargins).width
let maxNumColumns = Int(availableWidth / minColumnWidth)
let cellWidth = (availableWidth / CGFloat(maxNumColumns)).rounded(.down)
self.itemSize = CGSize(width: cellWidth, height: cellHeight)
self.sectionInset = UIEdgeInsets(top: self.minimumInteritemSpacing, left: 0.0, bottom: 0.0, right: 0.0)
if #available(iOS 11.0, *) {
self.sectionInsetReference = .fromSafeArea
} else {
// Fallback on earlier versions
}
}
// MARK: Attributes for Updated Items
override func finalLayoutAttributesForDisappearingItem(at itemIndexPath: IndexPath) -> UICollectionViewLayoutAttributes? {
guard let attributes = super.finalLayoutAttributesForDisappearingItem(at: itemIndexPath) else { return nil }
if !deletingIndexPaths.isEmpty {
if deletingIndexPaths.contains(itemIndexPath) {
attributes.transform = CGAffineTransform(scaleX: 0.5, y: 0.5)
attributes.alpha = 0.0
attributes.zIndex = 0
}
}
return attributes
}
override func initialLayoutAttributesForAppearingItem(at itemIndexPath: IndexPath) -> UICollectionViewLayoutAttributes? {
guard let attributes = super.initialLayoutAttributesForAppearingItem(at: itemIndexPath) else { return nil }
if insertingIndexPaths.contains(itemIndexPath) {
attributes.transform = CGAffineTransform(scaleX: 0.5, y: 0.5)
attributes.alpha = 0.0
attributes.zIndex = 0
}
return attributes
}
// MARK: Updates
override func prepare(forCollectionViewUpdates updateItems: [UICollectionViewUpdateItem]) {
super.prepare(forCollectionViewUpdates: updateItems)
for update in updateItems {
switch update.updateAction {
case .delete:
guard let indexPath = update.indexPathBeforeUpdate else { return }
deletingIndexPaths.append(indexPath)
case .insert:
guard let indexPath = update.indexPathAfterUpdate else { return }
insertingIndexPaths.append(indexPath)
default:
break
}
}
}
override func finalizeCollectionViewUpdates() {
super.finalizeCollectionViewUpdates()
deletingIndexPaths.removeAll()
insertingIndexPaths.removeAll()
}
}
| be88ea2ec3697c7601ae0c4cda8c34ea | 33.677419 | 126 | 0.63969 | false | false | false | false |
apple/swift-system | refs/heads/main | Sources/System/FilePermissions.swift | apache-2.0 | 1 | /*
This source file is part of the Swift System open source project
Copyright (c) 2020 Apple Inc. and the Swift System project authors
Licensed under Apache License v2.0 with Runtime Library Exception
See https://swift.org/LICENSE.txt for license information
*/
/// The access permissions for a file.
///
/// The following example
/// creates an instance of the `FilePermissions` structure
/// from a raw octal literal and compares it
/// to a file permission created using named options:
///
/// let perms = FilePermissions(rawValue: 0o644)
/// perms == [.ownerReadWrite, .groupRead, .otherRead] // true
@frozen
/*System 0.0.1, @available(macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0, *)*/
public struct FilePermissions: OptionSet, Hashable, Codable {
/// The raw C file permissions.
@_alwaysEmitIntoClient
public let rawValue: CInterop.Mode
/// Create a strongly-typed file permission from a raw C value.
@_alwaysEmitIntoClient
public init(rawValue: CInterop.Mode) { self.rawValue = rawValue }
@_alwaysEmitIntoClient
private init(_ raw: CInterop.Mode) { self.init(rawValue: raw) }
/// Indicates that other users have read-only permission.
@_alwaysEmitIntoClient
public static var otherRead: FilePermissions { FilePermissions(0o4) }
/// Indicates that other users have write-only permission.
@_alwaysEmitIntoClient
public static var otherWrite: FilePermissions { FilePermissions(0o2) }
/// Indicates that other users have execute-only permission.
@_alwaysEmitIntoClient
public static var otherExecute: FilePermissions { FilePermissions(0o1) }
/// Indicates that other users have read-write permission.
@_alwaysEmitIntoClient
public static var otherReadWrite: FilePermissions { FilePermissions(0o6) }
/// Indicates that other users have read-execute permission.
@_alwaysEmitIntoClient
public static var otherReadExecute: FilePermissions { FilePermissions(0o5) }
/// Indicates that other users have write-execute permission.
@_alwaysEmitIntoClient
public static var otherWriteExecute: FilePermissions { FilePermissions(0o3) }
/// Indicates that other users have read, write, and execute permission.
@_alwaysEmitIntoClient
public static var otherReadWriteExecute: FilePermissions { FilePermissions(0o7) }
/// Indicates that the group has read-only permission.
@_alwaysEmitIntoClient
public static var groupRead: FilePermissions { FilePermissions(0o40) }
/// Indicates that the group has write-only permission.
@_alwaysEmitIntoClient
public static var groupWrite: FilePermissions { FilePermissions(0o20) }
/// Indicates that the group has execute-only permission.
@_alwaysEmitIntoClient
public static var groupExecute: FilePermissions { FilePermissions(0o10) }
/// Indicates that the group has read-write permission.
@_alwaysEmitIntoClient
public static var groupReadWrite: FilePermissions { FilePermissions(0o60) }
/// Indicates that the group has read-execute permission.
@_alwaysEmitIntoClient
public static var groupReadExecute: FilePermissions { FilePermissions(0o50) }
/// Indicates that the group has write-execute permission.
@_alwaysEmitIntoClient
public static var groupWriteExecute: FilePermissions { FilePermissions(0o30) }
/// Indicates that the group has read, write, and execute permission.
@_alwaysEmitIntoClient
public static var groupReadWriteExecute: FilePermissions { FilePermissions(0o70) }
/// Indicates that the owner has read-only permission.
@_alwaysEmitIntoClient
public static var ownerRead: FilePermissions { FilePermissions(0o400) }
/// Indicates that the owner has write-only permission.
@_alwaysEmitIntoClient
public static var ownerWrite: FilePermissions { FilePermissions(0o200) }
/// Indicates that the owner has execute-only permission.
@_alwaysEmitIntoClient
public static var ownerExecute: FilePermissions { FilePermissions(0o100) }
/// Indicates that the owner has read-write permission.
@_alwaysEmitIntoClient
public static var ownerReadWrite: FilePermissions { FilePermissions(0o600) }
/// Indicates that the owner has read-execute permission.
@_alwaysEmitIntoClient
public static var ownerReadExecute: FilePermissions { FilePermissions(0o500) }
/// Indicates that the owner has write-execute permission.
@_alwaysEmitIntoClient
public static var ownerWriteExecute: FilePermissions { FilePermissions(0o300) }
/// Indicates that the owner has read, write, and execute permission.
@_alwaysEmitIntoClient
public static var ownerReadWriteExecute: FilePermissions { FilePermissions(0o700) }
/// Indicates that the file is executed as the owner.
///
/// For more information, see the `setuid(2)` man page.
@_alwaysEmitIntoClient
public static var setUserID: FilePermissions { FilePermissions(0o4000) }
/// Indicates that the file is executed as the group.
///
/// For more information, see the `setgid(2)` man page.
@_alwaysEmitIntoClient
public static var setGroupID: FilePermissions { FilePermissions(0o2000) }
/// Indicates that executable's text segment
/// should be kept in swap space even after it exits.
///
/// For more information, see the `chmod(2)` man page's
/// discussion of `S_ISVTX` (the sticky bit).
@_alwaysEmitIntoClient
public static var saveText: FilePermissions { FilePermissions(0o1000) }
}
/*System 0.0.1, @available(macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0, *)*/
extension FilePermissions
: CustomStringConvertible, CustomDebugStringConvertible
{
/// A textual representation of the file permissions.
@inline(never)
public var description: String {
let descriptions: [(Element, StaticString)] = [
(.ownerReadWriteExecute, ".ownerReadWriteExecute"),
(.ownerReadWrite, ".ownerReadWrite"),
(.ownerReadExecute, ".ownerReadExecute"),
(.ownerWriteExecute, ".ownerWriteExecute"),
(.ownerRead, ".ownerRead"),
(.ownerWrite, ".ownerWrite"),
(.ownerExecute, ".ownerExecute"),
(.groupReadWriteExecute, ".groupReadWriteExecute"),
(.groupReadWrite, ".groupReadWrite"),
(.groupReadExecute, ".groupReadExecute"),
(.groupWriteExecute, ".groupWriteExecute"),
(.groupRead, ".groupRead"),
(.groupWrite, ".groupWrite"),
(.groupExecute, ".groupExecute"),
(.otherReadWriteExecute, ".otherReadWriteExecute"),
(.otherReadWrite, ".otherReadWrite"),
(.otherReadExecute, ".otherReadExecute"),
(.otherWriteExecute, ".otherWriteExecute"),
(.otherRead, ".otherRead"),
(.otherWrite, ".otherWrite"),
(.otherExecute, ".otherExecute"),
(.setUserID, ".setUserID"),
(.setGroupID, ".setGroupID"),
(.saveText, ".saveText")
]
return _buildDescription(descriptions)
}
/// A textual representation of the file permissions, suitable for debugging.
public var debugDescription: String { self.description }
}
| a94a106ab5d3049834de8c64ee324105 | 38.062147 | 85 | 0.736766 | false | false | false | false |
huangboju/Moots | refs/heads/master | Examples/SwiftUI/SwiftUI-Apple/InterfacingWithUIKit/StartingPoint/Landmarks/Landmarks/Models/Data.swift | mit | 1 | /*
See LICENSE folder for this sample’s licensing information.
Abstract:
Helpers for loading images and data.
*/
import Foundation
import CoreLocation
import UIKit
import SwiftUI
let landmarkData: [Landmark] = load("landmarkData.json")
let features = landmarkData.filter { $0.isFeatured }
let hikeData: [Hike] = load("hikeData.json")
func load<T: Decodable>(_ filename: String) -> T {
let data: Data
guard let file = Bundle.main.url(forResource: filename, withExtension: nil)
else {
fatalError("Couldn't find \(filename) in main bundle.")
}
do {
data = try Data(contentsOf: file)
} catch {
fatalError("Couldn't load \(filename) from main bundle:\n\(error)")
}
do {
let decoder = JSONDecoder()
return try decoder.decode(T.self, from: data)
} catch {
fatalError("Couldn't parse \(filename) as \(T.self):\n\(error)")
}
}
final class ImageStore {
typealias _ImageDictionary = [String: CGImage]
fileprivate var images: _ImageDictionary = [:]
fileprivate static var scale = 2
static var shared = ImageStore()
func image(name: String) -> Image {
let index = _guaranteeImage(name: name)
return Image(images.values[index], scale: CGFloat(ImageStore.scale), label: Text(name))
}
static func loadImage(name: String) -> CGImage {
guard
let url = Bundle.main.url(forResource: name, withExtension: "jpg"),
let imageSource = CGImageSourceCreateWithURL(url as NSURL, nil),
let image = CGImageSourceCreateImageAtIndex(imageSource, 0, nil)
else {
fatalError("Couldn't load image \(name).jpg from main bundle.")
}
return image
}
fileprivate func _guaranteeImage(name: String) -> _ImageDictionary.Index {
if let index = images.index(forKey: name) { return index }
images[name] = ImageStore.loadImage(name: name)
return images.index(forKey: name)!
}
}
| 44b0255c629fa8fb8750293514e8266f | 27.661972 | 95 | 0.631941 | false | false | false | false |
narner/AudioKit | refs/heads/master | Examples/iOS/AnalogSynthX/AnalogSynthX/AudioSystem/GeneratorBank.swift | mit | 1 | //
// GeneratorBank.swift
// AnalogSynthX
//
// Created by Aurelius Prochazka on 6/25/16.
// Copyright © 2016 AudioKit. All rights reserved.
//
import AudioKit
class GeneratorBank: AKPolyphonicNode {
func updateWaveform1() {
vco1.index = (0...3).clamp(waveform1 + morph)
}
func updateWaveform2() {
vco2.index = (0...3).clamp(waveform2 + morph)
}
var waveform1 = 0.0 { didSet { updateWaveform1() } }
var waveform2 = 0.0 { didSet { updateWaveform2() } }
var globalbend: Double = 1.0 {
didSet {
vco1.pitchBend = globalbend
vco2.pitchBend = globalbend
subOsc.pitchBend = globalbend
fmOsc.pitchBend = globalbend
}
}
var offset1 = 0 {
willSet {
for noteNumber in onNotes {
vco1.stop(noteNumber: MIDINoteNumber(Int(noteNumber) + offset1))
vco1.play(noteNumber: MIDINoteNumber(Int(noteNumber) + newValue), velocity: 127)
}
}
}
var offset2 = 0 {
willSet {
for noteNumber in onNotes {
vco2.stop(noteNumber: MIDINoteNumber(Int(noteNumber) + offset2))
vco2.play(noteNumber: MIDINoteNumber(Int(noteNumber) + newValue), velocity: 127)
}
}
}
var morph: Double = 0.0 {
didSet {
updateWaveform1()
updateWaveform2()
}
}
/// Attack time
var attackDuration: Double = 0.1 {
didSet {
if attackDuration < 0.02 { attackDuration = 0.02 }
vco1.attackDuration = attackDuration
vco2.attackDuration = attackDuration
subOsc.attackDuration = attackDuration
fmOsc.attackDuration = attackDuration
noiseADSR.attackDuration = attackDuration
}
}
/// Decay time
var decayDuration: Double = 0.1 {
didSet {
if decayDuration < 0.02 { decayDuration = 0.02 }
vco1.decayDuration = decayDuration
vco2.decayDuration = decayDuration
subOsc.decayDuration = decayDuration
fmOsc.decayDuration = decayDuration
noiseADSR.decayDuration = decayDuration
}
}
/// Sustain Level
var sustainLevel: Double = 0.66 {
didSet {
vco1.sustainLevel = sustainLevel
vco2.sustainLevel = sustainLevel
subOsc.sustainLevel = sustainLevel
fmOsc.sustainLevel = sustainLevel
noiseADSR.sustainLevel = sustainLevel
}
}
/// Release time
var releaseDuration: Double = 0.5 {
didSet {
if releaseDuration < 0.02 { releaseDuration = 0.02 }
vco1.releaseDuration = releaseDuration
vco2.releaseDuration = releaseDuration
subOsc.releaseDuration = releaseDuration
fmOsc.releaseDuration = releaseDuration
noiseADSR.releaseDuration = releaseDuration
}
}
var vco1On = true {
didSet {
vco1Mixer.volume = vco1On ? 1.0 : 0.0
}
}
var vco2On = true {
didSet {
vco2Mixer.volume = vco2On ? 1.0 : 0.0
}
}
var vco1: AKMorphingOscillatorBank
var vco2: AKMorphingOscillatorBank
var subOsc = AKOscillatorBank()
var fmOsc = AKFMOscillatorBank()
var noise = AKWhiteNoise()
var noiseADSR: AKAmplitudeEnvelope
// We'll be using these simply to control volume independent of velocity
var vco1Mixer: AKMixer
var vco2Mixer: AKMixer
var subOscMixer: AKMixer
var fmOscMixer: AKMixer
var noiseMixer: AKMixer
var vcoBalancer: AKDryWetMixer
var sourceMixer: AKMixer
var onNotes = Set<MIDINoteNumber>()
override init() {
let triangle = AKTable(.triangle)
let square = AKTable(.square)
let sawtooth = AKTable(.sawtooth)
let squareWithHighPWM = AKTable()
let count = squareWithHighPWM.count
for i in squareWithHighPWM.indices {
if i < count / 8 {
squareWithHighPWM[i] = -1.0
} else {
squareWithHighPWM[i] = 1.0
}
}
vco1 = AKMorphingOscillatorBank(waveformArray: [triangle, square, squareWithHighPWM, sawtooth])
vco2 = AKMorphingOscillatorBank(waveformArray: [triangle, square, squareWithHighPWM, sawtooth])
noiseADSR = AKAmplitudeEnvelope(noise)
vco1Mixer = AKMixer(vco1)
vco2Mixer = AKMixer(vco2)
subOscMixer = AKMixer(subOsc)
fmOscMixer = AKMixer(fmOsc)
noiseMixer = AKMixer(noiseADSR)
// Default non-VCO's off
subOscMixer.volume = 0
fmOscMixer.volume = 0
noiseMixer.volume = 0
vcoBalancer = AKDryWetMixer(vco1Mixer, vco2Mixer, balance: 0.5)
sourceMixer = AKMixer(vcoBalancer, fmOscMixer, subOscMixer, noiseMixer)
super.init()
avAudioNode = sourceMixer.avAudioNode
}
/// Function to start, play, or activate the node, all do the same thing
override func play(noteNumber: MIDINoteNumber, velocity: MIDIVelocity) {
vco1.play(noteNumber: MIDINoteNumber(Int(noteNumber) + offset1), velocity: velocity)
vco2.play(noteNumber: MIDINoteNumber(Int(noteNumber) + offset2), velocity: velocity)
if noteNumber >= 12 {
subOsc.play(noteNumber: noteNumber - 12, velocity: velocity)
}
fmOsc.play(noteNumber: noteNumber, velocity: velocity)
if onNotes.isEmpty {
noise.start()
noiseADSR.start()
}
onNotes.insert(noteNumber)
}
/// Function to stop or bypass the node, both are equivalent
override func stop(noteNumber: MIDINoteNumber) {
vco1.stop(noteNumber: MIDINoteNumber(Int(noteNumber) + offset1))
vco2.stop(noteNumber: MIDINoteNumber(Int(noteNumber) + offset2))
if noteNumber >= 12 {
subOsc.stop(noteNumber: noteNumber - 12)
}
fmOsc.stop(noteNumber: noteNumber)
onNotes.remove(noteNumber)
if onNotes.isEmpty {
noiseADSR.stop()
}
}
}
| 0bc111134b305046e7031d8999eb6c0d | 28.854369 | 103 | 0.601789 | false | false | false | false |
CatchChat/Yep | refs/heads/master | Yep/Extensions/UIViewController+Yep.swift | mit | 1 | //
// UIViewController+Yep.swift
// Yep
//
// Created by NIX on 15/7/27.
// Copyright (c) 2015年 Catch Inc. All rights reserved.
//
import UIKit
import SafariServices
import YepKit
import YepNetworking
import AutoReview
// MAKR: - Heights
extension UIViewController {
var statusBarHeight: CGFloat {
if let window = view.window {
let statusBarFrame = window.convertRect(UIApplication.sharedApplication().statusBarFrame, toView: view)
return statusBarFrame.height
} else {
return 0
}
}
var navigationBarHeight: CGFloat {
if let navigationController = navigationController {
return navigationController.navigationBar.frame.height
} else {
return 0
}
}
var topBarsHeight: CGFloat {
return statusBarHeight + navigationBarHeight
}
}
// MAKR: - Report
extension ReportReason {
var title: String {
switch self {
case .Porno:
return String.trans_reportPorno
case .Advertising:
return String.trans_reportAdvertising
case .Scams:
return String.trans_reportScams
case .Other:
return String.trans_reportOther
}
}
}
extension UIViewController {
enum ReportObject {
case User(ProfileUser)
case Feed(feedID: String)
case Message(messageID: String)
}
func report(object: ReportObject) {
let reportWithReason: ReportReason -> Void = { [weak self] reason in
switch object {
case .User(let profileUser):
reportProfileUser(profileUser, forReason: reason, failureHandler: { [weak self] (reason, errorMessage) in
defaultFailureHandler(reason: reason, errorMessage: errorMessage)
if let errorMessage = errorMessage {
YepAlert.alertSorry(message: errorMessage, inViewController: self)
}
}, completion: {
})
case .Feed(let feedID):
reportFeedWithFeedID(feedID, forReason: reason, failureHandler: { [weak self] (reason, errorMessage) in
defaultFailureHandler(reason: reason, errorMessage: errorMessage)
if let errorMessage = errorMessage {
YepAlert.alertSorry(message: errorMessage, inViewController: self)
}
}, completion: {
})
case .Message(let messageID):
reportMessageWithMessageID(messageID, forReason: reason, failureHandler: { [weak self] (reason, errorMessage) in
defaultFailureHandler(reason: reason, errorMessage: errorMessage)
if let errorMessage = errorMessage {
YepAlert.alertSorry(message: errorMessage, inViewController: self)
}
}, completion: {
})
}
}
let reportAlertController = UIAlertController(title: NSLocalizedString("Report Reason", comment: ""), message: nil, preferredStyle: .ActionSheet)
let pornoReasonAction: UIAlertAction = UIAlertAction(title: ReportReason.Porno.title, style: .Default) { _ in
reportWithReason(.Porno)
}
reportAlertController.addAction(pornoReasonAction)
let advertisingReasonAction: UIAlertAction = UIAlertAction(title: ReportReason.Advertising.title, style: .Default) { _ in
reportWithReason(.Advertising)
}
reportAlertController.addAction(advertisingReasonAction)
let scamsReasonAction: UIAlertAction = UIAlertAction(title: ReportReason.Scams.title, style: .Default) { _ in
reportWithReason(.Scams)
}
reportAlertController.addAction(scamsReasonAction)
let otherReasonAction: UIAlertAction = UIAlertAction(title: ReportReason.Other("").title, style: .Default) { [weak self] _ in
YepAlert.textInput(title: NSLocalizedString("Other Reason", comment: ""), message: nil, placeholder: nil, oldText: nil, confirmTitle: NSLocalizedString("OK", comment: ""), cancelTitle: String.trans_cancel, inViewController: self, withConfirmAction: { text in
reportWithReason(.Other(text))
}, cancelAction: nil)
}
reportAlertController.addAction(otherReasonAction)
let cancelAction: UIAlertAction = UIAlertAction(title: String.trans_cancel, style: .Cancel) { [weak self] _ in
self?.dismissViewControllerAnimated(true, completion: nil)
}
reportAlertController.addAction(cancelAction)
self.presentViewController(reportAlertController, animated: true, completion: nil)
}
}
// MAKR: - openURL
extension UIViewController {
func yep_openURL(URL: NSURL) {
if let URL = URL.yep_validSchemeNetworkURL {
let safariViewController = SFSafariViewController(URL: URL)
presentViewController(safariViewController, animated: true, completion: nil)
} else {
YepAlert.alertSorry(message: NSLocalizedString("Invalid URL!", comment: ""), inViewController: self)
}
}
}
// MARK: - Review
extension UIViewController {
func remindUserToReview() {
let remindAction: dispatch_block_t = { [weak self] in
guard self?.view.window != nil else {
return
}
let info = AutoReview.Info(
appID: "983891256",
title: NSLocalizedString("Review Yep", comment: ""),
message: NSLocalizedString("Do you like Yep?\nWould you like to review it on the App Store?", comment: ""),
doNotRemindMeInThisVersionTitle: NSLocalizedString("Do not remind me in this version", comment: ""),
maybeNextTimeTitle: NSLocalizedString("Maybe next time", comment: ""),
confirmTitle: NSLocalizedString("Review now", comment: "")
)
self?.autoreview_tryReviewApp(withInfo: info)
}
delay(3, work: remindAction)
}
}
// MARK: - Alert
extension UIViewController {
func alertSaveFileFailed() {
YepAlert.alertSorry(message: NSLocalizedString("Yep can not save files!\nProbably not enough storage space.", comment: ""), inViewController: self)
}
}
| aed694ed1ec637fbb1ba0d42c930d44f | 31.668367 | 270 | 0.622365 | false | false | false | false |
tutsplus/watchos-2-from-scratch | refs/heads/master | Stocks WatchKit Extension/YQL.swift | bsd-2-clause | 1 | //
// YQL.swift
// Stocks
//
// Created by Derek Jensen on 11/19/15.
// Copyright © 2015 Derek Jensen. All rights reserved.
//
import Foundation
public class YQL
{
private class var prefix: String {
return "http://query.yahooapis.com/v1/public/yql?q="
}
private class var suffix: String {
return "&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&callback=";
}
public class func query(statement: String) -> NSDictionary
{
let query = "\(prefix)\(statement.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet())!)\(suffix)"
let jsonData = (try? String(contentsOfURL: NSURL(string: query)!, encoding: NSUTF8StringEncoding))?.dataUsingEncoding(NSUTF8StringEncoding)
let result = { _ -> NSDictionary in
if let data = jsonData
{
return (try! NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers)) as! NSDictionary
}
return NSDictionary()
}()
return result;
}
}
| 6c5cd3657eb9ba1182311477e2ff57a3 | 29.473684 | 150 | 0.634715 | false | false | false | false |
s-aska/Justaway-for-iOS | refs/heads/master | Justaway/NotificationsViewController.swift | mit | 1 | //
// NotificationsViewController.swift
// Justaway
//
// Created by Shinichiro Aska on 1/25/15.
// Copyright (c) 2015 Shinichiro Aska. All rights reserved.
//
import Foundation
import KeyClip
import Async
class NotificationsViewController: StatusTableViewController {
var maxMentionID: String?
override func saveCache() {
if self.adapter.rows.count > 0 {
guard let account = AccountSettingsStore.get()?.account() else {
return
}
let key = "notifications:\(account.userID)"
let statuses = self.adapter.statuses
let dictionary = ["statuses": ( statuses.count > 100 ? Array(statuses[0 ..< 100]) : statuses ).map({ $0.dictionaryValue })]
_ = KeyClip.save(key, dictionary: dictionary as NSDictionary)
NSLog("notifications saveCache.")
}
}
override func loadCache(_ success: @escaping ((_ statuses: [TwitterStatus]) -> Void), failure: @escaping ((_ error: NSError) -> Void)) {
adapter.activityMode = true
maxMentionID = nil
Async.background {
guard let account = AccountSettingsStore.get()?.account() else {
return
}
let oldKey = "notifications:\(account.userID)"
_ = KeyClip.delete(oldKey)
let key = "notifications-v2:\(account.userID)"
if let cache = KeyClip.load(key) as NSDictionary? {
if let statuses = cache["statuses"] as? [[String: AnyObject]], statuses.count > 0 {
success(statuses.map({ TwitterStatus($0) }))
return
}
}
success([TwitterStatus]())
Async.background(after: 0.4, { () -> Void in
self.loadData(nil)
})
}
}
override func refresh() {
maxMentionID = nil
loadData(nil)
}
override func loadData(_ maxID: String?, success: @escaping ((_ statuses: [TwitterStatus]) -> Void), failure: @escaping ((_ error: NSError) -> Void)) {
guard let account = AccountSettingsStore.get()?.account() else {
return
}
if account.exToken.isEmpty {
Twitter.getMentionTimeline(maxID: maxID, success: success, failure: failure)
} else {
let activitySuccess = { (statuses: [TwitterStatus], maxMentionID: String?) -> Void in
if let maxMentionID = maxMentionID {
self.maxMentionID = maxMentionID
}
success(statuses)
}
Twitter.getActivity(maxID: maxID, maxMentionID: maxMentionID, success: activitySuccess, failure: failure)
}
}
override func loadData(sinceID: String?, maxID: String?, success: @escaping ((_ statuses: [TwitterStatus]) -> Void), failure: @escaping ((_ error: NSError) -> Void)) {
guard let account = AccountSettingsStore.get()?.account() else {
return
}
if account.exToken.isEmpty {
Twitter.getMentionTimeline(maxID: maxID, sinceID: sinceID, success: success, failure: failure)
} else {
let activitySuccess = { (statuses: [TwitterStatus], maxMentionID: String?) -> Void in
if let maxMentionID = maxMentionID {
self.maxMentionID = maxMentionID
}
success(statuses)
}
Twitter.getActivity(maxID: maxID, sinceID: sinceID, maxMentionID: maxMentionID, success: activitySuccess, failure: failure)
}
}
override func accept(_ status: TwitterStatus) -> Bool {
if let event = status.event {
if let accountSettings = AccountSettingsStore.get() {
if let actionedBy = status.actionedBy {
if accountSettings.isMe(actionedBy.userID) {
return false
}
} else {
if accountSettings.isMe(status.user.userID) {
return false
}
}
}
if event == "quoted_tweet" || event == "favorited_retweet" || event == "retweeted_retweet" {
return true
}
}
if let accountSettings = AccountSettingsStore.get() {
if let actionedBy = status.actionedBy {
if accountSettings.isMe(actionedBy.userID) {
return false
}
}
for mention in status.mentions {
if accountSettings.isMe(mention.userID) {
return true
}
}
if status.isActioned {
if accountSettings.isMe(status.user.userID) {
return true
}
}
}
return false
}
}
| 078a8255757625efdbbd562400794389 | 35.088889 | 171 | 0.54064 | false | false | false | false |
herveperoteau/TracktionProto2 | refs/heads/master | TracktionProto2 WatchKit Extension/DateCompare.swift | mit | 1 | //
// DateCompare.swift
// TracktionProto2
//
// Created by Hervé PEROTEAU on 31/01/2016.
// Copyright © 2016 Hervé PEROTEAU. All rights reserved.
//
import Foundation
func <=(lhs: NSDate, rhs: NSDate) -> Bool {
return lhs.timeIntervalSince1970 <= rhs.timeIntervalSince1970
}
func >=(lhs: NSDate, rhs: NSDate) -> Bool {
return lhs.timeIntervalSince1970 >= rhs.timeIntervalSince1970
}
func >(lhs: NSDate, rhs: NSDate) -> Bool {
return lhs.timeIntervalSince1970 > rhs.timeIntervalSince1970
}
func <(lhs: NSDate, rhs: NSDate) -> Bool {
return lhs.timeIntervalSince1970 < rhs.timeIntervalSince1970
}
func ==(lhs: NSDate, rhs: NSDate) -> Bool {
return lhs.timeIntervalSince1970 == rhs.timeIntervalSince1970
} | 394ffbecd447acbc80e70a63f2a0e364 | 27.8 | 63 | 0.726008 | false | false | false | false |
feistydog/FeistyDB | refs/heads/master | Sources/FeistyDB/Database+Collation.swift | mit | 1 | //
// Copyright (c) 2015 - 2020 Feisty Dog, LLC
//
// See https://github.com/feistydog/FeistyDB/blob/master/LICENSE.txt for license information
//
import Foundation
import CSQLite
extension Database {
/// A comparator for `String` objects.
///
/// - parameter lhs: The left-hand operand
/// - parameter rhs: The right-hand operand
///
/// - returns: The result of comparing `lhs` to `rhs`
public typealias StringComparator = (_ lhs: String, _ rhs: String) -> ComparisonResult
/// Adds a custom collation function.
///
/// ```swift
/// try db.addCollation("localizedCompare", { (lhs, rhs) -> ComparisonResult in
/// return lhs.localizedCompare(rhs)
/// })
/// ```
///
/// - parameter name: The name of the custom collation sequence
/// - parameter block: A string comparison function
///
/// - throws: An error if the collation function couldn't be added
public func addCollation(_ name: String, _ block: @escaping StringComparator) throws {
let function_ptr = UnsafeMutablePointer<StringComparator>.allocate(capacity: 1)
function_ptr.initialize(to: block)
guard sqlite3_create_collation_v2(db, name, SQLITE_UTF8, function_ptr, { (context, lhs_len, lhs_data, rhs_len, rhs_data) -> Int32 in
// Have total faith that SQLite will pass valid parameters and use unsafelyUnwrapped
let lhs = String(bytesNoCopy: UnsafeMutableRawPointer(mutating: lhs_data.unsafelyUnwrapped), length: Int(lhs_len), encoding: .utf8, freeWhenDone: false).unsafelyUnwrapped
let rhs = String(bytesNoCopy: UnsafeMutableRawPointer(mutating: rhs_data.unsafelyUnwrapped), length: Int(rhs_len), encoding: .utf8, freeWhenDone: false).unsafelyUnwrapped
// Cast context to the appropriate type and call the comparator
let function_ptr = context.unsafelyUnwrapped.assumingMemoryBound(to: StringComparator.self)
let result = function_ptr.pointee(lhs, rhs)
return Int32(result.rawValue)
}, { context in
let function_ptr = context.unsafelyUnwrapped.assumingMemoryBound(to: StringComparator.self)
function_ptr.deinitialize(count: 1)
function_ptr.deallocate()
}) == SQLITE_OK else {
throw SQLiteError("Error adding collation sequence \"\(name)\"", takingDescriptionFromDatabase: db)
}
}
/// Removes a custom collation function.
///
/// - parameter name: The name of the custom collation sequence
///
/// - throws: An error if the collation function couldn't be removed
public func removeCollation(_ name: String) throws {
guard sqlite3_create_collation_v2(db, name, SQLITE_UTF8, nil, nil, nil) == SQLITE_OK else {
throw SQLiteError("Error removing collation sequence \"\(name)\"", takingDescriptionFromDatabase: db)
}
}
}
| 0173704ae3f963938d533e9624ca99e7 | 42.016129 | 173 | 0.725159 | false | false | false | false |
CodaFi/swift | refs/heads/master | test/AutoDiff/validation-test/separate_tangent_type.swift | apache-2.0 | 5 | // RUN: %target-run-simple-swift
// REQUIRES: executable_test
import StdlibUnittest
#if canImport(Darwin)
import Darwin.C
#elseif canImport(Glibc)
import Glibc
#elseif os(Windows)
import ucrt
#else
#error("Unsupported platform")
#endif
import DifferentiationUnittest
var SeparateTangentTypeTests = TestSuite("SeparateTangentType")
struct DifferentiableSubset : Differentiable {
@differentiable(wrt: self)
var w: Tracked<Float>
@differentiable(wrt: self)
var b: Tracked<Float>
@noDerivative var flag: Bool
struct TangentVector : Differentiable, AdditiveArithmetic {
typealias TangentVector = DifferentiableSubset.TangentVector
var w: Tracked<Float>
var b: Tracked<Float>
}
mutating func move(along v: TangentVector) {
w.move(along: v.w)
b.move(along: v.b)
}
}
SeparateTangentTypeTests.testWithLeakChecking("Trivial") {
let x = DifferentiableSubset(w: 0, b: 1, flag: false)
let pb = pullback(at: x) { x in x }
expectEqual(pb(DifferentiableSubset.TangentVector.zero), DifferentiableSubset.TangentVector.zero)
}
SeparateTangentTypeTests.testWithLeakChecking("Initialization") {
let x = DifferentiableSubset(w: 0, b: 1, flag: false)
let pb = pullback(at: x) { x in DifferentiableSubset(w: 1, b: 2, flag: true) }
expectEqual(pb(DifferentiableSubset.TangentVector.zero), DifferentiableSubset.TangentVector.zero)
}
SeparateTangentTypeTests.testWithLeakChecking("SomeArithmetics") {
let x = DifferentiableSubset(w: 0, b: 1, flag: false)
let pb = pullback(at: x) { x in DifferentiableSubset(w: x.w * x.w, b: x.b * x.b, flag: true) }
expectEqual(pb(DifferentiableSubset.TangentVector.zero), DifferentiableSubset.TangentVector.zero)
}
runAllTests()
| 27227ec00c86f6ea4bfeed17ef2fd9db | 30.054545 | 99 | 0.75 | false | true | false | false |
NoahPeeters/TCPTester | refs/heads/master | TCPTester/TCPTestData.swift | gpl-3.0 | 1 | //
// TCPTestData.swift
// TCPTester
//
// Created by Noah Peeters on 5/5/17.
// Copyright © 2017 Noah Peeters. All rights reserved.
//
import Foundation
class TCPTestData {
var host: String = "127.0.0.1";
var port: String = "22";
var messages: [TCPMessage] = [];
init(host: String = "127.0.0.1", port: String = "22") {
self.host = host
self.port = port
}
init(fromJsonData data: Data) throws {
guard let json = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions()) as? [String: Any],
let host = json["host"] as? String,
let port = json["port"] as? String,
let messages = json["messages"] as? [[String: Any]]
else {
throw NSError(domain: "Cannot open file.", code: errAECorruptData, userInfo: nil)
}
self.host = host
self.port = port
self.messages = []
for rawMessage in messages {
if let message = TCPMessage.init(json: rawMessage) {
self.messages.append(message)
}
}
}
func getJsonObject() -> [String: Any] {
var jsonMessages: [[String: Any]] = []
for message in messages {
jsonMessages.append(message.getJsonObject())
}
return [
"version": "1.0",
"host": host,
"port": port,
"messages": jsonMessages
]
}
func getJsonData() throws -> Data {
return try JSONSerialization.data(withJSONObject: getJsonObject(), options: JSONSerialization.WritingOptions())
}
}
class TCPMessage {
var time: Double;
var fromServer: Bool;
var encoding: OutputEncoding;
var message: Data;
init(time: Double, fromServer: Bool, encoding: OutputEncoding, message: Data) {
self.time = time;
self.fromServer = fromServer
self.encoding = encoding
self.message = message
}
init?(json: [String: Any]) {
guard let time = json["time"] as? Double,
let fromServer = json["fromServer"] as? Bool,
let encodingRawValue = json["encoding"] as? String,
let encoding = OutputEncoding(rawValue: encodingRawValue),
let base64message = json["message"] as? String,
let message = Data(base64Encoded: base64message, options: .ignoreUnknownCharacters)
else {
return nil
}
self.message = message
self.time = time
self.fromServer = fromServer
self.encoding = encoding
}
func getJsonObject() -> [String: Any] {
return [
"time": time,
"fromServer": fromServer,
"encoding": encoding.rawValue,
"message": message.base64EncodedString()
]
}
func getEncodedMessage() -> String {
return encoding.encode(data: message)
}
}
| 85d323cac4c922409698ebf4a06114c9 | 27.299065 | 133 | 0.550198 | false | false | false | false |
michaelsabo/hammer | refs/heads/master | Hammer/Classes/Service/GifService.swift | mit | 1 | //
// GifCollectionService.swift
// Hammer
//
// Created by Mike Sabo on 10/13/15.
// Copyright © 2015 FlyingDinosaurs. All rights reserved.
//
import Alamofire
import SwiftyJSON
import Regift
class GifService {
func getGifsResponse(completion: @escaping (_ success: Bool, _ gifs:Gifs?) -> Void) {
Alamofire.request(Router.gifs)
.responseJSON { response in
if let json = response.result.value {
let gifs = Gifs(gifsJSON: JSON(json))
if (response.result.isSuccess) {
completion(true, gifs)
}
}
completion(false, nil)
}
}
func getGifsForTagSearchResponse(_ query: String, completion: @escaping (_ success: Bool, _ gifs:Gifs?) -> Void) {
Alamofire.request(Router.gifsForTag(query))
.responseJSON { response in
if let json = response.result.value {
let gifs = Gifs(gifsJSON: JSON(json))
if (response.result.isSuccess) {
completion(true, gifs)
}
}
completion(false, nil)
}
}
func retrieveThumbnailImageFor(_ gif: Gif, completion: @escaping (_ success: Bool, _ gif:Gif?) -> Void) {
Alamofire.request(gif.thumbnailUrl, method: .get)
.responseData { response in
if (response.result.isSuccess) {
if let data = response.result.value {
gif.thumbnailData = data
completion(true, gif)
}
}
completion(false, nil)
}
}
func retrieveImageDataFor(_ gif: Gif, completion: @escaping (_ success: Bool, _ data:Data?) -> Void) {
Alamofire.request(gif.url, method: .get)
.responseData { response in
if (response.result.isSuccess) {
if let data = response.result.value {
completion(true, data)
}
}
completion(false, nil)
}
}
func retrieveGifForVideo(_ gif: Gif, completion: @escaping (_ success: Bool, _ data:Data?, _ byteSize:Int) -> Void) {
DispatchQueue.global().async {
Regift.createGIFFromSource(URL(safeString: gif.videoUrl)) { result,size in
if let filePath = result {
if let data = try? Data(contentsOf: filePath) {
completion(true, data, size)
}
}
completion(false, nil, 0)
}
}
}
func addGif(_ id : String, completion: @escaping (_ success: Bool) -> Void) {
Alamofire.request(Router.addGif(id))
.responseJSON { response in
if (response.result.isSuccess) {
// let json = JSON(response.result.value!)
// let gif = Gif(json: json["gif"], index: 0)
completion(true)
}
completion(false)
}
}
}
extension URL {
public init(safeString string: String) {
guard let instance = URL(string: string) else {
fatalError("Unconstructable URL: \(string)")
}
self = instance
}
}
extension String {
mutating func replaceSpaces() -> String {
return self.replacingOccurrences(of: " ", with: "-")
}
}
| 0f9350f2ac7808883f3cdd5b472337ec | 25.464912 | 119 | 0.589327 | false | false | false | false |
Shimmen/CoreDataTests | refs/heads/master | CoreDataTest-1/CoreDataTest-1/ViewController.swift | mit | 1 | //
// ViewController.swift
// CoreDataTest-1
//
// Created by Simon Moos on 06/11/14.
//
import UIKit
import CoreData
class ViewController: UITableViewController
{
var people: [Person] = [Person]()
// Returns the managed object context from the AppDelegate
var managedObjectContext: NSManagedObjectContext {
let appDelegate = UIApplication.sharedApplication().delegate as AppDelegate
return appDelegate.managedObjectContext!
}
// MARK: - View Controller lifecycle
override func viewDidLoad()
{
super.viewDidLoad()
}
override func didReceiveMemoryWarning()
{
super.didReceiveMemoryWarning()
}
// MARK: - Building table view
override func numberOfSectionsInTableView(tableView: UITableView) -> Int
{
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return people.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
let cell = tableView.dequeueReusableCellWithIdentifier("Cell") as UITableViewCell
let person = people[indexPath.row]
cell.textLabel.text = person.identification
return cell
}
// MARK: - Editing table view
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool
{
return true
}
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath)
{
if editingStyle == .Delete {
removePersonAtIndexPath(indexPath)
}
}
// MARK: - Adding and removing cells
@IBAction func addNewPerson()
{
// Create Person (with default values for all attributes) in database
let personEntity = NSEntityDescription.entityForName("Person", inManagedObjectContext: managedObjectContext)
// Create a Person from the entity so custom properites/attributes can be set
var person = Person(entity: personEntity!, insertIntoManagedObjectContext: managedObjectContext)
// Set properties/attributes
person.firstName = "Firsname"
person.lastName = "Lastname"
person.age = NSDate().timeIntervalSince1970 // Just to get some unique number
// Add to data source list and tell table view to update those rows
let indexPath = NSIndexPath(forRow: 0, inSection: 0)
people.insert(person, atIndex: indexPath.row)
tableView.insertRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
}
func removePersonAtIndexPath(indexPath: NSIndexPath)
{
// Remove from database
managedObjectContext.deleteObject(people[indexPath.row])
// Remove from table view and people array
people.removeAtIndex(indexPath.row)
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
}
}
| 89734264c8bc36febf22db25560dfe35 | 30.21 | 155 | 0.67158 | false | false | false | false |
johnno1962/GitDiff | refs/heads/master | SharedXPC/LineGenerators.swift | mit | 2 | //
// LineGenerators.swift
// refactord
//
// Created by John Holdsworth on 19/12/2015.
// Copyright © 2015 John Holdsworth. All rights reserved.
//
// $Id: //depot/Refactorator/refactord/LineGenerators.swift#7 $
//
// Repo: https://github.com/johnno1962/Refactorator
//
import Foundation
open class TaskGenerator: FileGenerator {
let task: Process
convenience init(command: String, directory: String? = nil, lineSeparator: String? = nil) {
self.init(launchPath: "/bin/bash", arguments: ["-c", "exec \(command)"],
directory: directory, lineSeparator: lineSeparator)
}
convenience init(launchPath: String, arguments: [String] = [], directory: String? = nil, lineSeparator: String? = nil) {
let task = Process()
task.launchPath = launchPath
task.arguments = arguments
task.currentDirectoryPath = directory ?? "."
self.init(task: task, lineSeparator: lineSeparator)
}
init(task: Process, lineSeparator: String? = nil) {
self.task = task
let pipe = Pipe()
task.standardOutput = pipe.fileHandleForWriting
task.launch()
pipe.fileHandleForWriting.closeFile()
super.init(handle: pipe.fileHandleForReading, lineSeparator: lineSeparator)
}
deinit {
task.terminate()
}
}
open class FileGenerator: IteratorProtocol {
let eol: Int32
let handle: FileHandle
let readBuffer = NSMutableData()
convenience init?(path: String, lineSeparator: String? = nil) {
guard let handle = FileHandle(forReadingAtPath: path) else { return nil }
self.init(handle: handle, lineSeparator: lineSeparator)
}
init(handle: FileHandle, lineSeparator: String? = nil) {
eol = Int32((lineSeparator ?? "\n").utf16.first!)
self.handle = handle
}
open func next() -> String? {
while true {
if let endOfLine = memchr(readBuffer.bytes, eol, readBuffer.length) {
let endOfLine = endOfLine.assumingMemoryBound(to: Int8.self)
endOfLine[0] = 0
let start = readBuffer.bytes.assumingMemoryBound(to: Int8.self)
let line = String(cString: start)
let consumed = NSMakeRange(0, UnsafePointer<Int8>(endOfLine) + 1 - start)
readBuffer.replaceBytes(in: consumed, withBytes: nil, length: 0)
return line
}
let bytesRead = handle.availableData
if bytesRead.count <= 0 {
if readBuffer.length != 0 {
let last = String.fromData(data: readBuffer)
readBuffer.length = 0
return last
} else {
break
}
}
readBuffer.append(bytesRead)
}
return nil
}
open var lineSequence: AnySequence<String> {
return AnySequence({ self })
}
deinit {
handle.closeFile()
}
}
extension String {
static func fromData(data: NSData, encoding: String.Encoding = .utf8) -> String? {
return String(data: data as Data, encoding: encoding)
}
}
| 1db5aef462f9fe39937deca48e296a11 | 26.973684 | 124 | 0.596425 | false | false | false | false |
mansoor92/MaksabComponents | refs/heads/master | MaksabComponents/Classes/Navigation Controller/MaksabNavigationController.swift | mit | 1 | //
// MaksabNavigationController.swift
// Pods
//
// Created by Incubasys on 20/07/2017.
//
//
import UIKit
import StylingBoilerPlate
open class MaksabNavigationController: UINavigationController {
@IBInspectable public var isTransparent: Bool = true {
didSet{
setBarStyle(_isTransparent: isTransparent)
}
}
override open func viewDidLoad() {
super.viewDidLoad()
setBarStyle(_isTransparent: isTransparent)
self.navigationBar.topItem?.title = ""
}
func setBarStyle(_isTransparent: Bool) {
if _isTransparent{
let img = UIImage.getImageFromColor(color: UIColor.clear, size: CGSize(width: self.view.frame.size.width, height: 64))
self.navigationBar.setBackgroundImage(img, for: .default)
let shadowImg = UIImage.getImageFromColor(color: UIColor.clear, size: CGSize(width: self.view.frame.size.width, height: 1))
self.navigationBar.shadowImage = shadowImg
UIApplication.shared.statusBarStyle = .default
}else{
let img = UIImage.getImageFromColor(color: UIColor.appColor(color: .Primary), size: CGSize(width: self.view.frame.size.width, height: 64))
self.navigationBar.setBackgroundImage(img, for: .default)
let shadowImg = UIImage.getImageFromColor(color: UIColor.appColor(color: .PrimaryDark), size: CGSize(width: self.view.frame.size.width, height: 1))
self.navigationBar.shadowImage = shadowImg
UIApplication.shared.statusBarStyle = .lightContent
}
}
open override var preferredStatusBarStyle: UIStatusBarStyle{
if isTransparent{
return .default
}else{
return .lightContent
}
}
}
| 7196d5518d83d98792d8a4a39dae62ee | 35.22449 | 159 | 0.660282 | false | false | false | false |
DragonCherry/CameraPreviewController | refs/heads/master | CameraPreviewController/Classes/CameraPreviewController+Filter.swift | mit | 1 | //
// CameraPreviewController+Filter.swift
// Pods
//
// Created by DragonCherry on 6/7/17.
//
//
import UIKit
import GPUImage
// MARK: - Filter APIs
extension CameraPreviewController {
open func contains(targetFilter: GPUImageFilter?) -> Bool {
guard let targetFilter = targetFilter else { return false }
for filter in filters {
if filter == targetFilter {
return true
}
}
return false
}
open func add(filter: GPUImageFilter?) {
guard let filter = filter, !contains(targetFilter: filter) else { return }
lastFilter.removeAllTargets()
lastFilter.addTarget(filter)
filter.addTarget(preview)
if let videoWriter = self.videoWriter {
filter.addTarget(videoWriter)
}
filters.append(filter)
}
open func add(newFilters: [GPUImageFilter]?) {
guard let newFilters = newFilters, let firstNewFilter = newFilters.first, newFilters.count > 0 else { return }
lastFilter.removeAllTargets()
lastFilter.addTarget(firstNewFilter)
filters.append(contentsOf: filters)
if let videoWriter = self.videoWriter {
filters.last?.addTarget(videoWriter)
}
filters.last?.addTarget(preview)
}
open func removeFilters() {
defaultFilter.removeAllTargets()
for filter in filters {
filter.removeAllTargets()
filter.removeFramebuffer()
}
filters.removeAll()
if let videoWriter = self.videoWriter {
defaultFilter.addTarget(videoWriter)
}
defaultFilter.addTarget(preview)
}
}
| 809342c540e4145b997ebf7a5b46cf18 | 27.728814 | 118 | 0.616519 | false | false | false | false |
ncvitak/TrumpBot | refs/heads/master | TrumpBotIntent/IntentHandler.swift | mit | 1 | //
// IntentHandler.swift
// TrumpBotIntent
//
// Created by Nico Cvitak on 2016-07-23.
// Copyright © 2016 Nicholas Cvitak. All rights reserved.
//
import Intents
import AVFoundation
class IntentHandler: INExtension, INSendMessageIntentHandling, AVSpeechSynthesizerDelegate {
let speechSynthesizer = AVSpeechSynthesizer()
var contentResolveCompletion: ((INStringResolutionResult) -> Void)?
override init() {
try! AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
try! AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback, with: [AVAudioSessionCategoryOptions.mixWithOthers])
try! AVAudioSession.sharedInstance().setActive(true)
super.init()
speechSynthesizer.delegate = self
}
override func handler(for intent: INIntent) -> AnyObject {
// This is the default implementation. If you want different objects to handle different intents,
// you can override this and return the handler you want for that particular intent.
return self
}
func handle(sendMessage intent: INSendMessageIntent, completion: (INSendMessageIntentResponse) -> Swift.Void) {
print("Message intent is being handled.")
let userActivity = NSUserActivity(activityType: NSStringFromClass(INSendMessageIntent.self))
let response = INSendMessageIntentResponse(code: .success, userActivity: userActivity)
completion(response)
}
func resolveRecipients(forSendMessage intent: INSendMessageIntent, with completion: ([INPersonResolutionResult]) -> Void) {
if let recipients = intent.recipients where recipients.count == 1 && recipients[0].displayName == "Donald" {
completion([INPersonResolutionResult.success(with: recipients[0])])
} else {
completion([INPersonResolutionResult.needsValue()])
}
}
func resolveContent(forSendMessage intent: INSendMessageIntent, with completion: (INStringResolutionResult) -> Void) {
let content = intent.content != nil ? intent.content! : ""
let response = botResponse(content: content.lowercased())
contentResolveCompletion = completion
speechSynthesizer.speak(AVSpeechUtterance(string: response))
}
func speechSynthesizer(_ synthesizer: AVSpeechSynthesizer, didFinish utterance: AVSpeechUtterance) {
contentResolveCompletion?(INStringResolutionResult.needsValue())
contentResolveCompletion = nil
}
}
| 734ef73761f85c1eeb858c9638a8802d | 40.387097 | 141 | 0.710055 | false | false | false | false |
neekon/ios | refs/heads/master | Neekon/Neekon/MainNavigationController.swift | mit | 1 | //
// MainNavigationController.swift
// Neekon
//
// Created by Eiman Zolfaghari on 2/9/15.
// Copyright (c) 2015 Iranican Inc. All rights reserved.
//
import UIKit
class MainNavigationController: UINavigationController {
override func viewDidLoad() {
super.viewDidLoad()
let bgImage = UIImage(named:"home-BG.jpg")
let bgImageView = UIImageView(image: bgImage)
bgImageView.frame = self.view.frame
self.view.addSubview(bgImageView)
self.view.sendSubviewToBack(bgImageView)
self.view.backgroundColor = UIColor.clearColor()
self.navigationBar.translucent = true
self.navigationBar.barTintColor = UIColor.purpleColor()
UITabBar.appearance().barTintColor = UIColor.purpleColor()
UITabBar.appearance().tintColor = UIColor.whiteColor()
}
override func preferredStatusBarStyle() -> UIStatusBarStyle {
return UIStatusBarStyle.LightContent
}
}
| fb30954939d6c83b1fd78e9161393910 | 28.352941 | 66 | 0.667335 | false | false | false | false |
mlgoogle/wp | refs/heads/master | wp/Model/DealParam.swift | apache-2.0 | 1 | //
// DealParam.swift
// wp
//
// Created by 木柳 on 2017/1/12.
// Copyright © 2017年 com.yundian. All rights reserved.
//
import UIKit
class KChartParam: DealParam {
var symbol: String = "" //商品类型
var exchangeName: String = "" //交易所
var platformName: String = "" //平台名称
var aType: Int = 0 //1.股票 2现货 3期货 4.外汇
var chartType: Int = 0 // int32 K线类型 60-1分钟K线,300-5分K线,900-15分K线,1800-30分K线,3600-60分K线,5-日K线
var startTime: Int64 = 0
var endTime: Int64 = 0
var count: Int = Int(AppConst.klineCount)
}
class DealPriceParam: DealModel {
var goodsinfos: [KChartParam] = []
class func goodsinfosModelClass() -> AnyClass {
return KChartParam.classForCoder()
}
}
class DealParam: BaseParam {
}
class BuildDealParam: DealParam {
var codeId: Int = 0
var buySell: Int = 0
var amount: Int = 0
var prince: Double = 0
var limit: Int = 0
var stop: Int = 0
var isDeferred: Int = 0
}
class PositionParam: DealParam{
var gid = 0
}
class ProductParam: DealParam{
var pid = AppConst.pid
}
class BenifityParam: DealParam{
var tid = 0
var handle = 0
}
class UndealParam: DealParam {
var htype = 1
var start = 0
var count = 10
}
class HistoryDealParam: BaseParam{
var start = 0
var count = 0
}
class DealHistoryDetailParam: DealParam {
var symbol:String = ""
var start = 0
var count = 10
}
| 37399fcf7824a67c337eaf985f3eccb2 | 18.569444 | 96 | 0.637331 | false | false | false | false |
GrandCentralBoard/GrandCentralBoard | refs/heads/develop | GrandCentralBoard/Widgets/GitHub/GitHubSource.swift | gpl-3.0 | 2 | //
// GitHubSource.swift
// GrandCentralBoard
//
// Created by Michał Laskowski on 22/05/16.
//
import RxSwift
import GCBCore
struct GitHubSourceNoDataError: ErrorType, HavingMessage {
let message = "GitHub returned no repositories".localized
}
private extension CollectionType where Generator.Element == Repository {
func filterAndSortByPRCountAndName() -> [Repository] {
return filter { $0.pullRequestsCount > 0 }.sort({ (left, right) -> Bool in
if left.pullRequestsCount == right.pullRequestsCount {
return left.name < right.name
}
return left.pullRequestsCount > right.pullRequestsCount
})
}
}
final class GitHubSource: Asynchronous {
typealias ResultType = Result<[Repository]>
let sourceType: SourceType = .Momentary
private let disposeBag = DisposeBag()
private let dataProvider: GitHubDataProviding
let interval: NSTimeInterval
init(dataProvider: GitHubDataProviding, refreshInterval: NSTimeInterval) {
self.dataProvider = dataProvider
interval = refreshInterval
}
func read(closure: (ResultType) -> Void) {
dataProvider.repositoriesWithPRsCount().single().map { (repositories) -> [Repository] in
guard repositories.count > 0 else { throw GitHubSourceNoDataError() }
return repositories.filterAndSortByPRCountAndName()
}.observeOn(MainScheduler.instance).subscribe { (event) in
switch event {
case .Error(let error): closure(.Failure(error))
case .Next(let repositories): closure(.Success(repositories.filterAndSortByPRCountAndName()))
case .Completed: break
}
}.addDisposableTo(disposeBag)
}
}
| f88eabddf0e9b72d518aa099185c57d6 | 32.113208 | 105 | 0.676353 | false | false | false | false |
itouch2/LeetCode | refs/heads/master | LeetCode/SearchinRotatedSortedArray.swift | mit | 1 | //
// SearchinRotatedSortedArray.swift
// LeetCode
//
// Created by You Tu on 2017/9/11.
// Copyright © 2017年 You Tu. All rights reserved.
//
import Cocoa
/*
Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.
(i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2).
You are given a target value to search. If found in the array return its index, otherwise return -1.
You may assume no duplicate exists in the array.
*/
class SearchinRotatedSortedArray: NSObject {
func search(_ nums: [Int], _ target: Int) -> Int {
return searchFromRange(nums, target, 0, nums.count - 1)
}
func searchFromRange(_ nums: [Int], _ target: Int, _ left: Int, _ right: Int) -> Int {
if left > right {
return -1
}
let mid = left + (right - left) / 2
if nums[mid] == target {
return mid
}
if nums[left] < nums[right] {
if target < nums[left] {
return -1
}
if target > nums[right] {
return -1
}
return binarySearchFromRange(nums, target, left: left, right: right)
}
let leftIndex = searchFromRange(nums, target, mid + 1, right)
if leftIndex != -1 {
return leftIndex
}
return searchFromRange(nums, target, left, mid - 1)
}
func binarySearchFromRange(_ nums: [Int], _ target: Int, left: Int, right: Int) -> Int {
if target < nums[left] || target > nums[right] {
return -1
}
if left > right {
return -1
}
let mid = left + (right - left) / 2
if nums[mid] == target {
return mid
} else if nums[mid] < target {
return binarySearchFromRange(nums, target, left: mid + 1, right: right)
} else {
return binarySearchFromRange(nums, target, left: left, right: mid - 1)
}
}
}
| 1349dabf9e282640b20ff33e50ad6d13 | 26.328947 | 101 | 0.519981 | false | false | false | false |
Jnosh/swift | refs/heads/master | test/decl/ext/generic.swift | apache-2.0 | 5 | // RUN: %target-typecheck-verify-swift
protocol P1 { associatedtype AssocType }
protocol P2 : P1 { }
protocol P3 { }
struct X<T : P1, U : P2, V> {
struct Inner<A, B : P3> { }
struct NonGenericInner { }
}
extension Int : P1 {
typealias AssocType = Int
}
extension Double : P2 {
typealias AssocType = Double
}
extension X<Int, Double, String> { } // expected-error{{constrained extension must be declared on the unspecialized generic type 'X' with constraints specified by a 'where' clause}}
// Lvalue check when the archetypes are not the same.
struct LValueCheck<T> {
let x = 0
}
extension LValueCheck {
init(newY: Int) {
x = 42
}
}
// Member type references into another extension.
struct MemberTypeCheckA<T> { }
protocol MemberTypeProto {
associatedtype AssocType
func foo(_ a: AssocType)
init(_ assoc: MemberTypeCheckA<AssocType>)
}
struct MemberTypeCheckB<T> : MemberTypeProto {
func foo(_ a: T) {}
typealias Element = T
var t1: T
}
extension MemberTypeCheckB {
typealias Underlying = MemberTypeCheckA<T>
}
extension MemberTypeCheckB {
init(_ x: Underlying) { }
}
extension MemberTypeCheckB {
var t2: Element { return t1 }
}
// rdar://problem/19795284
extension Array {
var pairs: [(Element, Element)] {
get {
return []
}
}
}
// rdar://problem/21001937
struct GenericOverloads<T, U> {
var t: T
var u: U
init(t: T, u: U) { self.t = t; self.u = u }
func foo() { }
var prop: Int { return 0 }
subscript (i: Int) -> Int { return i }
}
extension GenericOverloads where T : P1, U : P2 {
init(t: T, u: U) { self.t = t; self.u = u }
func foo() { }
var prop: Int { return 1 }
subscript (i: Int) -> Int { return i }
}
extension Array where Element : Hashable {
var worseHashEver: Int {
var result = 0
for elt in self {
result = (result << 1) ^ elt.hashValue
}
return result
}
}
func notHashableArray<T>(_ x: [T]) {
x.worseHashEver // expected-error{{type 'T' does not conform to protocol 'Hashable'}}
}
func hashableArray<T : Hashable>(_ x: [T]) {
// expected-warning @+1 {{unused}}
x.worseHashEver // okay
}
func intArray(_ x: [Int]) {
// expected-warning @+1 {{unused}}
x.worseHashEver
}
class GenericClass<T> { }
extension GenericClass where T : Equatable {
func foo(_ x: T, y: T) -> Bool { return x == y }
}
func genericClassEquatable<T : Equatable>(_ gc: GenericClass<T>, x: T, y: T) {
_ = gc.foo(x, y: y)
}
func genericClassNotEquatable<T>(_ gc: GenericClass<T>, x: T, y: T) {
gc.foo(x, y: y) // expected-error{{type 'T' does not conform to protocol 'Equatable'}}
}
extension Array where Element == String { }
extension GenericClass : P3 where T : P3 { } // expected-error{{extension of type 'GenericClass' with constraints cannot have an inheritance clause}}
extension GenericClass where Self : P3 { }
// expected-error@-1{{'Self' is only available in a protocol or as the result of a method in a class; did you mean 'GenericClass'?}} {{30-34=GenericClass}}
// expected-error@-2{{type 'GenericClass<T>' in conformance requirement does not refer to a generic parameter or associated type}}
protocol P4 {
associatedtype T
init(_: T)
}
protocol P5 { }
struct S4<Q>: P4 {
init(_: Q) { }
}
extension S4 where T : P5 {}
struct S5<Q> {
init(_: Q) { }
}
extension S5 : P4 {}
| 259146b2f93c2a021cddfcc62234c8c0 | 19.86875 | 181 | 0.650195 | false | false | false | false |
AlexIzh/Griddle | refs/heads/master | CollectionPresenter/3rd/DraggableCollectionViewFlowLayout.swift | mit | 1 | //
// KDRearrangeableCollectionViewFlowLayout.swift
// KDRearrangeableCollectionViewFlowLayout
//
// Created by Michael Michailidis on 16/03/2015.
// Copyright (c) 2015 Karmadust. All rights reserved.
//
import UIKit
@objc protocol DraggableCollectionViewFlowLayoutDelegate: UICollectionViewDelegate {
func moveDataItem(_ fromIndexPath: IndexPath, toIndexPath: IndexPath) -> Void
func didFinishMoving(_ fromIndexPath: IndexPath, toIndexPath: IndexPath) -> Void
}
class DraggableCollectionViewFlowLayout: UICollectionViewFlowLayout, UIGestureRecognizerDelegate {
var animating: Bool = false
var collectionViewFrameInCanvas: CGRect = CGRect.zero
var hitTestRectagles = [String: CGRect]()
var startIndexPath: IndexPath?
var canvas: UIView? {
didSet {
if canvas != nil {
calculateBorders()
}
}
}
struct Bundle {
var offset: CGPoint = CGPoint.zero
var sourceCell: UICollectionViewCell
var representationImageView: UIView
var currentIndexPath: IndexPath
}
var bundle: Bundle?
override init() {
super.init()
setup()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func awakeFromNib() {
super.awakeFromNib()
setup()
}
func setup() {
if let _ = self.collectionView {
// let longPressGestureRecogniser = UILongPressGestureRecognizer(target: self, action: "handleGesture:")
//
// longPressGestureRecogniser.minimumPressDuration = 0.2
// longPressGestureRecogniser.delegate = self
//
// collectionView.addGestureRecognizer(longPressGestureRecogniser)
if canvas == nil {
canvas = collectionView!.superview
}
}
}
override func prepare() {
super.prepare()
calculateBorders()
}
fileprivate func calculateBorders() {
if let collectionView = self.collectionView {
collectionViewFrameInCanvas = collectionView.frame
if canvas != collectionView.superview {
collectionViewFrameInCanvas = canvas!.convert(collectionViewFrameInCanvas, from: collectionView)
}
var leftRect: CGRect = collectionViewFrameInCanvas
leftRect.size.width = 20.0
hitTestRectagles["left"] = leftRect
var topRect: CGRect = collectionViewFrameInCanvas
topRect.size.height = 20.0
hitTestRectagles["top"] = topRect
var rightRect: CGRect = collectionViewFrameInCanvas
rightRect.origin.x = rightRect.size.width - 20.0
rightRect.size.width = 20.0
hitTestRectagles["right"] = rightRect
var bottomRect: CGRect = collectionViewFrameInCanvas
bottomRect.origin.y = bottomRect.origin.y + rightRect.size.height - 20.0
bottomRect.size.height = 20.0
hitTestRectagles["bottom"] = bottomRect
}
}
// MARK: - UIGestureRecognizerDelegate
func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
if let ca = self.canvas {
if let cv = self.collectionView {
let pointPressedInCanvas = gestureRecognizer.location(in: ca)
for cell in cv.visibleCells {
let cellInCanvasFrame = ca.convert(cell.frame, from: cv)
if cellInCanvasFrame.contains(pointPressedInCanvas) {
let representationImage = cell.snapshotView(afterScreenUpdates: true)
representationImage!.frame = cellInCanvasFrame
let offset = CGPoint(x: pointPressedInCanvas.x - cellInCanvasFrame.origin.x, y: pointPressedInCanvas.y - cellInCanvasFrame.origin.y)
let indexPath: IndexPath = cv.indexPath(for: cell as UICollectionViewCell)!
bundle = Bundle(offset: offset, sourceCell: cell, representationImageView: representationImage!, currentIndexPath: indexPath)
break
}
}
}
}
return (bundle != nil)
}
func checkForDraggingAtTheEdgeAndAnimatePaging(_ gestureRecognizer: UILongPressGestureRecognizer) {
if animating == true {
return
}
if let bundle = self.bundle {
_ = gestureRecognizer.location(in: canvas)
var nextPageRect: CGRect = collectionView!.bounds
if scrollDirection == UICollectionViewScrollDirection.horizontal {
if bundle.representationImageView.frame.intersects(hitTestRectagles["left"]!) {
nextPageRect.origin.x -= nextPageRect.size.width
if nextPageRect.origin.x < 0.0 {
nextPageRect.origin.x = 0.0
}
} else if bundle.representationImageView.frame.intersects(hitTestRectagles["right"]!) {
nextPageRect.origin.x += nextPageRect.size.width
if nextPageRect.origin.x + nextPageRect.size.width > collectionView!.contentSize.width {
nextPageRect.origin.x = collectionView!.contentSize.width - nextPageRect.size.width
}
}
} else if scrollDirection == UICollectionViewScrollDirection.vertical {
_ = hitTestRectagles["top"]
if bundle.representationImageView.frame.intersects(hitTestRectagles["top"]!) {
nextPageRect.origin.y -= nextPageRect.size.height
if nextPageRect.origin.y < 0.0 {
nextPageRect.origin.y = 0.0
}
} else if bundle.representationImageView.frame.intersects(hitTestRectagles["bottom"]!) {
nextPageRect.origin.y += nextPageRect.size.height
if nextPageRect.origin.y + nextPageRect.size.height > collectionView!.contentSize.height {
nextPageRect.origin.y = collectionView!.contentSize.height - nextPageRect.size.height
}
}
}
if !nextPageRect.equalTo(collectionView!.bounds) {
let delayTime = DispatchTime.now() + Double(Int64(0.8 * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC)
DispatchQueue.main.asyncAfter(deadline: delayTime, execute: {
self.animating = false
self.handleGesture(gestureRecognizer)
})
animating = true
collectionView!.scrollRectToVisible(nextPageRect, animated: true)
}
}
}
func handleGesture(_ gesture: UILongPressGestureRecognizer) {
if let bundle = self.bundle {
let dragPointOnCanvas = gesture.location(in: canvas)
if gesture.state == UIGestureRecognizerState.began {
bundle.sourceCell.isHidden = true
canvas?.addSubview(bundle.representationImageView)
// UIView.animateWithDuration(0.5, animations: { () -> Void in
// bundle.representationImageView.alpha = 0.8
// });
let dragPointOnCollectionView = gesture.location(in: collectionView)
startIndexPath = collectionView?.indexPathForItem(at: dragPointOnCollectionView)
}
if gesture.state == UIGestureRecognizerState.changed {
// Update the representation image
var imageViewFrame = bundle.representationImageView.frame
var point = CGPoint.zero
point.x = dragPointOnCanvas.x - bundle.offset.x
point.y = dragPointOnCanvas.y - bundle.offset.y
imageViewFrame.origin = point
bundle.representationImageView.frame = imageViewFrame
let dragPointOnCollectionView = gesture.location(in: collectionView)
if let indexPath: IndexPath = self.collectionView?.indexPathForItem(at: dragPointOnCollectionView) {
checkForDraggingAtTheEdgeAndAnimatePaging(gesture)
if (indexPath == bundle.currentIndexPath) == false {
// If we have a collection view controller that implements the delegate we call the method first
if let delegate = self.collectionView!.delegate as? DraggableCollectionViewFlowLayoutDelegate {
delegate.moveDataItem(bundle.currentIndexPath, toIndexPath: indexPath)
}
collectionView!.moveItem(at: bundle.currentIndexPath, to: indexPath)
self.bundle!.currentIndexPath = indexPath
}
}
}
if gesture.state == UIGestureRecognizerState.ended {
bundle.sourceCell.isHidden = false
bundle.representationImageView.removeFromSuperview()
if let _ = self.collectionView?.delegate as? DraggableCollectionViewFlowLayoutDelegate { // if we have a proper data source then we can reload and have the data displayed correctly
collectionView!.reloadData()
}
if let delegate = self.collectionView!.delegate as? DraggableCollectionViewFlowLayoutDelegate {
if let start = self.startIndexPath {
delegate.didFinishMoving(start, toIndexPath: self.bundle!.currentIndexPath)
}
}
self.bundle = nil
}
}
}
}
| 73dd684bae235c6d1c1d6ca7133530aa | 31.71831 | 192 | 0.630865 | false | false | false | false |
STShenZhaoliang/STKitSwift | refs/heads/master | STKitSwift/Date+STKit.swift | mit | 1 | //
// Date+STKit.swift
// STKitSwift
//
// The MIT License (MIT)
//
// Copyright (c) 2019 沈天
//
// 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
/// This extension add some useful functions to Date.
public extension Date {
// MARK: - Variables
/// Set and get current year.
var year: Int {
get {
let calendar = Calendar.autoupdatingCurrent
let components = calendar.dateComponents([.year], from: self)
guard let year = components.year else {
return 0
}
return year
}
set {
update(components: [.year: newValue])
}
}
/// Set and get current month.
var month: Int {
get {
let calendar = Calendar.autoupdatingCurrent
let components = calendar.dateComponents([.month], from: self)
guard let month = components.month else {
return 0
}
return month
}
set {
update(components: [.month: newValue])
}
}
/// Set and get current day.
var day: Int {
get {
let calendar = Calendar.autoupdatingCurrent
let components = calendar.dateComponents([.day], from: self)
guard let day = components.day else {
return 0
}
return day
}
set {
update(components: [.day: newValue])
}
}
/// Set and get current hour.
var hour: Int {
get {
let calendar = Calendar.autoupdatingCurrent
let components = calendar.dateComponents([.hour], from: self)
guard let hour = components.hour else {
return 0
}
return hour
}
set {
update(components: [.hour: newValue])
}
}
/// Set and get current minute.
var minute: Int {
get {
let calendar = Calendar.autoupdatingCurrent
let components = calendar.dateComponents([.minute], from: self)
guard let minute = components.minute else {
return 0
}
return minute
}
set {
update(components: [.minute: newValue])
}
}
/// Set and get current second.
var second: Int {
get {
let calendar = Calendar.autoupdatingCurrent
let components = calendar.dateComponents([.second], from: self)
guard let second = components.second else {
return 0
}
return second
}
set {
update(components: [.second: newValue])
}
}
/// Get current nanosecond.
var nanosecond: Int {
let calendar = Calendar.autoupdatingCurrent
let components = calendar.dateComponents([.nanosecond], from: self)
guard let nanosecond = components.nanosecond else {
return 0
}
return nanosecond
}
/// Get the weekday number from
/// - 1 - Sunday.
/// - 2 - Monday.
/// - 3 - Tuerday.
/// - 4 - Wednesday.
/// - 5 - Thursday.
/// - 6 - Friday.
/// - 7 - Saturday.
var weekday: Int {
let calendar = Calendar.autoupdatingCurrent
let components = calendar.dateComponents([.weekday], from: self)
guard let weekday = components.weekday else {
return 0
}
return weekday
}
/// Editable date components.
///
/// - year: Year component.
/// - month: Month component.
/// - day: Day component.
/// - hour: Hour component.
/// - minute: Minute component.
/// - second: Second component.
enum EditableDateComponents: Int {
case year
case month
case day
case hour
case minute
case second
}
// MARK: - Functions
/// Update current Date components.
///
/// - Parameters:
/// - components: Dictionary of components and values to be updated.
mutating func update(components: [EditableDateComponents: Int]) {
let autoupdatingCalendar = Calendar.autoupdatingCurrent
var dateComponents = autoupdatingCalendar.dateComponents([.year, .month, .day, .weekday, .hour, .minute, .second, .nanosecond], from: self)
for (component, value) in components {
switch component {
case .year:
dateComponents.year = value
case .month:
dateComponents.month = value
case .day:
dateComponents.day = value
case .hour:
dateComponents.hour = value
case .minute:
dateComponents.minute = value
case .second:
dateComponents.second = value
}
}
let calendar = Calendar(identifier: autoupdatingCalendar.identifier)
guard let date = calendar.date(from: dateComponents) else {
return
}
self = date
}
}
| 5bfd7979e6246f5f72c4dcf04d9371eb | 28.704225 | 147 | 0.549708 | false | false | false | false |
hujewelz/hotaru | refs/heads/master | Hotaru/Classes/Core/Cancelable.swift | mit | 1 | //
// Cancelable.swift
// Hotaru
//
// Created by huluobo on 2017/12/25.
//
import Foundation
public protocol Cancelable {
var isCanceled: Bool { get set }
mutating func cancel()
/// Add a Cancelabel to the default Cancel bag
func addToCancelBag()
/// Add a Cancelabel to Cancel bag
func addTo(_ cancelBag: CancelBag)
}
public extension Cancelable {
public mutating func cancel() {
isCanceled = true
}
public func addToCancelBag() {}
public func addTo(_ cancelBag: CancelBag) {
cancelBag.addToCancelBag(self)
}
}
public protocol CancelBag: class {
func addToCancelBag(_ cancelable: Cancelable)
}
final class Cancel {
typealias Canceled = () -> Void
var isCanceled: Bool = false
fileprivate weak var obj: CancelBag?
fileprivate var canceled: Canceled
static func create(obj: CancelBag? = nil, _ canceled: @escaping Canceled) -> Cancel {
return Cancel(obj: obj, canceled)
}
init(obj: CancelBag? = nil, _ canceled: @escaping Canceled) {
self.obj = obj
self.canceled = canceled
}
deinit {
canceled()
}
}
extension Cancel: Cancelable {
func addToCancelBag() {
obj?.addToCancelBag(self)
}
func cancel() {
isCanceled = true
canceled()
}
}
| 9dad41f0d252d3b70cdfeada9b0a588d | 17.837838 | 89 | 0.598996 | false | false | false | false |
brockboland/Vokoder | refs/heads/master | SwiftSampleProject/SwiftyVokoderTests/ManagedObjectContextTests.swift | mit | 3 | //
// ManagedObjectContextTests.swift
// SwiftSampleProject
//
// Created by Carl Hill-Popper on 2/9/16.
// Copyright © 2016 Vokal.
//
import XCTest
import Vokoder
@testable import SwiftyVokoder
class ManagedObjectContextTests: XCTestCase {
let manager = VOKCoreDataManager.sharedInstance()
override func setUp() {
super.setUp()
self.manager.resetCoreData()
self.manager.setResource("CoreDataModel", database: "CoreDataModel.sqlite")
// Don't need to keep a reference to the imported object, so set to _
let _ = Stop.vok_import(CTAData.allStopDictionaries())
self.manager.saveMainContextAndWait()
}
func testContextChain() {
let tempContext = self.manager.temporaryContext()
//temp context is a child of the main context
XCTAssertEqual(tempContext.parent, self.manager.managedObjectContext)
//main context has a private parent context
XCTAssertNotNil(self.manager.managedObjectContext.parent)
}
func testDeletingObjectsOnTempContextGetsSavedToMainContext() {
//get a temp context, delete from temp, save to main, verify deleted on main
let tempContext = self.manager.temporaryContext()
let countOfStations = self.manager.count(for: Station.self)
XCTAssertGreaterThan(countOfStations, 0)
tempContext.performAndWait {
self.manager.deleteAllObjects(of: Station.self, context: tempContext)
}
self.manager.saveAndMerge(withMainContextAndWait: tempContext)
let updatedCountOfStations = self.manager.count(for: Station.self)
XCTAssertEqual(updatedCountOfStations, 0)
XCTAssertNotEqual(countOfStations, updatedCountOfStations)
}
func testAddingObjectsOnTempContextGetsSavedToMainContext() {
//get a temp context, add to temp, save to main, verify added to main
let tempContext = self.manager.temporaryContext()
let countOfTrainLines: UInt = self.manager.count(for: TrainLine.self)
let expectedCountOfTrainLines = countOfTrainLines + 1
tempContext.performAndWait {
let silverLine = TrainLine.vok_newInstance(with: tempContext)
silverLine.identifier = "SLV"
silverLine.name = "Silver Line"
}
self.manager.saveAndMerge(withMainContextAndWait: tempContext)
let updatedCount = self.manager.count(for: TrainLine.self)
XCTAssertEqual(updatedCount, expectedCountOfTrainLines)
}
func testSaveWithoutWaitingEventuallySaves() {
let countOfStations = self.manager.count(for: Station.self)
XCTAssertGreaterThan(countOfStations, 0)
self.manager.deleteAllObjects(of: Station.self, context: nil)
self.expectation(forNotification: NSNotification.Name.NSManagedObjectContextDidSave.rawValue,
object: self.manager.managedObjectContext) { _ in
let updatedCountOfStations = self.manager.count(for: Station.self)
XCTAssertEqual(updatedCountOfStations, 0)
XCTAssertNotEqual(countOfStations, updatedCountOfStations)
return true
}
guard let rootContext = self.manager.managedObjectContext.parent else {
XCTFail("Expecting the main context to have a parent context")
return
}
self.expectation(forNotification: NSNotification.Name.NSManagedObjectContextDidSave.rawValue,
object: rootContext) { _ in
let updatedCountOfStations = self.manager.count(for: Station.self, for: rootContext)
XCTAssertEqual(updatedCountOfStations, 0)
XCTAssertNotEqual(countOfStations, updatedCountOfStations)
return true
}
self.manager.saveMainContext()
self.waitForExpectations(timeout: 10, handler: nil)
}
func testSaveAndMergeWithMainContextSavesGrandChildren() {
let childContext = self.manager.temporaryContext()
let grandChildContext = NSManagedObjectContext(concurrencyType: .privateQueueConcurrencyType)
grandChildContext.parent = childContext
let countOfStations = self.manager.count(for: Station.self)
XCTAssertGreaterThan(countOfStations, 0)
grandChildContext.performAndWait {
self.manager.deleteAllObjects(of: Station.self, context: grandChildContext)
}
self.manager.saveAndMerge(withMainContextAndWait: grandChildContext)
let updatedCountOfStations = self.manager.count(for: Station.self)
XCTAssertEqual(updatedCountOfStations, 0)
XCTAssertNotEqual(countOfStations, updatedCountOfStations)
}
func testUnsavedMainContextChangesGetPassedToTempContexts() {
let countOfStations = self.manager.count(for: Station.self)
XCTAssert(countOfStations > 0)
//temp contexts should reflect any changes to their parent context (the main context)
//regardless of if they were created before...
let childContextBeforeChanges = self.manager.temporaryContext()
//...changes are made to the parent context...
self.manager.deleteAllObjects(of: Station.self, context: nil)
//...or after the changes are made
let childContextAfterChanges = self.manager.temporaryContext()
let childCountOfStations = self.manager.count(for: Station.self, for: childContextBeforeChanges)
XCTAssertNotEqual(countOfStations, childCountOfStations)
XCTAssertEqual(childCountOfStations, 0)
let otherChildCountOfStations = self.manager.count(for: Station.self, for: childContextAfterChanges)
XCTAssertNotEqual(countOfStations, otherChildCountOfStations)
XCTAssertEqual(otherChildCountOfStations, childCountOfStations)
XCTAssertEqual(otherChildCountOfStations, 0)
}
func testUnsavedTempContextChangesDoNotGetPassedToMainContext() {
let countOfStations = self.manager.count(for: Station.self)
XCTAssertGreaterThan(countOfStations, 0)
let childContext = self.manager.temporaryContext()
self.manager.deleteAllObjects(of: Station.self, context: childContext)
let childCountOfStations = self.manager.count(for: Station.self, for: childContext)
XCTAssertNotEqual(countOfStations, childCountOfStations)
XCTAssertEqual(childCountOfStations, 0)
let updatedCountOfStations = self.manager.count(for: Station.self)
XCTAssertEqual(countOfStations, updatedCountOfStations)
}
}
| 198d753a368e09eae2f9fee9f471c352 | 40.802469 | 108 | 0.68547 | false | true | false | false |
SheepYo/HAYO | refs/heads/master | iOS/HAYO/FriendView.swift | mit | 1 | //
// FriendView.swift
// Sheep
//
// Created by mono on 8/3/14.
// Copyright (c) 2014 Sheep. All rights reserved.
//
import Foundation
class FriendView: UIView {
@IBOutlet weak var imageView: UIImageView!
@IBOutlet weak var nicknameLabel: UILabel!
class func create() -> FriendView {
return NSBundle.mainBundle().loadNibNamed("FriendView", owner: self, options: nil)[0] as FriendView
}
override func awakeFromNib() {
super.awakeFromNib()
imageView.configureAsMyCircle()
self.layer.borderColor = UIColor.whiteColor().CGColor
self.layer.borderWidth = 2
self.layer.cornerRadius = 4
}
var _user: User!
var user: User! {
get {
return _user
}
set {
_user = newValue
nicknameLabel.text = _user.username
if let image = _user.image {
imageView.image = image
return
}
imageView.sd_setImageWithURL(NSURL(string: _user.imageURL), completed: {image, error, type, url -> () in
})
}
}
} | d6cb93d0ca30589f324ec00cab75f9ef | 23.108696 | 112 | 0.57852 | false | false | false | false |
myriadmobile/Droar | refs/heads/master | Droar/Classes/Droar Core/Droar.swift | mit | 1 | //
// Droar.swift
// Pods
//
// Created by Nathan Jangula on 6/5/17.
//
//
import UIKit
@objc public enum DroarGestureType: UInt {
case tripleTap, panFromRight
}
@objc public class Droar: NSObject {
// Droar is a purely static class.
private override init() { }
static var window: DroarWindow!
internal static var navController: UINavigationController!
internal static var viewController: DroarViewController?
internal static let drawerWidth: CGFloat = 300
private static let startOnce = DispatchOnce()
public static private(set) var isStarted = false;
@objc public static func start() {
startOnce.perform {
initializeWindow()
setGestureType(.panFromRight)
KnobManager.sharedInstance.prepareForStart()
Droar.isStarted = true
}
}
@objc public static func setGestureType(_ type: DroarGestureType, _ threshold: CGFloat = 50.0) {
configureRecognizerForType(type, threshold)
}
//Navigation
@objc public static func pushViewController(_ viewController: UIViewController, animated: Bool) {
navController.pushViewController(viewController, animated: animated)
}
@objc public static func present(_ viewController: UIViewController, animated: Bool, completion: (() -> Void)?) {
navController.present(viewController, animated: animated, completion: completion)
}
//Internal Accessors
static func loadKeyWindow() -> UIWindow? {
var window = UIApplication.shared.windows.filter {$0.isKeyWindow}.first
if window == nil {
window = UIApplication.shared.keyWindow
}
return window
}
static func loadActiveResponder() -> UIViewController? {
return loadKeyWindow()?.rootViewController
}
}
//Knobs
extension Droar {
@objc public static func register(_ knob: DroarKnob) {
KnobManager.sharedInstance.registerStaticKnob(knob)
viewController?.tableView.reloadData()
}
@objc(registerDefaultKnobs:)
public static func objc_registerDefaultKnobs(knobs: [Int]) {
registerDefaultKnobs(knobs.map({ DefaultKnobType(rawValue: $0)! }))
}
public static func registerDefaultKnobs(_ knobs: [DefaultKnobType]) {
KnobManager.sharedInstance.registerDefaultKnobs(knobs)
viewController?.tableView.reloadData()
}
public static func refreshKnobs() {
viewController?.tableView.reloadData()
}
}
//Visibility
extension Droar {
//Technically this could be wrong depending on the tx value, but it is close enough.
@objc public static var isVisible: Bool { return !(navController.view.transform == CGAffineTransform.identity) }
@objc public static func openDroar(completion: (()->Void)? = nil) {
window.isHidden = false
UIView.animate(withDuration: 0.25, animations: {
navController.view.transform = CGAffineTransform(translationX: -navController.view.frame.size.width, y: 0)
window.setActivationPercent(1)
}) { (completed) in
//Swap gestures
openRecognizer.view?.removeGestureRecognizer(openRecognizer)
window.addGestureRecognizer(dismissalRecognizer)
completion?()
}
}
@objc public static func closeDroar(completion: (()->Void)? = nil) {
UIView.animate(withDuration: 0.25, animations: {
navController.view.transform = CGAffineTransform.identity
window.setActivationPercent(0)
}) { (completed) in
window.isHidden = true
//Swap gestures
dismissalRecognizer.view?.removeGestureRecognizer(dismissalRecognizer)
replaceGestureRecognizer(with: openRecognizer)
completion?()
}
}
@objc static func toggleVisibility(completion: (()->Void)? = nil) {
if isVisible {
closeDroar(completion: completion)
} else {
openDroar(completion: completion)
}
}
}
//Backwards compatibility
extension Droar {
public static func dismissWindow() {
closeDroar(completion: nil)
}
}
| 54a39ceca5c13326bba8c5494e2a8ff1 | 28.9375 | 118 | 0.638367 | false | false | false | false |
larryhou/swift | refs/heads/master | Tachograph/Tachograph/RouteBrowerController.swift | mit | 1 | //
// BrowserViewController.swift
// Tachograph
//
// Created by larryhou on 4/7/2017.
// Copyright © 2017 larryhou. All rights reserved.
//
import Foundation
import AVFoundation
import UIKit
import AVKit
class AssetCell: UITableViewCell {
@IBOutlet weak var ib_image: UIImageView!
@IBOutlet weak var ib_time: UILabel!
@IBOutlet weak var ib_progress: UIProgressView!
@IBOutlet weak var ib_id: UILabel!
@IBOutlet weak var ib_share: UIButton!
@IBOutlet weak var ib_download: UIButton!
var data: CameraModel.CameraAsset?
func progressUpdate(name: String, value: Float) {
if value < 1.0 || Float.nan == value {
ib_share.isHidden = true
} else {
ib_share.isHidden = false
}
ib_progress.progress = value
ib_download.isHidden = !ib_share.isHidden
ib_progress.isHidden = ib_download.isHidden
}
}
class EventBrowserController: RouteBrowerController {
override func viewDidLoad() {
super.viewDidLoad()
assetType = .event
}
override func loadModel() {
loading = true
CameraModel.shared.fetchEventVideos()
}
}
class RouteBrowerController: UIViewController,
UITableViewDelegate, UITableViewDataSource, CameraModelDelegate, AssetManagerDelegate {
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var movieView: UIView!
var videoAssets: [CameraModel.CameraAsset] = []
var formatter: DateFormatter!
var loadingIndicator: UIActivityIndicatorView!
var playController: AVPlayerViewController!
var assetType: CameraModel.AssetType = .route
override func viewDidLoad() {
super.viewDidLoad()
formatter = DateFormatter()
formatter.dateFormat = "HH:mm/MM-dd"
loadViews()
}
override func viewWillAppear(_ animated: Bool) {
loadModel()
CameraModel.shared.delegate = self
AssetManager.shared.delegate = self
}
func loadModel() {
loading = true
CameraModel.shared.fetchRouteVideos()
}
func loadViews() {
loadingIndicator = UIActivityIndicatorView(activityIndicatorStyle: .gray)
loadingIndicator.frame = CGRect(x: 0, y: 0, width: 50, height: 50)
loadingIndicator.hidesWhenStopped = false
playController = AVPlayerViewController()
playController.entersFullScreenWhenPlaybackBegins = true
playController.view.frame = CGRect(origin: CGPoint(), size: movieView.frame.size)
movieView.addSubview(playController.view)
}
func assetManager(_ manager: AssetManager, progress: Float, of name: String) {
for cell in tableView.visibleCells {
if let assetCell = cell as? AssetCell, let data = assetCell.data, data.name == name {
let progress = AssetManager.shared.get(progressOf: name)
assetCell.progressUpdate(name: name, value: progress)
break
}
}
}
func model(update: CameraModel.CameraAsset, type: CameraModel.AssetType) {
if type != assetType {return}
videoAssets.insert(update, at: 0)
let index = IndexPath(row: 0, section: 0)
tableView.insertRows(at: [index], with: UITableViewRowAnimation.top)
}
func model(assets: [CameraModel.CameraAsset], type: CameraModel.AssetType) {
if self.videoAssets.count != assets.count {
loading = false
videoAssets = assets
guard let tableView = self.tableView else {return}
tableView.reloadData()
}
guard let tableView = self.tableView else {return}
loadingIndicator.stopAnimating()
tableView.tableFooterView = nil
}
// MARK: cell
@IBAction func share(_ sender: UIButton) {
let rect = sender.superview!.convert(sender.frame, to: tableView)
if let list = tableView.indexPathsForRows(in: rect) {
let data = videoAssets[list[0].row]
if let location = AssetManager.shared.get(cacheOf: data.url) {
let controller = UIActivityViewController(activityItems: [location], applicationActivities: nil)
present(controller, animated: true, completion: nil)
}
}
}
@IBAction func download(_ sender: UIButton) {
let rect = sender.superview!.convert(sender.frame, to: tableView)
if let list = tableView.indexPathsForRows(in: rect) {
let data = videoAssets[list[0].row]
AssetManager.shared.load(url: data.url, completion: nil, progression: nil)
}
}
// MARK: table
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 70
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return videoAssets.count
}
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
if indexPath.row == videoAssets.count - 1 {
if tableView.tableFooterView == nil {
tableView.tableFooterView = loadingIndicator
}
loadingIndicator.startAnimating()
loadModel()
}
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let data = videoAssets[indexPath.row]
guard let url = URL(string: data.url) else {return}
if playController.player == nil {
playController.player = AVPlayer(url: url)
} else {
playController.player?.replaceCurrentItem(with: AVPlayerItem(url: url))
}
playController.player?.play()
}
var loading = false
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if let cell = tableView.dequeueReusableCell(withIdentifier: "AssetCell") as? AssetCell {
let data = videoAssets[indexPath.row]
cell.ib_time.text = formatter.string(from: data.timestamp)
cell.ib_progress.isHidden = true
cell.ib_progress.progress = 0.0
cell.ib_id.text = data.id
cell.data = data
if let url = AssetManager.shared.get(cacheOf: data.icon) {
cell.ib_image.image = try! UIImage(data: Data(contentsOf: url))
} else {
cell.ib_image.image = UIImage(named: "icon.thm")
AssetManager.shared.load(url: data.icon, completion: {
cell.ib_image.image = UIImage(data: $1)
})
}
cell.ib_share.isHidden = !AssetManager.shared.has(cacheOf: data.url)
cell.ib_download.isHidden = !cell.ib_share.isHidden
return cell
}
return UITableViewCell()
}
override var supportedInterfaceOrientations: UIInterfaceOrientationMask {return .portrait}
}
| bf186054a23fd6b136b5bb1e3e3c365b | 32.816425 | 112 | 0.637143 | false | false | false | false |
mobilabsolutions/jenkins-ios | refs/heads/master | JenkinsiOS/Controller/SettingsTableViewController.swift | mit | 1 | //
// SettingsTableViewController.swift
// JenkinsiOS
//
// Created by Robert on 07.08.18.
// Copyright © 2018 MobiLab Solutions. All rights reserved.
//
import UIKit
class SettingsTableViewController: UITableViewController, AccountProvidable, CurrentAccountProviding, CurrentAccountProvidingDelegate {
var account: Account? {
didSet {
guard let account = account
else { return }
updateSections(for: account)
tableView.reloadData()
}
}
private let remoteConfigManager = RemoteConfigurationManager()
private var shouldUseDirectAccountDesign: Bool {
return remoteConfigManager.configuration.shouldUseNewAccountDesign
}
var currentAccountDelegate: CurrentAccountProvidingDelegate?
@IBOutlet var versionLabel: UILabel!
private enum SettingsSection {
case plugins
case users
case accounts(currentAccountName: String)
case currentAccount(currentAccountName: String)
case otherAccounts(otherAccountNames: [String])
case about
struct Cell {
enum CellType {
case contentCell
case creationCell
}
let actionTitle: String
let type: CellType
}
var title: String {
switch self {
case .plugins:
return "PLUGINS"
case .users:
return "USERS"
case .accounts(currentAccountName: _):
return "ACCOUNTS"
case .currentAccount(currentAccountName: _):
return "ACTIVE ACCOUNT"
case .otherAccounts(otherAccountNames: _):
return "OTHER ACCOUNTS"
case .about:
return "INFO"
}
}
var cells: [Cell] {
switch self {
case .plugins:
return [Cell(actionTitle: "View Plugins", type: .contentCell)]
case .users:
return [Cell(actionTitle: "View Users", type: .contentCell)]
case let .accounts(currentAccountName):
return [Cell(actionTitle: currentAccountName, type: .contentCell)]
case let .currentAccount(currentAccountName):
return [Cell(actionTitle: currentAccountName, type: .contentCell)]
case let .otherAccounts(otherAccountNames):
return otherAccountNames.map { Cell(actionTitle: $0, type: .contentCell) }
+ [Cell(actionTitle: "Add account", type: .creationCell)]
case .about:
return [Cell(actionTitle: "About Butler", type: .contentCell), Cell(actionTitle: "FAQs", type: .contentCell)]
}
}
}
private var sections: [SettingsSection] = []
override func viewDidLoad() {
super.viewDidLoad()
tabBarController?.navigationItem.title = "Settings"
tableView.backgroundColor = Constants.UI.backgroundColor
tableView.separatorStyle = .none
tableView.register(UINib(nibName: "CreationTableViewCell", bundle: .main), forCellReuseIdentifier: Constants.Identifiers.creationCell)
setBottomContentInsetForOlderDevices()
setVersionNumberText()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
tabBarController?.navigationItem.title = "Settings"
tableView.reloadData()
// Make sure the navigation item does not contain the search bar.
if #available(iOS 11.0, *) {
tabBarController?.navigationItem.searchController = nil
}
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
LoggingManager.loggingManager.logSettingsView(accountsIncluded: shouldUseDirectAccountDesign)
}
override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
resizeFooter()
}
// MARK: - Table view data source
override func numberOfSections(in _: UITableView) -> Int {
return sections.count
}
override func tableView(_: UITableView, numberOfRowsInSection section: Int) -> Int {
return 1 + sections[section].cells.count
}
override func tableView(_: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
if indexPath.row == 0 {
return 47
}
return 42
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if indexPath.row == 0 {
let cell = tableView.dequeueReusableCell(withIdentifier: Constants.Identifiers.headerCell, for: indexPath)
cell.textLabel?.text = sections[indexPath.section].title
cell.selectionStyle = .none
cell.contentView.backgroundColor = Constants.UI.backgroundColor
cell.textLabel?.backgroundColor = Constants.UI.backgroundColor
cell.textLabel?.textColor = Constants.UI.skyBlue
cell.textLabel?.font = UIFont.boldDefaultFont(ofSize: 13)
return cell
} else if sections[indexPath.section].cells[indexPath.row - 1].type == .creationCell {
let cell = tableView.dequeueReusableCell(withIdentifier: Constants.Identifiers.creationCell, for: indexPath) as! CreationTableViewCell
cell.contentView.backgroundColor = .white
cell.titleLabel.text = sections[indexPath.section].cells[indexPath.row - 1].actionTitle
return cell
} else {
let cell = tableView.dequeueReusableCell(withIdentifier: Constants.Identifiers.settingsCell, for: indexPath) as! BasicTableViewCell
cell.contentView.backgroundColor = .white
cell.title = sections[indexPath.section].cells[indexPath.row - 1].actionTitle
return cell
}
}
override func tableView(_: UITableView, didSelectRowAt indexPath: IndexPath) {
guard indexPath.row != 0
else { return }
if sections[indexPath.section].cells[indexPath.row - 1].type == .creationCell {
performSegue(withIdentifier: Constants.Identifiers.editAccountSegue, sender: sections[indexPath.section].cells[indexPath.row - 1])
return
}
switch sections[indexPath.section] {
case .plugins:
performSegue(withIdentifier: Constants.Identifiers.showPluginsSegue, sender: nil)
case .users:
performSegue(withIdentifier: Constants.Identifiers.showUsersSegue, sender: nil)
case .accounts:
performSegue(withIdentifier: Constants.Identifiers.showAccountsSegue, sender: nil)
case .currentAccount:
performSegue(withIdentifier: Constants.Identifiers.editAccountSegue, sender: account)
case .otherAccounts:
guard let current = account
else { return }
let nonCurrent = nonCurrentAccounts(currentAccount: current)
performSegue(withIdentifier: Constants.Identifiers.editAccountSegue, sender: nonCurrent[indexPath.row - 1])
case .about:
if indexPath.row == 1 {
performSegue(withIdentifier: Constants.Identifiers.aboutSegue, sender: nil)
} else if indexPath.row == 2 {
performSegue(withIdentifier: Constants.Identifiers.faqSegue, sender: nil)
}
}
}
func didChangeCurrentAccount(current: Account) {
currentAccountDelegate?.didChangeCurrentAccount(current: current)
account = current
tableView.reloadData()
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let providedAccount = sender as? Account, var dest = segue.destination as? AccountProvidable {
dest.account = providedAccount
} else if let cell = sender as? SettingsSection.Cell, cell.type == .creationCell, var dest = segue.destination as? AccountProvidable {
dest.account = nil
} else if var dest = segue.destination as? AccountProvidable {
dest.account = account
}
if var dest = segue.destination as? CurrentAccountProviding {
dest.currentAccountDelegate = self
}
if let dest = segue.destination as? AccountDeletionNotifying {
dest.accountDeletionDelegate = tabBarController as? AccountDeletionNotified
}
if let dest = segue.destination as? AddAccountContainerViewController {
dest.delegate = self
}
if let dest = segue.destination as? AddAccountContainerViewController, let account = sender as? Account {
dest.editingCurrentAccount = account == self.account
}
}
private func updateSections(for account: Account) {
if shouldUseDirectAccountDesign {
sections = [
.plugins, .users,
.currentAccount(currentAccountName: account.displayName ?? account.baseUrl.absoluteString),
.otherAccounts(otherAccountNames: nonCurrentAccounts(currentAccount: account).map { $0.displayName ?? $0.baseUrl.absoluteString }),
.about,
]
} else {
sections = [
.plugins, .users,
.accounts(currentAccountName: account.displayName ?? account.baseUrl.absoluteString),
.about,
]
}
}
private func nonCurrentAccounts(currentAccount account: Account) -> [Account] {
return AccountManager.manager.accounts.filter { !$0.isEqual(account) }.sorted(by: { (first, second) -> Bool in
(first.displayName ?? first.baseUrl.absoluteString) < (second.displayName ?? second.baseUrl.absoluteString)
})
}
private func setVersionNumberText() {
let provider = VersionNumberBuilder()
versionLabel.text = provider.fullVersionNumberDescription
}
private func resizeFooter() {
guard let footer = tableView.tableFooterView
else { return }
let tabBarHeight = tabBarController?.tabBar.frame.height ?? 0
let navigationBarHeight = navigationController?.navigationBar.frame.height ?? 0
let statusBarHeight = UIApplication.shared.statusBarFrame.height
let additionalHeight = tabBarHeight + navigationBarHeight + statusBarHeight
let newMinimumHeight = tableView.frame.height - tableView.visibleCells.reduce(0, { $0 + $1.bounds.height }) - additionalHeight
footer.frame = CGRect(x: footer.frame.minX, y: footer.frame.minY, width: footer.frame.width,
height: max(20, newMinimumHeight))
}
}
extension SettingsTableViewController: AddAccountTableViewControllerDelegate {
func didEditAccount(account: Account, oldAccount: Account?, useAsCurrentAccount: Bool) {
if useAsCurrentAccount {
self.account = account
currentAccountDelegate?.didChangeCurrentAccount(current: account)
}
var shouldAnimateNavigationStackChanges = true
if oldAccount == nil {
let confirmationController = AccountCreatedViewController(nibName: "AccountCreatedViewController", bundle: .main)
confirmationController.delegate = self
navigationController?.pushViewController(confirmationController, animated: true)
shouldAnimateNavigationStackChanges = false
}
var viewControllers = navigationController?.viewControllers ?? []
// Remove the add account view controller from the navigation controller stack
viewControllers = viewControllers.filter { !($0 is AddAccountContainerViewController) }
navigationController?.setViewControllers(viewControllers, animated: shouldAnimateNavigationStackChanges)
if let currentAccount = self.account {
updateSections(for: currentAccount)
}
tableView.reloadData()
}
func didDeleteAccount(account: Account) {
if account == self.account {
self.account = AccountManager.manager.accounts.first
}
if let currentAccount = self.account {
updateSections(for: currentAccount)
}
tableView.reloadData()
navigationController?.popViewController(animated: false)
let handler = OnBoardingHandler()
if AccountManager.manager.accounts.isEmpty, handler.shouldShowAccountCreationViewController() {
let navigationController = UINavigationController()
present(navigationController, animated: false, completion: nil)
handler.showAccountCreationViewController(on: navigationController, delegate: self)
}
}
}
extension SettingsTableViewController: AccountCreatedViewControllerDelegate {
func doneButtonPressed() {
navigationController?.popViewController(animated: true)
}
}
extension SettingsTableViewController: OnBoardingDelegate {
func didFinishOnboarding(didAddAccount _: Bool) {
account = AccountManager.manager.currentAccount ?? AccountManager.manager.accounts.first
dismiss(animated: true, completion: nil)
}
}
| 89b91ab4e134be711bed6dadfbc76e58 | 39.387692 | 147 | 0.655036 | false | false | false | false |
4jchc/4jchc-BaiSiBuDeJie | refs/heads/master | 4jchc-BaiSiBuDeJie/4jchc-BaiSiBuDeJie/Class/Essence-精华/View/XMGCommentCell.swift | apache-2.0 | 1 | //
// XMGCommentCell.swift
// 4jchc-BaiSiBuDeJie
//
// Created by 蒋进 on 16/3/1.
// Copyright © 2016年 蒋进. All rights reserved.
//
import UIKit
protocol TableViewCellDelegate
{
func tableCellSelected( var tableCell : UITableViewCell)
}
class XMGCommentCell: UITableViewCell {
@IBOutlet weak var profileImageView: UIImageView!
@IBOutlet weak var sexView: UIImageView!
@IBOutlet weak var contentLabel: UILabel!
@IBOutlet weak var usernameLabel: UILabel!
@IBOutlet weak var likeCountLabel: UILabel!
@IBOutlet weak var voiceButton: UIButton!
var delegate : TableViewCellDelegate?
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
if((self.delegate) != nil)
{
delegate?.tableCellSelected(self);
}
// Configure the view for the selected state
}
/// 让label有资格成为第一响应者
override func canBecomeFirstResponder() -> Bool {
return true
}
/**
* label能执行哪些操作(比如copy, paste等等)
* @return YES:支持这种操作
*/
override func canPerformAction(action: Selector, withSender sender: AnyObject?) -> Bool {
//super.canPerformAction(action, withSender: sender)
return false
}
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
self.backgroundView = UIImageView(image: UIImage(named: "mainCellBackground"))
// self.profileImageView.layer.cornerRadius = self.profileImageView.width * 0.5;
// self.profileImageView.layer.masksToBounds = true
}
/** 评论 */
var comment:XMGComment?{
didSet{
//self.profileImageView.sd_setImageWithURL(NSURL(string: comment!.user!.profile_image!), placeholderImage: UIImage(named: "defaultUserIcon"))
self.profileImageView.setHeader(comment!.user!.profile_image!)
self.sexView.image = comment!.user!.sex?.isEqualToString(XMGUserSexMale) == true ? UIImage(named: "Profile_manIcon") : UIImage(named: "Profile_womanIcon")
self.contentLabel.text = comment!.content;
self.usernameLabel.text = comment!.user!.username;
self.likeCountLabel.text = String(format: "%zd",comment!.like_count)
if (comment!.voiceuri!.length > 0) {
self.voiceButton.hidden = false
self.voiceButton.setTitle("\(comment!.voicetime)''", forState: .Normal)
} else {
self.voiceButton.hidden = true
}
}
}
/*
//MARK: 重写frame来设置cell的内嵌
override var frame:CGRect{
set{
var frame = newValue
frame.origin.x = XMGTopicCellMargin;
frame.size.width -= 2 * XMGTopicCellMargin;
super.frame=frame
}
get{
return super.frame
}
}
*/
}
| 407f92f9677ed2a99287300613053c8e | 26.896226 | 166 | 0.611769 | false | false | false | false |
Ataraxiis/MGW-Esport | refs/heads/develop | Carthage/Checkouts/RxSwift/RxSwift/Observables/Observable+Time.swift | apache-2.0 | 34 | //
// Observable+Time.swift
// Rx
//
// Created by Krunoslav Zaher on 3/22/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
// MARK: throttle
extension ObservableType {
/**
Ignores elements from an observable sequence which are followed by another element within a specified relative time duration, using the specified scheduler to run throttling timers.
`throttle` and `debounce` are synonyms.
- seealso: [debounce operator on reactivex.io](http://reactivex.io/documentation/operators/debounce.html)
- parameter dueTime: Throttling duration for each element.
- parameter scheduler: Scheduler to run the throttle timers and send events on.
- returns: The throttled sequence.
*/
@warn_unused_result(message="http://git.io/rxs.uo")
public func throttle(dueTime: RxTimeInterval, scheduler: SchedulerType)
-> Observable<E> {
return Throttle(source: self.asObservable(), dueTime: dueTime, scheduler: scheduler)
}
/**
Ignores elements from an observable sequence which are followed by another element within a specified relative time duration, using the specified scheduler to run throttling timers.
`throttle` and `debounce` are synonyms.
- seealso: [debounce operator on reactivex.io](http://reactivex.io/documentation/operators/debounce.html)
- parameter dueTime: Throttling duration for each element.
- parameter scheduler: Scheduler to run the throttle timers and send events on.
- returns: The throttled sequence.
*/
@warn_unused_result(message="http://git.io/rxs.uo")
public func debounce(dueTime: RxTimeInterval, scheduler: SchedulerType)
-> Observable<E> {
return Throttle(source: self.asObservable(), dueTime: dueTime, scheduler: scheduler)
}
}
// MARK: sample
extension ObservableType {
/**
Samples the source observable sequence using a samper observable sequence producing sampling ticks.
Upon each sampling tick, the latest element (if any) in the source sequence during the last sampling interval is sent to the resulting sequence.
**In case there were no new elements between sampler ticks, no element is sent to the resulting sequence.**
- seealso: [sample operator on reactivex.io](http://reactivex.io/documentation/operators/sample.html)
- parameter sampler: Sampling tick sequence.
- returns: Sampled observable sequence.
*/
@warn_unused_result(message="http://git.io/rxs.uo")
public func sample<O: ObservableType>(sampler: O)
-> Observable<E> {
return Sample(source: self.asObservable(), sampler: sampler.asObservable(), onlyNew: true)
}
}
extension Observable where Element : SignedIntegerType {
/**
Returns an observable sequence that produces a value after each period, using the specified scheduler to run timers and to send out observer messages.
- seealso: [interval operator on reactivex.io](http://reactivex.io/documentation/operators/interval.html)
- parameter period: Period for producing the values in the resulting sequence.
- parameter scheduler: Scheduler to run the timer on.
- returns: An observable sequence that produces a value after each period.
*/
@warn_unused_result(message="http://git.io/rxs.uo")
public static func interval(period: RxTimeInterval, scheduler: SchedulerType)
-> Observable<E> {
return Timer(dueTime: period,
period: period,
scheduler: scheduler
)
}
}
// MARK: timer
extension Observable where Element: SignedIntegerType {
/**
Returns an observable sequence that periodically produces a value after the specified initial relative due time has elapsed, using the specified scheduler to run timers.
- seealso: [timer operator on reactivex.io](http://reactivex.io/documentation/operators/timer.html)
- parameter dueTime: Relative time at which to produce the first value.
- parameter period: Period to produce subsequent values.
- parameter scheduler: Scheduler to run timers on.
- returns: An observable sequence that produces a value after due time has elapsed and then each period.
*/
@warn_unused_result(message="http://git.io/rxs.uo")
public static func timer(dueTime: RxTimeInterval, period: RxTimeInterval? = nil, scheduler: SchedulerType)
-> Observable<E> {
return Timer(
dueTime: dueTime,
period: period,
scheduler: scheduler
)
}
}
// MARK: take
extension ObservableType {
/**
Takes elements for the specified duration from the start of the observable source sequence, using the specified scheduler to run timers.
- seealso: [take operator on reactivex.io](http://reactivex.io/documentation/operators/take.html)
- parameter duration: Duration for taking elements from the start of the sequence.
- parameter scheduler: Scheduler to run the timer on.
- returns: An observable sequence with the elements taken during the specified duration from the start of the source sequence.
*/
@warn_unused_result(message="http://git.io/rxs.uo")
public func take(duration: RxTimeInterval, scheduler: SchedulerType)
-> Observable<E> {
return TakeTime(source: self.asObservable(), duration: duration, scheduler: scheduler)
}
}
// MARK: skip
extension ObservableType {
/**
Skips elements for the specified duration from the start of the observable source sequence, using the specified scheduler to run timers.
- seealso: [skip operator on reactivex.io](http://reactivex.io/documentation/operators/skip.html)
- parameter duration: Duration for skipping elements from the start of the sequence.
- parameter scheduler: Scheduler to run the timer on.
- returns: An observable sequence with the elements skipped during the specified duration from the start of the source sequence.
*/
@warn_unused_result(message="http://git.io/rxs.uo")
public func skip(duration: RxTimeInterval, scheduler: SchedulerType)
-> Observable<E> {
return SkipTime(source: self.asObservable(), duration: duration, scheduler: scheduler)
}
}
// MARK: ignoreElements
extension ObservableType {
/**
Skips elements and completes (or errors) when the receiver completes (or errors). Equivalent to filter that always returns false.
- seealso: [ignoreElements operator on reactivex.io](http://reactivex.io/documentation/operators/ignoreelements.html)
- returns: An observable sequence that skips all elements of the source sequence.
*/
@warn_unused_result(message="http://git.io/rxs.uo")
public func ignoreElements()
-> Observable<E> {
return filter { _ -> Bool in
return false
}
}
}
// MARK: delaySubscription
extension ObservableType {
/**
Time shifts the observable sequence by delaying the subscription with the specified relative time duration, using the specified scheduler to run timers.
- seealso: [delay operator on reactivex.io](http://reactivex.io/documentation/operators/delay.html)
- parameter dueTime: Relative time shift of the subscription.
- parameter scheduler: Scheduler to run the subscription delay timer on.
- returns: Time-shifted sequence.
*/
@warn_unused_result(message="http://git.io/rxs.uo")
public func delaySubscription(dueTime: RxTimeInterval, scheduler: SchedulerType)
-> Observable<E> {
return DelaySubscription(source: self.asObservable(), dueTime: dueTime, scheduler: scheduler)
}
}
// MARK: buffer
extension ObservableType {
/**
Projects each element of an observable sequence into a buffer that's sent out when either it's full or a given amount of time has elapsed, using the specified scheduler to run timers.
A useful real-world analogy of this overload is the behavior of a ferry leaving the dock when all seats are taken, or at the scheduled time of departure, whichever event occurs first.
- seealso: [buffer operator on reactivex.io](http://reactivex.io/documentation/operators/buffer.html)
- parameter timeSpan: Maximum time length of a buffer.
- parameter count: Maximum element count of a buffer.
- parameter scheduler: Scheduler to run buffering timers on.
- returns: An observable sequence of buffers.
*/
@warn_unused_result(message="http://git.io/rxs.uo")
public func buffer(timeSpan timeSpan: RxTimeInterval, count: Int, scheduler: SchedulerType)
-> Observable<[E]> {
return BufferTimeCount(source: self.asObservable(), timeSpan: timeSpan, count: count, scheduler: scheduler)
}
}
// MARK: window
extension ObservableType {
/**
Projects each element of an observable sequence into a window that is completed when either it’s full or a given amount of time has elapsed.
- seealso: [window operator on reactivex.io](http://reactivex.io/documentation/operators/window.html)
- parameter timeSpan: Maximum time length of a window.
- parameter count: Maximum element count of a window.
- parameter scheduler: Scheduler to run windowing timers on.
- returns: An observable sequence of windows (instances of `Observable`).
*/
@warn_unused_result(message="http://git.io/rxs.uo")
public func window(timeSpan timeSpan: RxTimeInterval, count: Int, scheduler: SchedulerType)
-> Observable<Observable<E>> {
return WindowTimeCount(source: self.asObservable(), timeSpan: timeSpan, count: count, scheduler: scheduler)
}
}
// MARK: timeout
extension ObservableType {
/**
Applies a timeout policy for each element in the observable sequence. If the next element isn't received within the specified timeout duration starting from its predecessor, a TimeoutError is propagated to the observer.
- seealso: [timeout operator on reactivex.io](http://reactivex.io/documentation/operators/timeout.html)
- parameter dueTime: Maximum duration between values before a timeout occurs.
- parameter scheduler: Scheduler to run the timeout timer on.
- returns: An observable sequence with a TimeoutError in case of a timeout.
*/
@warn_unused_result(message="http://git.io/rxs.uo")
public func timeout(dueTime: RxTimeInterval, scheduler: SchedulerType)
-> Observable<E> {
return Timeout(source: self.asObservable(), dueTime: dueTime, other: Observable.error(RxError.Timeout), scheduler: scheduler)
}
/**
Applies a timeout policy for each element in the observable sequence, using the specified scheduler to run timeout timers. If the next element isn't received within the specified timeout duration starting from its predecessor, the other observable sequence is used to produce future messages from that point on.
- seealso: [timeout operator on reactivex.io](http://reactivex.io/documentation/operators/timeout.html)
- parameter dueTime: Maximum duration between values before a timeout occurs.
- parameter other: Sequence to return in case of a timeout.
- parameter scheduler: Scheduler to run the timeout timer on.
- returns: The source sequence switching to the other sequence in case of a timeout.
*/
@warn_unused_result(message="http://git.io/rxs.uo")
public func timeout<O: ObservableConvertibleType where E == O.E>(dueTime: RxTimeInterval, other: O, scheduler: SchedulerType)
-> Observable<E> {
return Timeout(source: self.asObservable(), dueTime: dueTime, other: other.asObservable(), scheduler: scheduler)
}
}
| 9b01c1a6ca5233e8345b29264bcaef4f | 41.79562 | 316 | 0.713543 | false | false | false | false |
antlr/antlr4 | refs/heads/dev | runtime/Swift/Sources/Antlr4/RuleContext.swift | bsd-3-clause | 4 | /* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
* Use of this file is governed by the BSD 3-clause license that
* can be found in the LICENSE.txt file in the project root.
*/
/// A rule context is a record of a single rule invocation.
///
/// We form a stack of these context objects using the parent
/// pointer. A parent pointer of null indicates that the current
/// context is the bottom of the stack. The ParserRuleContext subclass
/// as a children list so that we can turn this data structure into a
/// tree.
///
/// The root node always has a null pointer and invokingState of ATNState.INVALID_STATE_NUMBER.
///
/// Upon entry to parsing, the first invoked rule function creates a
/// context object (asubclass specialized for that rule such as
/// SContext) and makes it the root of a parse tree, recorded by field
/// Parser._ctx.
///
/// public final SContext s() throws RecognitionException {
/// SContext _localctx = new SContext(_ctx, getState()); <-- create new node
/// enterRule(_localctx, 0, RULE_s); <-- push it
/// ...
/// exitRule(); <-- pop back to _localctx
/// return _localctx;
/// }
///
/// A subsequent rule invocation of r from the start rule s pushes a
/// new context object for r whose parent points at s and use invoking
/// state is the state with r emanating as edge label.
///
/// The invokingState fields from a context object to the root
/// together form a stack of rule indication states where the root
/// (bottom of the stack) has a -1 sentinel value. If we invoke start
/// symbol s then call r1, which calls r2, the would look like
/// this:
///
/// SContext[-1] <- root node (bottom of the stack)
/// R1Context[p] <- p in rule s called r1
/// R2Context[q] <- q in rule r1 called r2
///
/// So the top of the stack, _ctx, represents a call to the current
/// rule and it holds the return address from another rule that invoke
/// to this rule. To invoke a rule, we must always have a current context.
///
/// The parent contexts are useful for computing lookahead sets and
/// getting error information.
///
/// These objects are used during parsing and prediction.
/// For the special case of parsers, we use the subclass
/// ParserRuleContext.
///
/// - SeeAlso: org.antlr.v4.runtime.ParserRuleContext
///
open class RuleContext: RuleNode {
/// What context invoked this rule?
public weak var parent: RuleContext?
/// What state invoked the rule associated with this context?
/// The "return address" is the followState of invokingState
/// If parent is null, this should be ATNState.INVALID_STATE_NUMBER
/// this context object represents the start rule.
///
public var invokingState = ATNState.INVALID_STATE_NUMBER
public init() {
}
public init(_ parent: RuleContext?, _ invokingState: Int) {
self.parent = parent
//if ( parent!=null ) { print("invoke "+stateNumber+" from "+parent)}
self.invokingState = invokingState
}
open func depth() -> Int {
var n = 0
var p: RuleContext? = self
while let pWrap = p {
p = pWrap.parent
n += 1
}
return n
}
/// A context is empty if there is no invoking state; meaning nobody called
/// current context.
///
open func isEmpty() -> Bool {
return invokingState == ATNState.INVALID_STATE_NUMBER
}
// satisfy the ParseTree / SyntaxTree interface
open func getSourceInterval() -> Interval {
return Interval.INVALID
}
open func getRuleContext() -> RuleContext {
return self
}
open func getParent() -> Tree? {
return parent
}
open func setParent(_ parent: RuleContext) {
self.parent = parent
}
open func getPayload() -> AnyObject {
return self
}
/// Return the combined text of all child nodes. This method only considers
/// tokens which have been added to the parse tree.
///
/// Since tokens on hidden channels (e.g. whitespace or comments) are not
/// added to the parse trees, they will not appear in the output of this
/// method.
///
open func getText() -> String {
let length = getChildCount()
if length == 0 {
return ""
}
var builder = ""
for i in 0..<length {
builder += self[i].getText()
}
return builder
}
open func getRuleIndex() -> Int {
return -1
}
open func getAltNumber() -> Int { return ATN.INVALID_ALT_NUMBER }
open func setAltNumber(_ altNumber: Int) { }
open func getChild(_ i: Int) -> Tree? {
return nil
}
open func getChildCount() -> Int {
return 0
}
open subscript(index: Int) -> ParseTree {
preconditionFailure("Index out of range (RuleContext never has children, though its subclasses may).")
}
open func accept<T>(_ visitor: ParseTreeVisitor<T>) -> T? {
return visitor.visitChildren(self)
}
/// Print out a whole tree, not just a node, in LISP format
/// (root child1 .. childN). Print just a node if this is a leaf.
/// We have to know the recognizer so we can get rule names.
///
open func toStringTree(_ recog: Parser) -> String {
return Trees.toStringTree(self, recog)
}
/// Print out a whole tree, not just a node, in LISP format
/// (root child1 .. childN). Print just a node if this is a leaf.
///
public func toStringTree(_ ruleNames: [String]?) -> String {
return Trees.toStringTree(self, ruleNames)
}
open func toStringTree() -> String {
return toStringTree(nil)
}
open var description: String {
return toString(nil, nil)
}
open var debugDescription: String {
return description
}
public final func toString<T>(_ recog: Recognizer<T>) -> String {
return toString(recog, ParserRuleContext.EMPTY)
}
public final func toString(_ ruleNames: [String]) -> String {
return toString(ruleNames, nil)
}
// recog null unless ParserRuleContext, in which case we use subclass toString(...)
open func toString<T>(_ recog: Recognizer<T>?, _ stop: RuleContext) -> String {
let ruleNames = recog?.getRuleNames()
return toString(ruleNames, stop)
}
open func toString(_ ruleNames: [String]?, _ stop: RuleContext?) -> String {
var buf = ""
var p: RuleContext? = self
buf += "["
while let pWrap = p, pWrap !== stop {
if let ruleNames = ruleNames {
let ruleIndex = pWrap.getRuleIndex()
let ruleIndexInRange = (ruleIndex >= 0 && ruleIndex < ruleNames.count)
let ruleName = (ruleIndexInRange ? ruleNames[ruleIndex] : String(ruleIndex))
buf += ruleName
}
else {
if !pWrap.isEmpty() {
buf += String(pWrap.invokingState)
}
}
if let pWp = pWrap.parent, (ruleNames != nil || !pWp.isEmpty()) {
buf += " "
}
p = pWrap.parent
}
buf += "]"
return buf
}
open func castdown<T>(_ subType: T.Type) -> T {
return self as! T
}
}
| b2f8d05afdd09a7567bcce411a6c6e4d | 29.932773 | 110 | 0.609209 | false | false | false | false |
alblue/swift-corelibs-foundation | refs/heads/master | Foundation/NSStringAPI.swift | apache-2.0 | 3 | //===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
//
// Exposing the API of NSString on Swift's String
//
//===----------------------------------------------------------------------===//
// Important Note
// ==============
//
// This file is shared between two projects:
//
// 1. https://github.com/apple/swift/tree/master/stdlib/public/SDK/Foundation
// 2. https://github.com/apple/swift-corelibs-foundation/tree/master/Foundation
//
// If you change this file, you must update it in both places.
#if !DEPLOYMENT_RUNTIME_SWIFT
@_exported import Foundation // Clang module
#endif
// Open Issues
// ===========
//
// Property Lists need to be properly bridged
//
func _toNSArray<T, U : AnyObject>(_ a: [T], f: (T) -> U) -> NSArray {
let result = NSMutableArray(capacity: a.count)
for s in a {
result.add(f(s))
}
return result
}
#if !DEPLOYMENT_RUNTIME_SWIFT
// We only need this for UnsafeMutablePointer, but there's not currently a way
// to write that constraint.
extension Optional {
/// Invokes `body` with `nil` if `self` is `nil`; otherwise, passes the
/// address of `object` to `body`.
///
/// This is intended for use with Foundation APIs that return an Objective-C
/// type via out-parameter where it is important to be able to *ignore* that
/// parameter by passing `nil`. (For some APIs, this may allow the
/// implementation to avoid some work.)
///
/// In most cases it would be simpler to just write this code inline, but if
/// `body` is complicated than that results in unnecessarily repeated code.
internal func _withNilOrAddress<NSType : AnyObject, ResultType>(
of object: inout NSType?,
_ body:
(AutoreleasingUnsafeMutablePointer<NSType?>?) -> ResultType
) -> ResultType {
return self == nil ? body(nil) : body(&object)
}
}
#endif
extension String {
//===--- Class Methods --------------------------------------------------===//
//===--------------------------------------------------------------------===//
// @property (class) const NSStringEncoding *availableStringEncodings;
/// An array of the encodings that strings support in the application's
/// environment.
public static var availableStringEncodings: [Encoding] {
var result = [Encoding]()
var p = NSString.availableStringEncodings
while p.pointee != 0 {
result.append(Encoding(rawValue: p.pointee))
p += 1
}
return result
}
// @property (class) NSStringEncoding defaultCStringEncoding;
/// The C-string encoding assumed for any method accepting a C string as an
/// argument.
public static var defaultCStringEncoding: Encoding {
return Encoding(rawValue: NSString.defaultCStringEncoding)
}
// + (NSString *)localizedNameOfStringEncoding:(NSStringEncoding)encoding
/// Returns a human-readable string giving the name of the specified encoding.
///
/// - Parameter encoding: A string encoding. For possible values, see
/// `String.Encoding`.
/// - Returns: A human-readable string giving the name of `encoding` in the
/// current locale.
public static func localizedName(
of encoding: Encoding
) -> String {
return NSString.localizedName(of: encoding.rawValue)
}
// + (instancetype)localizedStringWithFormat:(NSString *)format, ...
/// Returns a string created by using a given format string as a
/// template into which the remaining argument values are substituted
/// according to the user's default locale.
public static func localizedStringWithFormat(
_ format: String, _ arguments: CVarArg...
) -> String {
return String(format: format, locale: Locale.current,
arguments: arguments)
}
//===--------------------------------------------------------------------===//
// NSString factory functions that have a corresponding constructor
// are omitted.
//
// + (instancetype)string
//
// + (instancetype)
// stringWithCharacters:(const unichar *)chars length:(NSUInteger)length
//
// + (instancetype)stringWithFormat:(NSString *)format, ...
//
// + (instancetype)
// stringWithContentsOfFile:(NSString *)path
// encoding:(NSStringEncoding)enc
// error:(NSError **)error
//
// + (instancetype)
// stringWithContentsOfFile:(NSString *)path
// usedEncoding:(NSStringEncoding *)enc
// error:(NSError **)error
//
// + (instancetype)
// stringWithContentsOfURL:(NSURL *)url
// encoding:(NSStringEncoding)enc
// error:(NSError **)error
//
// + (instancetype)
// stringWithContentsOfURL:(NSURL *)url
// usedEncoding:(NSStringEncoding *)enc
// error:(NSError **)error
//
// + (instancetype)
// stringWithCString:(const char *)cString
// encoding:(NSStringEncoding)enc
//===--------------------------------------------------------------------===//
//===--- Adds nothing for String beyond what String(s) does -------------===//
// + (instancetype)stringWithString:(NSString *)aString
//===--------------------------------------------------------------------===//
// + (instancetype)stringWithUTF8String:(const char *)bytes
/// Creates a string by copying the data from a given
/// C array of UTF8-encoded bytes.
public init?(utf8String bytes: UnsafePointer<CChar>) {
if let ns = NSString(utf8String: bytes) {
self = String._unconditionallyBridgeFromObjectiveC(ns)
} else {
return nil
}
}
}
extension String {
//===--- Already provided by String's core ------------------------------===//
// - (instancetype)init
//===--- Initializers that can fail -------------------------------------===//
// - (instancetype)
// initWithBytes:(const void *)bytes
// length:(NSUInteger)length
// encoding:(NSStringEncoding)encoding
/// Creates a new string equivalent to the given bytes interpreted in the
/// specified encoding.
///
/// - Parameters:
/// - bytes: A sequence of bytes to interpret using `encoding`.
/// - encoding: The ecoding to use to interpret `bytes`.
public init? <S: Sequence>(bytes: S, encoding: Encoding)
where S.Iterator.Element == UInt8 {
let byteArray = Array(bytes)
if let ns = NSString(
bytes: byteArray, length: byteArray.count, encoding: encoding.rawValue) {
self = String._unconditionallyBridgeFromObjectiveC(ns)
} else {
return nil
}
}
// - (instancetype)
// initWithBytesNoCopy:(void *)bytes
// length:(NSUInteger)length
// encoding:(NSStringEncoding)encoding
// freeWhenDone:(BOOL)flag
/// Creates a new string that contains the specified number of bytes from the
/// given buffer, interpreted in the specified encoding, and optionally
/// frees the buffer.
///
/// - Warning: This initializer is not memory-safe!
public init?(
bytesNoCopy bytes: UnsafeMutableRawPointer, length: Int,
encoding: Encoding, freeWhenDone flag: Bool
) {
if let ns = NSString(
bytesNoCopy: bytes, length: length, encoding: encoding.rawValue,
freeWhenDone: flag) {
self = String._unconditionallyBridgeFromObjectiveC(ns)
} else {
return nil
}
}
// - (instancetype)
// initWithCharacters:(const unichar *)characters
// length:(NSUInteger)length
/// Creates a new string that contains the specified number of characters
/// from the given C array of Unicode characters.
public init(
utf16CodeUnits: UnsafePointer<unichar>,
count: Int
) {
self = String._unconditionallyBridgeFromObjectiveC(NSString(characters: utf16CodeUnits, length: count))
}
// - (instancetype)
// initWithCharactersNoCopy:(unichar *)characters
// length:(NSUInteger)length
// freeWhenDone:(BOOL)flag
/// Creates a new string that contains the specified number of characters
/// from the given C array of UTF-16 code units.
public init(
utf16CodeUnitsNoCopy: UnsafePointer<unichar>,
count: Int,
freeWhenDone flag: Bool
) {
self = String._unconditionallyBridgeFromObjectiveC(NSString(
charactersNoCopy: UnsafeMutablePointer(mutating: utf16CodeUnitsNoCopy),
length: count,
freeWhenDone: flag))
}
//===--- Initializers that can fail -------------------------------------===//
// - (instancetype)
// initWithContentsOfFile:(NSString *)path
// encoding:(NSStringEncoding)enc
// error:(NSError **)error
//
/// Produces a string created by reading data from the file at a
/// given path interpreted using a given encoding.
public init(
contentsOfFile path: String,
encoding enc: Encoding
) throws {
let ns = try NSString(contentsOfFile: path, encoding: enc.rawValue)
self = String._unconditionallyBridgeFromObjectiveC(ns)
}
// - (instancetype)
// initWithContentsOfFile:(NSString *)path
// usedEncoding:(NSStringEncoding *)enc
// error:(NSError **)error
/// Produces a string created by reading data from the file at
/// a given path and returns by reference the encoding used to
/// interpret the file.
public init(
contentsOfFile path: String,
usedEncoding: inout Encoding
) throws {
var enc: UInt = 0
let ns = try NSString(contentsOfFile: path, usedEncoding: &enc)
usedEncoding = Encoding(rawValue: enc)
self = String._unconditionallyBridgeFromObjectiveC(ns)
}
public init(
contentsOfFile path: String
) throws {
let ns = try NSString(contentsOfFile: path, usedEncoding: nil)
self = String._unconditionallyBridgeFromObjectiveC(ns)
}
// - (instancetype)
// initWithContentsOfURL:(NSURL *)url
// encoding:(NSStringEncoding)enc
// error:(NSError**)error
/// Produces a string created by reading data from a given URL
/// interpreted using a given encoding. Errors are written into the
/// inout `error` argument.
public init(
contentsOf url: URL,
encoding enc: Encoding
) throws {
let ns = try NSString(contentsOf: url, encoding: enc.rawValue)
self = String._unconditionallyBridgeFromObjectiveC(ns)
}
// - (instancetype)
// initWithContentsOfURL:(NSURL *)url
// usedEncoding:(NSStringEncoding *)enc
// error:(NSError **)error
/// Produces a string created by reading data from a given URL
/// and returns by reference the encoding used to interpret the
/// data. Errors are written into the inout `error` argument.
public init(
contentsOf url: URL,
usedEncoding: inout Encoding
) throws {
var enc: UInt = 0
let ns = try NSString(contentsOf: url as URL, usedEncoding: &enc)
usedEncoding = Encoding(rawValue: enc)
self = String._unconditionallyBridgeFromObjectiveC(ns)
}
public init(
contentsOf url: URL
) throws {
let ns = try NSString(contentsOf: url, usedEncoding: nil)
self = String._unconditionallyBridgeFromObjectiveC(ns)
}
// - (instancetype)
// initWithCString:(const char *)nullTerminatedCString
// encoding:(NSStringEncoding)encoding
/// Produces a string containing the bytes in a given C array,
/// interpreted according to a given encoding.
public init?(
cString: UnsafePointer<CChar>,
encoding enc: Encoding
) {
if let ns = NSString(cString: cString, encoding: enc.rawValue) {
self = String._unconditionallyBridgeFromObjectiveC(ns)
} else {
return nil
}
}
// FIXME: handle optional locale with default arguments
// - (instancetype)
// initWithData:(NSData *)data
// encoding:(NSStringEncoding)encoding
/// Returns a `String` initialized by converting given `data` into
/// Unicode characters using a given `encoding`.
public init?(data: Data, encoding: Encoding) {
guard let s = NSString(data: data, encoding: encoding.rawValue) else { return nil }
self = String._unconditionallyBridgeFromObjectiveC(s)
}
// - (instancetype)initWithFormat:(NSString *)format, ...
/// Returns a `String` object initialized by using a given
/// format string as a template into which the remaining argument
/// values are substituted.
public init(format: String, _ arguments: CVarArg...) {
self = String(format: format, arguments: arguments)
}
// - (instancetype)
// initWithFormat:(NSString *)format
// arguments:(va_list)argList
/// Returns a `String` object initialized by using a given
/// format string as a template into which the remaining argument
/// values are substituted according to the user's default locale.
public init(format: String, arguments: [CVarArg]) {
self = String(format: format, locale: nil, arguments: arguments)
}
// - (instancetype)initWithFormat:(NSString *)format locale:(id)locale, ...
/// Returns a `String` object initialized by using a given
/// format string as a template into which the remaining argument
/// values are substituted according to given locale information.
public init(format: String, locale: Locale?, _ args: CVarArg...) {
self = String(format: format, locale: locale, arguments: args)
}
// - (instancetype)
// initWithFormat:(NSString *)format
// locale:(id)locale
// arguments:(va_list)argList
/// Returns a `String` object initialized by using a given
/// format string as a template into which the remaining argument
/// values are substituted according to given locale information.
public init(format: String, locale: Locale?, arguments: [CVarArg]) {
#if DEPLOYMENT_RUNTIME_SWIFT
self = withVaList(arguments) {
String._unconditionallyBridgeFromObjectiveC(
NSString(format: format, locale: locale?._bridgeToObjectiveC(), arguments: $0)
)
}
#else
self = withVaList(arguments) {
NSString(format: format, locale: locale, arguments: $0) as String
}
#endif
}
}
extension StringProtocol where Index == String.Index {
//===--- Bridging Helpers -----------------------------------------------===//
//===--------------------------------------------------------------------===//
/// The corresponding `NSString` - a convenience for bridging code.
// FIXME(strings): There is probably a better way to bridge Self to NSString
var _ns: NSString {
return self._ephemeralString._bridgeToObjectiveC()
}
// self can be a Substring so we need to subtract/add this offset when
// passing _ns to the Foundation APIs. Will be 0 if self is String.
@inlinable
internal var _substringOffset: Int {
return self.startIndex.encodedOffset
}
/// Return an `Index` corresponding to the given offset in our UTF-16
/// representation.
func _index(_ utf16Index: Int) -> Index {
return Index(encodedOffset: utf16Index + _substringOffset)
}
@inlinable
internal func _toRelativeNSRange(_ r: Range<String.Index>) -> NSRange {
return NSRange(
location: r.lowerBound.encodedOffset - _substringOffset,
length: r.upperBound.encodedOffset - r.lowerBound.encodedOffset)
}
/// Return a `Range<Index>` corresponding to the given `NSRange` of
/// our UTF-16 representation.
func _range(_ r: NSRange) -> Range<Index> {
return _index(r.location)..<_index(r.location + r.length)
}
/// Return a `Range<Index>?` corresponding to the given `NSRange` of
/// our UTF-16 representation.
func _optionalRange(_ r: NSRange) -> Range<Index>? {
if r.location == NSNotFound {
return nil
}
return _range(r)
}
/// Invoke `body` on an `Int` buffer. If `index` was converted from
/// non-`nil`, convert the buffer to an `Index` and write it into the
/// memory referred to by `index`
func _withOptionalOutParameter<Result>(
_ index: UnsafeMutablePointer<Index>?,
_ body: (UnsafeMutablePointer<Int>?) -> Result
) -> Result {
var utf16Index: Int = 0
let result = (index != nil ? body(&utf16Index) : body(nil))
index?.pointee = _index(utf16Index)
return result
}
/// Invoke `body` on an `NSRange` buffer. If `range` was converted
/// from non-`nil`, convert the buffer to a `Range<Index>` and write
/// it into the memory referred to by `range`
func _withOptionalOutParameter<Result>(
_ range: UnsafeMutablePointer<Range<Index>>?,
_ body: (UnsafeMutablePointer<NSRange>?) -> Result
) -> Result {
var nsRange = NSRange(location: 0, length: 0)
let result = (range != nil ? body(&nsRange) : body(nil))
range?.pointee = self._range(nsRange)
return result
}
//===--- Instance Methods/Properties-------------------------------------===//
//===--------------------------------------------------------------------===//
//===--- Omitted by agreement during API review 5/20/2014 ---------------===//
// @property BOOL boolValue;
// - (BOOL)canBeConvertedToEncoding:(NSStringEncoding)encoding
/// Returns a Boolean value that indicates whether the string can be
/// converted to the specified encoding without loss of information.
///
/// - Parameter encoding: A string encoding.
/// - Returns: `true` if the string can be encoded in `encoding` without loss
/// of information; otherwise, `false`.
public func canBeConverted(to encoding: String.Encoding) -> Bool {
return _ns.canBeConverted(to: encoding.rawValue)
}
// @property NSString* capitalizedString
/// A copy of the string with each word changed to its corresponding
/// capitalized spelling.
///
/// This property performs the canonical (non-localized) mapping. It is
/// suitable for programming operations that require stable results not
/// depending on the current locale.
///
/// A capitalized string is a string with the first character in each word
/// changed to its corresponding uppercase value, and all remaining
/// characters set to their corresponding lowercase values. A "word" is any
/// sequence of characters delimited by spaces, tabs, or line terminators.
/// Some common word delimiting punctuation isn't considered, so this
/// property may not generally produce the desired results for multiword
/// strings. See the `getLineStart(_:end:contentsEnd:for:)` method for
/// additional information.
///
/// Case transformations aren’t guaranteed to be symmetrical or to produce
/// strings of the same lengths as the originals.
public var capitalized: String {
return _ns.capitalized as String
}
// @property (readonly, copy) NSString *localizedCapitalizedString NS_AVAILABLE(10_11, 9_0);
/// A capitalized representation of the string that is produced
/// using the current locale.
@available(macOS 10.11, iOS 9.0, *)
public var localizedCapitalized: String {
return _ns.localizedCapitalized
}
// - (NSString *)capitalizedStringWithLocale:(Locale *)locale
/// Returns a capitalized representation of the string
/// using the specified locale.
public func capitalized(with locale: Locale?) -> String {
return _ns.capitalized(with: locale) as String
}
// - (NSComparisonResult)caseInsensitiveCompare:(NSString *)aString
/// Returns the result of invoking `compare:options:` with
/// `NSCaseInsensitiveSearch` as the only option.
public func caseInsensitiveCompare<
T : StringProtocol
>(_ aString: T) -> ComparisonResult {
return _ns.caseInsensitiveCompare(aString._ephemeralString)
}
//===--- Omitted by agreement during API review 5/20/2014 ---------------===//
// - (unichar)characterAtIndex:(NSUInteger)index
//
// We have a different meaning for "Character" in Swift, and we are
// trying not to expose error-prone UTF-16 integer indexes
// - (NSString *)
// commonPrefixWithString:(NSString *)aString
// options:(StringCompareOptions)mask
/// Returns a string containing characters this string and the
/// given string have in common, starting from the beginning of each
/// up to the first characters that aren't equivalent.
public func commonPrefix<
T : StringProtocol
>(with aString: T, options: String.CompareOptions = []) -> String {
return _ns.commonPrefix(with: aString._ephemeralString, options: options)
}
// - (NSComparisonResult)
// compare:(NSString *)aString
//
// - (NSComparisonResult)
// compare:(NSString *)aString options:(StringCompareOptions)mask
//
// - (NSComparisonResult)
// compare:(NSString *)aString options:(StringCompareOptions)mask
// range:(NSRange)range
//
// - (NSComparisonResult)
// compare:(NSString *)aString options:(StringCompareOptions)mask
// range:(NSRange)range locale:(id)locale
/// Compares the string using the specified options and
/// returns the lexical ordering for the range.
public func compare<T : StringProtocol>(
_ aString: T,
options mask: String.CompareOptions = [],
range: Range<Index>? = nil,
locale: Locale? = nil
) -> ComparisonResult {
// According to Ali Ozer, there may be some real advantage to
// dispatching to the minimal selector for the supplied options.
// So let's do that; the switch should compile away anyhow.
let aString = aString._ephemeralString
return locale != nil ? _ns.compare(
aString,
options: mask,
range: _toRelativeNSRange(
range ?? startIndex..<endIndex
),
locale: locale?._bridgeToObjectiveC()
)
: range != nil ? _ns.compare(
aString,
options: mask,
range: _toRelativeNSRange(range!)
)
: !mask.isEmpty ? _ns.compare(aString, options: mask)
: _ns.compare(aString)
}
// - (NSUInteger)
// completePathIntoString:(NSString **)outputName
// caseSensitive:(BOOL)flag
// matchesIntoArray:(NSArray **)outputArray
// filterTypes:(NSArray *)filterTypes
/// Interprets the string as a path in the file system and
/// attempts to perform filename completion, returning a numeric
/// value that indicates whether a match was possible, and by
/// reference the longest path that matches the string.
///
/// - Returns: The actual number of matching paths.
public func completePath(
into outputName: UnsafeMutablePointer<String>? = nil,
caseSensitive: Bool,
matchesInto outputArray: UnsafeMutablePointer<[String]>? = nil,
filterTypes: [String]? = nil
) -> Int {
#if DEPLOYMENT_RUNTIME_SWIFT
var outputNamePlaceholder: String?
var outputArrayPlaceholder = [String]()
let res = self._ns.completePath(
into: &outputNamePlaceholder,
caseSensitive: caseSensitive,
matchesInto: &outputArrayPlaceholder,
filterTypes: filterTypes
)
if let n = outputNamePlaceholder {
outputName?.pointee = n
} else {
outputName?.pointee = ""
}
outputArray?.pointee = outputArrayPlaceholder
return res
#else // DEPLOYMENT_RUNTIME_SWIFT
var nsMatches: NSArray?
var nsOutputName: NSString?
let result: Int = outputName._withNilOrAddress(of: &nsOutputName) {
outputName in outputArray._withNilOrAddress(of: &nsMatches) {
outputArray in
// FIXME: completePath(...) is incorrectly annotated as requiring
// non-optional output parameters. rdar://problem/25494184
let outputNonOptionalName = unsafeBitCast(
outputName, to: AutoreleasingUnsafeMutablePointer<NSString?>.self)
let outputNonOptionalArray = unsafeBitCast(
outputArray, to: AutoreleasingUnsafeMutablePointer<NSArray?>.self)
return self._ns.completePath(
into: outputNonOptionalName,
caseSensitive: caseSensitive,
matchesInto: outputNonOptionalArray,
filterTypes: filterTypes
)
}
}
if let matches = nsMatches {
// Since this function is effectively a bridge thunk, use the
// bridge thunk semantics for the NSArray conversion
outputArray?.pointee = matches as! [String]
}
if let n = nsOutputName {
outputName?.pointee = n as String
}
return result
#endif // DEPLOYMENT_RUNTIME_SWIFT
}
// - (NSArray *)
// componentsSeparatedByCharactersInSet:(NSCharacterSet *)separator
/// Returns an array containing substrings from the string
/// that have been divided by characters in the given set.
public func components(separatedBy separator: CharacterSet) -> [String] {
return _ns.components(separatedBy: separator)
}
// - (NSArray *)componentsSeparatedByString:(NSString *)separator
/// Returns an array containing substrings from the string that have been
/// divided by the given separator.
///
/// The substrings in the resulting array appear in the same order as the
/// original string. Adjacent occurrences of the separator string produce
/// empty strings in the result. Similarly, if the string begins or ends
/// with the separator, the first or last substring, respectively, is empty.
/// The following example shows this behavior:
///
/// let list1 = "Karin, Carrie, David"
/// let items1 = list1.components(separatedBy: ", ")
/// // ["Karin", "Carrie", "David"]
///
/// // Beginning with the separator:
/// let list2 = ", Norman, Stanley, Fletcher"
/// let items2 = list2.components(separatedBy: ", ")
/// // ["", "Norman", "Stanley", "Fletcher"
///
/// If the list has no separators, the array contains only the original
/// string itself.
///
/// let name = "Karin"
/// let list = name.components(separatedBy: ", ")
/// // ["Karin"]
///
/// - Parameter separator: The separator string.
/// - Returns: An array containing substrings that have been divided from the
/// string using `separator`.
// FIXME(strings): now when String conforms to Collection, this can be
// replaced by split(separator:maxSplits:omittingEmptySubsequences:)
public func components<
T : StringProtocol
>(separatedBy separator: T) -> [String] {
return _ns.components(separatedBy: separator._ephemeralString)
}
// - (const char *)cStringUsingEncoding:(NSStringEncoding)encoding
/// Returns a representation of the string as a C string
/// using a given encoding.
public func cString(using encoding: String.Encoding) -> [CChar]? {
return withExtendedLifetime(_ns) {
(s: NSString) -> [CChar]? in
_persistCString(s.cString(using: encoding.rawValue))
}
}
// - (NSData *)dataUsingEncoding:(NSStringEncoding)encoding
//
// - (NSData *)
// dataUsingEncoding:(NSStringEncoding)encoding
// allowLossyConversion:(BOOL)flag
/// Returns a `Data` containing a representation of
/// the `String` encoded using a given encoding.
public func data(
using encoding: String.Encoding,
allowLossyConversion: Bool = false
) -> Data? {
return _ns.data(
using: encoding.rawValue,
allowLossyConversion: allowLossyConversion)
}
// @property NSString* decomposedStringWithCanonicalMapping;
/// A string created by normalizing the string's contents using Form D.
public var decomposedStringWithCanonicalMapping: String {
return _ns.decomposedStringWithCanonicalMapping
}
// @property NSString* decomposedStringWithCompatibilityMapping;
/// A string created by normalizing the string's contents using Form KD.
public var decomposedStringWithCompatibilityMapping: String {
return _ns.decomposedStringWithCompatibilityMapping
}
//===--- Importing Foundation should not affect String printing ---------===//
// Therefore, we're not exposing this:
//
// @property NSString* description
//===--- Omitted for consistency with API review results 5/20/2014 -----===//
// @property double doubleValue;
// - (void)
// enumerateLinesUsing:(void (^)(NSString *line, BOOL *stop))block
/// Enumerates all the lines in a string.
public func enumerateLines(
invoking body: @escaping (_ line: String, _ stop: inout Bool) -> Void
) {
_ns.enumerateLines {
(line: String, stop: UnsafeMutablePointer<ObjCBool>)
in
var stop_ = false
body(line, &stop_)
if stop_ {
stop.pointee = true
}
}
}
// @property NSStringEncoding fastestEncoding;
/// The fastest encoding to which the string can be converted without loss
/// of information.
public var fastestEncoding: String.Encoding {
return String.Encoding(rawValue: _ns.fastestEncoding)
}
// - (BOOL)
// getCString:(char *)buffer
// maxLength:(NSUInteger)maxBufferCount
// encoding:(NSStringEncoding)encoding
/// Converts the `String`'s content to a given encoding and
/// stores them in a buffer.
/// - Note: will store a maximum of `min(buffer.count, maxLength)` bytes.
public func getCString(
_ buffer: inout [CChar], maxLength: Int, encoding: String.Encoding
) -> Bool {
return _ns.getCString(&buffer,
maxLength: Swift.min(buffer.count, maxLength),
encoding: encoding.rawValue)
}
// - (NSUInteger)hash
/// An unsigned integer that can be used as a hash table address.
public var hash: Int {
return _ns.hash
}
// - (NSUInteger)lengthOfBytesUsingEncoding:(NSStringEncoding)enc
/// Returns the number of bytes required to store the
/// `String` in a given encoding.
public func lengthOfBytes(using encoding: String.Encoding) -> Int {
return _ns.lengthOfBytes(using: encoding.rawValue)
}
// - (NSComparisonResult)localizedCaseInsensitiveCompare:(NSString *)aString
/// Compares the string and the given string using a case-insensitive,
/// localized, comparison.
public
func localizedCaseInsensitiveCompare<
T : StringProtocol
>(_ aString: T) -> ComparisonResult {
return _ns.localizedCaseInsensitiveCompare(aString._ephemeralString)
}
// - (NSComparisonResult)localizedCompare:(NSString *)aString
/// Compares the string and the given string using a localized comparison.
public func localizedCompare<
T : StringProtocol
>(_ aString: T) -> ComparisonResult {
return _ns.localizedCompare(aString._ephemeralString)
}
/// Compares the string and the given string as sorted by the Finder.
public func localizedStandardCompare<
T : StringProtocol
>(_ string: T) -> ComparisonResult {
return _ns.localizedStandardCompare(string._ephemeralString)
}
//===--- Omitted for consistency with API review results 5/20/2014 ------===//
// @property long long longLongValue
// @property (readonly, copy) NSString *localizedLowercase NS_AVAILABLE(10_11, 9_0);
/// A lowercase version of the string that is produced using the current
/// locale.
@available(macOS 10.11, iOS 9.0, *)
public var localizedLowercase: String {
return _ns.localizedLowercase
}
// - (NSString *)lowercaseStringWithLocale:(Locale *)locale
/// Returns a version of the string with all letters
/// converted to lowercase, taking into account the specified
/// locale.
public func lowercased(with locale: Locale?) -> String {
return _ns.lowercased(with: locale)
}
// - (NSUInteger)maximumLengthOfBytesUsingEncoding:(NSStringEncoding)enc
/// Returns the maximum number of bytes needed to store the
/// `String` in a given encoding.
public
func maximumLengthOfBytes(using encoding: String.Encoding) -> Int {
return _ns.maximumLengthOfBytes(using: encoding.rawValue)
}
// @property NSString* precomposedStringWithCanonicalMapping;
/// A string created by normalizing the string's contents using Form C.
public var precomposedStringWithCanonicalMapping: String {
return _ns.precomposedStringWithCanonicalMapping
}
// @property NSString * precomposedStringWithCompatibilityMapping;
/// A string created by normalizing the string's contents using Form KC.
public var precomposedStringWithCompatibilityMapping: String {
return _ns.precomposedStringWithCompatibilityMapping
}
#if !DEPLOYMENT_RUNTIME_SWIFT
// - (id)propertyList
/// Parses the `String` as a text representation of a
/// property list, returning an NSString, NSData, NSArray, or
/// NSDictionary object, according to the topmost element.
public func propertyList() -> Any {
return _ns.propertyList()
}
// - (NSDictionary *)propertyListFromStringsFileFormat
/// Returns a dictionary object initialized with the keys and
/// values found in the `String`.
public func propertyListFromStringsFileFormat() -> [String : String] {
return _ns.propertyListFromStringsFileFormat() as! [String : String]? ?? [:]
}
#endif
// - (BOOL)localizedStandardContainsString:(NSString *)str NS_AVAILABLE(10_11, 9_0);
/// Returns a Boolean value indicating whether the string contains the given
/// string, taking the current locale into account.
///
/// This is the most appropriate method for doing user-level string searches,
/// similar to how searches are done generally in the system. The search is
/// locale-aware, case and diacritic insensitive. The exact list of search
/// options applied may change over time.
@available(macOS 10.11, iOS 9.0, *)
public func localizedStandardContains<
T : StringProtocol
>(_ string: T) -> Bool {
return _ns.localizedStandardContains(string._ephemeralString)
}
// @property NSStringEncoding smallestEncoding;
/// The smallest encoding to which the string can be converted without
/// loss of information.
public var smallestEncoding: String.Encoding {
return String.Encoding(rawValue: _ns.smallestEncoding)
}
// - (NSString *)
// stringByAddingPercentEncodingWithAllowedCharacters:
// (NSCharacterSet *)allowedCharacters
/// Returns a new string created by replacing all characters in the string
/// not in the specified set with percent encoded characters.
public func addingPercentEncoding(
withAllowedCharacters allowedCharacters: CharacterSet
) -> String? {
// FIXME: the documentation states that this method can return nil if the
// transformation is not possible, without going into further details. The
// implementation can only return nil if malloc() returns nil, so in
// practice this is not possible. Still, to be consistent with
// documentation, we declare the method as returning an optional String.
//
// <rdar://problem/17901698> Docs for -[NSString
// stringByAddingPercentEncodingWithAllowedCharacters] don't precisely
// describe when return value is nil
return _ns.addingPercentEncoding(withAllowedCharacters:
allowedCharacters
)
}
// - (NSString *)stringByAppendingFormat:(NSString *)format, ...
/// Returns a string created by appending a string constructed from a given
/// format string and the following arguments.
public func appendingFormat<
T : StringProtocol
>(
_ format: T, _ arguments: CVarArg...
) -> String {
return _ns.appending(
String(format: format._ephemeralString, arguments: arguments))
}
// - (NSString *)stringByAppendingString:(NSString *)aString
/// Returns a new string created by appending the given string.
// FIXME(strings): shouldn't it be deprecated in favor of `+`?
public func appending<
T : StringProtocol
>(_ aString: T) -> String {
return _ns.appending(aString._ephemeralString)
}
/// Returns a string with the given character folding options
/// applied.
public func folding(
options: String.CompareOptions = [], locale: Locale?
) -> String {
return _ns.folding(options: options, locale: locale)
}
// - (NSString *)stringByPaddingToLength:(NSUInteger)newLength
// withString:(NSString *)padString
// startingAtIndex:(NSUInteger)padIndex
/// Returns a new string formed from the `String` by either
/// removing characters from the end, or by appending as many
/// occurrences as necessary of a given pad string.
public func padding<
T : StringProtocol
>(
toLength newLength: Int,
withPad padString: T,
startingAt padIndex: Int
) -> String {
return _ns.padding(
toLength: newLength,
withPad: padString._ephemeralString,
startingAt: padIndex)
}
// @property NSString* stringByRemovingPercentEncoding;
/// A new string made from the string by replacing all percent encoded
/// sequences with the matching UTF-8 characters.
public var removingPercentEncoding: String? {
return _ns.removingPercentEncoding
}
// - (NSString *)
// stringByReplacingCharactersInRange:(NSRange)range
// withString:(NSString *)replacement
/// Returns a new string in which the characters in a
/// specified range of the `String` are replaced by a given string.
public func replacingCharacters<
T : StringProtocol, R : RangeExpression
>(in range: R, with replacement: T) -> String where R.Bound == Index {
return _ns.replacingCharacters(
in: _toRelativeNSRange(range.relative(to: self)),
with: replacement._ephemeralString)
}
// - (NSString *)
// stringByReplacingOccurrencesOfString:(NSString *)target
// withString:(NSString *)replacement
//
// - (NSString *)
// stringByReplacingOccurrencesOfString:(NSString *)target
// withString:(NSString *)replacement
// options:(StringCompareOptions)options
// range:(NSRange)searchRange
/// Returns a new string in which all occurrences of a target
/// string in a specified range of the string are replaced by
/// another given string.
public func replacingOccurrences<
Target : StringProtocol,
Replacement : StringProtocol
>(
of target: Target,
with replacement: Replacement,
options: String.CompareOptions = [],
range searchRange: Range<Index>? = nil
) -> String {
let target = target._ephemeralString
let replacement = replacement._ephemeralString
return (searchRange != nil) || (!options.isEmpty)
? _ns.replacingOccurrences(
of: target,
with: replacement,
options: options,
range: _toRelativeNSRange(
searchRange ?? startIndex..<endIndex
)
)
: _ns.replacingOccurrences(of: target, with: replacement)
}
#if !DEPLOYMENT_RUNTIME_SWIFT
// - (NSString *)
// stringByReplacingPercentEscapesUsingEncoding:(NSStringEncoding)encoding
/// Returns a new string made by replacing in the `String`
/// all percent escapes with the matching characters as determined
/// by a given encoding.
@available(swift, deprecated: 3.0, obsoleted: 4.0,
message: "Use removingPercentEncoding instead, which always uses the recommended UTF-8 encoding.")
public func replacingPercentEscapes(
using encoding: String.Encoding
) -> String? {
return _ns.replacingPercentEscapes(using: encoding.rawValue)
}
#endif
// - (NSString *)stringByTrimmingCharactersInSet:(NSCharacterSet *)set
/// Returns a new string made by removing from both ends of
/// the `String` characters contained in a given character set.
public func trimmingCharacters(in set: CharacterSet) -> String {
return _ns.trimmingCharacters(in: set)
}
// @property (readonly, copy) NSString *localizedUppercaseString NS_AVAILABLE(10_11, 9_0);
/// An uppercase version of the string that is produced using the current
/// locale.
@available(macOS 10.11, iOS 9.0, *)
public var localizedUppercase: String {
return _ns.localizedUppercase as String
}
// - (NSString *)uppercaseStringWithLocale:(Locale *)locale
/// Returns a version of the string with all letters
/// converted to uppercase, taking into account the specified
/// locale.
public func uppercased(with locale: Locale?) -> String {
return _ns.uppercased(with: locale)
}
//===--- Omitted due to redundancy with "utf8" property -----------------===//
// - (const char *)UTF8String
// - (BOOL)
// writeToFile:(NSString *)path
// atomically:(BOOL)useAuxiliaryFile
// encoding:(NSStringEncoding)enc
// error:(NSError **)error
/// Writes the contents of the `String` to a file at a given
/// path using a given encoding.
public func write<
T : StringProtocol
>(
toFile path: T, atomically useAuxiliaryFile: Bool,
encoding enc: String.Encoding
) throws {
try _ns.write(
toFile: path._ephemeralString,
atomically: useAuxiliaryFile,
encoding: enc.rawValue)
}
// - (BOOL)
// writeToURL:(NSURL *)url
// atomically:(BOOL)useAuxiliaryFile
// encoding:(NSStringEncoding)enc
// error:(NSError **)error
/// Writes the contents of the `String` to the URL specified
/// by url using the specified encoding.
public func write(
to url: URL, atomically useAuxiliaryFile: Bool,
encoding enc: String.Encoding
) throws {
try _ns.write(
to: url, atomically: useAuxiliaryFile, encoding: enc.rawValue)
}
// - (nullable NSString *)stringByApplyingTransform:(NSString *)transform reverse:(BOOL)reverse NS_AVAILABLE(10_11, 9_0);
#if !DEPLOYMENT_RUNTIME_SWIFT
/// Perform string transliteration.
@available(macOS 10.11, iOS 9.0, *)
public func applyingTransform(
_ transform: StringTransform, reverse: Bool
) -> String? {
return _ns.applyingTransform(transform, reverse: reverse)
}
// - (void)
// enumerateLinguisticTagsInRange:(NSRange)range
// scheme:(NSString *)tagScheme
// options:(LinguisticTaggerOptions)opts
// orthography:(Orthography *)orthography
// usingBlock:(
// void (^)(
// NSString *tag, NSRange tokenRange,
// NSRange sentenceRange, BOOL *stop)
// )block
/// Performs linguistic analysis on the specified string by
/// enumerating the specific range of the string, providing the
/// Block with the located tags.
public func enumerateLinguisticTags<
T : StringProtocol, R : RangeExpression
>(
in range: R,
scheme tagScheme: T,
options opts: NSLinguisticTagger.Options = [],
orthography: NSOrthography? = nil,
invoking body:
(String, Range<Index>, Range<Index>, inout Bool) -> Void
) where R.Bound == Index {
let range = range.relative(to: self)
_ns.enumerateLinguisticTags(
in: _toRelativeNSRange(range),
scheme: tagScheme._ephemeralString,
options: opts,
orthography: orthography != nil ? orthography! : nil
) {
var stop_ = false
body($0, self._range($1), self._range($2), &stop_)
if stop_ {
$3.pointee = true
}
}
}
#endif
// - (void)
// enumerateSubstringsInRange:(NSRange)range
// options:(NSStringEnumerationOptions)opts
// usingBlock:(
// void (^)(
// NSString *substring,
// NSRange substringRange,
// NSRange enclosingRange,
// BOOL *stop)
// )block
/// Enumerates the substrings of the specified type in the specified range of
/// the string.
///
/// Mutation of a string value while enumerating its substrings is not
/// supported. If you need to mutate a string from within `body`, convert
/// your string to an `NSMutableString` instance and then call the
/// `enumerateSubstrings(in:options:using:)` method.
///
/// - Parameters:
/// - range: The range within the string to enumerate substrings.
/// - opts: Options specifying types of substrings and enumeration styles.
/// If `opts` is omitted or empty, `body` is called a single time with
/// the range of the string specified by `range`.
/// - body: The closure executed for each substring in the enumeration. The
/// closure takes four arguments:
/// - The enumerated substring. If `substringNotRequired` is included in
/// `opts`, this parameter is `nil` for every execution of the
/// closure.
/// - The range of the enumerated substring in the string that
/// `enumerate(in:options:_:)` was called on.
/// - The range that includes the substring as well as any separator or
/// filler characters that follow. For instance, for lines,
/// `enclosingRange` contains the line terminators. The enclosing
/// range for the first string enumerated also contains any characters
/// that occur before the string. Consecutive enclosing ranges are
/// guaranteed not to overlap, and every single character in the
/// enumerated range is included in one and only one enclosing range.
/// - An `inout` Boolean value that the closure can use to stop the
/// enumeration by setting `stop = true`.
public func enumerateSubstrings<
R : RangeExpression
>(
in range: R,
options opts: String.EnumerationOptions = [],
_ body: @escaping (
_ substring: String?, _ substringRange: Range<Index>,
_ enclosingRange: Range<Index>, inout Bool
) -> Void
) where R.Bound == Index {
_ns.enumerateSubstrings(
in: _toRelativeNSRange(range.relative(to: self)), options: opts) {
var stop_ = false
body($0,
self._range($1),
self._range($2),
&stop_)
if stop_ {
UnsafeMutablePointer($3).pointee = true
}
}
}
//===--- Omitted for consistency with API review results 5/20/2014 ------===//
// @property float floatValue;
// - (BOOL)
// getBytes:(void *)buffer
// maxLength:(NSUInteger)maxBufferCount
// usedLength:(NSUInteger*)usedBufferCount
// encoding:(NSStringEncoding)encoding
// options:(StringEncodingConversionOptions)options
// range:(NSRange)range
// remainingRange:(NSRangePointer)leftover
/// Writes the given `range` of characters into `buffer` in a given
/// `encoding`, without any allocations. Does not NULL-terminate.
///
/// - Parameter buffer: A buffer into which to store the bytes from
/// the receiver. The returned bytes are not NUL-terminated.
///
/// - Parameter maxBufferCount: The maximum number of bytes to write
/// to buffer.
///
/// - Parameter usedBufferCount: The number of bytes used from
/// buffer. Pass `nil` if you do not need this value.
///
/// - Parameter encoding: The encoding to use for the returned bytes.
///
/// - Parameter options: A mask to specify options to use for
/// converting the receiver's contents to `encoding` (if conversion
/// is necessary).
///
/// - Parameter range: The range of characters in the receiver to get.
///
/// - Parameter leftover: The remaining range. Pass `nil` If you do
/// not need this value.
///
/// - Returns: `true` iff some characters were converted.
///
/// - Note: Conversion stops when the buffer fills or when the
/// conversion isn't possible due to the chosen encoding.
///
/// - Note: will get a maximum of `min(buffer.count, maxLength)` bytes.
public func getBytes<
R : RangeExpression
>(
_ buffer: inout [UInt8],
maxLength maxBufferCount: Int,
usedLength usedBufferCount: UnsafeMutablePointer<Int>,
encoding: String.Encoding,
options: String.EncodingConversionOptions = [],
range: R,
remaining leftover: UnsafeMutablePointer<Range<Index>>
) -> Bool where R.Bound == Index {
return _withOptionalOutParameter(leftover) {
self._ns.getBytes(
&buffer,
maxLength: Swift.min(buffer.count, maxBufferCount),
usedLength: usedBufferCount,
encoding: encoding.rawValue,
options: options,
range: _toRelativeNSRange(range.relative(to: self)),
remaining: $0)
}
}
// - (void)
// getLineStart:(NSUInteger *)startIndex
// end:(NSUInteger *)lineEndIndex
// contentsEnd:(NSUInteger *)contentsEndIndex
// forRange:(NSRange)aRange
/// Returns by reference the beginning of the first line and
/// the end of the last line touched by the given range.
public func getLineStart<
R : RangeExpression
>(
_ start: UnsafeMutablePointer<Index>,
end: UnsafeMutablePointer<Index>,
contentsEnd: UnsafeMutablePointer<Index>,
for range: R
) where R.Bound == Index {
_withOptionalOutParameter(start) {
start in self._withOptionalOutParameter(end) {
end in self._withOptionalOutParameter(contentsEnd) {
contentsEnd in self._ns.getLineStart(
start, end: end,
contentsEnd: contentsEnd,
for: _toRelativeNSRange(range.relative(to: self)))
}
}
}
}
// - (void)
// getParagraphStart:(NSUInteger *)startIndex
// end:(NSUInteger *)endIndex
// contentsEnd:(NSUInteger *)contentsEndIndex
// forRange:(NSRange)aRange
/// Returns by reference the beginning of the first paragraph
/// and the end of the last paragraph touched by the given range.
public func getParagraphStart<
R : RangeExpression
>(
_ start: UnsafeMutablePointer<Index>,
end: UnsafeMutablePointer<Index>,
contentsEnd: UnsafeMutablePointer<Index>,
for range: R
) where R.Bound == Index {
_withOptionalOutParameter(start) {
start in self._withOptionalOutParameter(end) {
end in self._withOptionalOutParameter(contentsEnd) {
contentsEnd in self._ns.getParagraphStart(
start, end: end,
contentsEnd: contentsEnd,
for: _toRelativeNSRange(range.relative(to: self)))
}
}
}
}
//===--- Already provided by core Swift ---------------------------------===//
// - (instancetype)initWithString:(NSString *)aString
//===--- Initializers that can fail dropped for factory functions -------===//
// - (instancetype)initWithUTF8String:(const char *)bytes
//===--- Omitted for consistency with API review results 5/20/2014 ------===//
// @property NSInteger integerValue;
// @property Int intValue;
//===--- Omitted by apparent agreement during API review 5/20/2014 ------===//
// @property BOOL absolutePath;
// - (BOOL)isEqualToString:(NSString *)aString
// - (NSRange)lineRangeForRange:(NSRange)aRange
/// Returns the range of characters representing the line or lines
/// containing a given range.
public func lineRange<
R : RangeExpression
>(for aRange: R) -> Range<Index> where R.Bound == Index {
return _range(_ns.lineRange(
for: _toRelativeNSRange(aRange.relative(to: self))))
}
#if !DEPLOYMENT_RUNTIME_SWIFT
// - (NSArray *)
// linguisticTagsInRange:(NSRange)range
// scheme:(NSString *)tagScheme
// options:(LinguisticTaggerOptions)opts
// orthography:(Orthography *)orthography
// tokenRanges:(NSArray**)tokenRanges
/// Returns an array of linguistic tags for the specified
/// range and requested tags within the receiving string.
public func linguisticTags<
T : StringProtocol, R : RangeExpression
>(
in range: R,
scheme tagScheme: T,
options opts: NSLinguisticTagger.Options = [],
orthography: NSOrthography? = nil,
tokenRanges: UnsafeMutablePointer<[Range<Index>]>? = nil // FIXME:Can this be nil?
) -> [String] where R.Bound == Index {
var nsTokenRanges: NSArray?
let result = tokenRanges._withNilOrAddress(of: &nsTokenRanges) {
self._ns.linguisticTags(
in: _toRelativeNSRange(range.relative(to: self)),
scheme: tagScheme._ephemeralString,
options: opts,
orthography: orthography,
tokenRanges: $0) as NSArray
}
if let nsTokenRanges = nsTokenRanges {
tokenRanges?.pointee = (nsTokenRanges as [AnyObject]).map {
self._range($0.rangeValue)
}
}
return result as! [String]
}
// - (NSRange)paragraphRangeForRange:(NSRange)aRange
/// Returns the range of characters representing the
/// paragraph or paragraphs containing a given range.
public func paragraphRange<
R : RangeExpression
>(for aRange: R) -> Range<Index> where R.Bound == Index {
return _range(
_ns.paragraphRange(for: _toRelativeNSRange(aRange.relative(to: self))))
}
#endif
// - (NSRange)rangeOfCharacterFromSet:(NSCharacterSet *)aSet
//
// - (NSRange)
// rangeOfCharacterFromSet:(NSCharacterSet *)aSet
// options:(StringCompareOptions)mask
//
// - (NSRange)
// rangeOfCharacterFromSet:(NSCharacterSet *)aSet
// options:(StringCompareOptions)mask
// range:(NSRange)aRange
/// Finds and returns the range in the `String` of the first
/// character from a given character set found in a given range with
/// given options.
public func rangeOfCharacter(
from aSet: CharacterSet,
options mask: String.CompareOptions = [],
range aRange: Range<Index>? = nil
) -> Range<Index>? {
return _optionalRange(
_ns.rangeOfCharacter(
from: aSet,
options: mask,
range: _toRelativeNSRange(
aRange ?? startIndex..<endIndex
)
)
)
}
// - (NSRange)rangeOfComposedCharacterSequenceAtIndex:(NSUInteger)anIndex
/// Returns the range in the `String` of the composed
/// character sequence located at a given index.
public
func rangeOfComposedCharacterSequence(at anIndex: Index) -> Range<Index> {
return _range(
_ns.rangeOfComposedCharacterSequence(at: anIndex.encodedOffset))
}
// - (NSRange)rangeOfComposedCharacterSequencesForRange:(NSRange)range
/// Returns the range in the string of the composed character
/// sequences for a given range.
public func rangeOfComposedCharacterSequences<
R : RangeExpression
>(
for range: R
) -> Range<Index> where R.Bound == Index {
// Theoretically, this will be the identity function. In practice
// I think users will be able to observe differences in the input
// and output ranges due (if nothing else) to locale changes
return _range(
_ns.rangeOfComposedCharacterSequences(
for: _toRelativeNSRange(range.relative(to: self))))
}
// - (NSRange)rangeOfString:(NSString *)aString
//
// - (NSRange)
// rangeOfString:(NSString *)aString options:(StringCompareOptions)mask
//
// - (NSRange)
// rangeOfString:(NSString *)aString
// options:(StringCompareOptions)mask
// range:(NSRange)aRange
//
// - (NSRange)
// rangeOfString:(NSString *)aString
// options:(StringCompareOptions)mask
// range:(NSRange)searchRange
// locale:(Locale *)locale
/// Finds and returns the range of the first occurrence of a
/// given string within a given range of the `String`, subject to
/// given options, using the specified locale, if any.
public func range<
T : StringProtocol
>(
of aString: T,
options mask: String.CompareOptions = [],
range searchRange: Range<Index>? = nil,
locale: Locale? = nil
) -> Range<Index>? {
let aString = aString._ephemeralString
return _optionalRange(
locale != nil ? _ns.range(
of: aString,
options: mask,
range: _toRelativeNSRange(
searchRange ?? startIndex..<endIndex
),
locale: locale
)
: searchRange != nil ? _ns.range(
of: aString, options: mask, range: _toRelativeNSRange(searchRange!)
)
: !mask.isEmpty ? _ns.range(of: aString, options: mask)
: _ns.range(of: aString)
)
}
// - (NSRange)localizedStandardRangeOfString:(NSString *)str NS_AVAILABLE(10_11, 9_0);
/// Finds and returns the range of the first occurrence of a given string,
/// taking the current locale into account. Returns `nil` if the string was
/// not found.
///
/// This is the most appropriate method for doing user-level string searches,
/// similar to how searches are done generally in the system. The search is
/// locale-aware, case and diacritic insensitive. The exact list of search
/// options applied may change over time.
@available(macOS 10.11, iOS 9.0, *)
public func localizedStandardRange<
T : StringProtocol
>(of string: T) -> Range<Index>? {
return _optionalRange(
_ns.localizedStandardRange(of: string._ephemeralString))
}
#if !DEPLOYMENT_RUNTIME_SWIFT
// - (NSString *)
// stringByAddingPercentEscapesUsingEncoding:(NSStringEncoding)encoding
/// Returns a representation of the `String` using a given
/// encoding to determine the percent escapes necessary to convert
/// the `String` into a legal URL string.
@available(swift, deprecated: 3.0, obsoleted: 4.0,
message: "Use addingPercentEncoding(withAllowedCharacters:) instead, which always uses the recommended UTF-8 encoding, and which encodes for a specific URL component or subcomponent since each URL component or subcomponent has different rules for what characters are valid.")
public func addingPercentEscapes(
using encoding: String.Encoding
) -> String? {
return _ns.addingPercentEscapes(using: encoding.rawValue)
}
#endif
//===--- From the 10.10 release notes; not in public documentation ------===//
// No need to make these unavailable on earlier OSes, since they can
// forward trivially to rangeOfString.
/// Returns `true` iff `other` is non-empty and contained within
/// `self` by case-sensitive, non-literal search.
///
/// Equivalent to `self.rangeOfString(other) != nil`
public func contains<T : StringProtocol>(_ other: T) -> Bool {
let r = self.range(of: other) != nil
if #available(macOS 10.10, iOS 8.0, *) {
assert(r == _ns.contains(other._ephemeralString))
}
return r
}
/// Returns a Boolean value indicating whether the given string is non-empty
/// and contained within this string by case-insensitive, non-literal
/// search, taking into account the current locale.
///
/// Locale-independent case-insensitive operation, and other needs, can be
/// achieved by calling `range(of:options:range:locale:)`.
///
/// Equivalent to:
///
/// range(of: other, options: .caseInsensitiveSearch,
/// locale: Locale.current) != nil
public func localizedCaseInsensitiveContains<
T : StringProtocol
>(_ other: T) -> Bool {
let r = self.range(
of: other, options: .caseInsensitive, locale: Locale.current
) != nil
if #available(macOS 10.10, iOS 8.0, *) {
assert(r ==
_ns.localizedCaseInsensitiveContains(other._ephemeralString))
}
return r
}
}
// Deprecated slicing
extension StringProtocol where Index == String.Index {
// - (NSString *)substringFromIndex:(NSUInteger)anIndex
/// Returns a new string containing the characters of the
/// `String` from the one at a given index to the end.
@available(swift, deprecated: 4.0,
message: "Please use String slicing subscript with a 'partial range from' operator.")
public func substring(from index: Index) -> String {
return _ns.substring(from: index.encodedOffset)
}
// - (NSString *)substringToIndex:(NSUInteger)anIndex
/// Returns a new string containing the characters of the
/// `String` up to, but not including, the one at a given index.
@available(swift, deprecated: 4.0,
message: "Please use String slicing subscript with a 'partial range upto' operator.")
public func substring(to index: Index) -> String {
return _ns.substring(to: index.encodedOffset)
}
// - (NSString *)substringWithRange:(NSRange)aRange
/// Returns a string object containing the characters of the
/// `String` that lie within a given range.
@available(swift, deprecated: 4.0,
message: "Please use String slicing subscript.")
public func substring(with aRange: Range<Index>) -> String {
return _ns.substring(with: _toRelativeNSRange(aRange))
}
}
extension StringProtocol {
// - (const char *)fileSystemRepresentation
/// Returns a file system-specific representation of the `String`.
@available(*, unavailable, message: "Use getFileSystemRepresentation on URL instead.")
public var fileSystemRepresentation: [CChar] {
fatalError("unavailable function can't be called")
}
// - (BOOL)
// getFileSystemRepresentation:(char *)buffer
// maxLength:(NSUInteger)maxLength
/// Interprets the `String` as a system-independent path and
/// fills a buffer with a C-string in a format and encoding suitable
/// for use with file-system calls.
/// - Note: will store a maximum of `min(buffer.count, maxLength)` bytes.
@available(*, unavailable, message: "Use getFileSystemRepresentation on URL instead.")
public func getFileSystemRepresentation(
_ buffer: inout [CChar], maxLength: Int) -> Bool {
fatalError("unavailable function can't be called")
}
//===--- Kept for consistency with API review results 5/20/2014 ---------===//
// We decided to keep pathWithComponents, so keeping this too
// @property NSString lastPathComponent;
/// Returns the last path component of the `String`.
@available(*, unavailable, message: "Use lastPathComponent on URL instead.")
public var lastPathComponent: String {
fatalError("unavailable function can't be called")
}
//===--- Renamed by agreement during API review 5/20/2014 ---------------===//
// @property NSUInteger length;
/// Returns the number of Unicode characters in the `String`.
@available(*, unavailable,
message: "Take the count of a UTF-16 view instead, i.e. str.utf16.count")
public var utf16Count: Int {
fatalError("unavailable function can't be called")
}
// @property NSArray* pathComponents
/// Returns an array of NSString objects containing, in
/// order, each path component of the `String`.
@available(*, unavailable, message: "Use pathComponents on URL instead.")
public var pathComponents: [String] {
fatalError("unavailable function can't be called")
}
// @property NSString* pathExtension;
/// Interprets the `String` as a path and returns the
/// `String`'s extension, if any.
@available(*, unavailable, message: "Use pathExtension on URL instead.")
public var pathExtension: String {
fatalError("unavailable function can't be called")
}
// @property NSString *stringByAbbreviatingWithTildeInPath;
/// Returns a new string that replaces the current home
/// directory portion of the current path with a tilde (`~`)
/// character.
@available(*, unavailable, message: "Use abbreviatingWithTildeInPath on NSString instead.")
public var abbreviatingWithTildeInPath: String {
fatalError("unavailable function can't be called")
}
// - (NSString *)stringByAppendingPathComponent:(NSString *)aString
/// Returns a new string made by appending to the `String` a given string.
@available(*, unavailable, message: "Use appendingPathComponent on URL instead.")
public func appendingPathComponent(_ aString: String) -> String {
fatalError("unavailable function can't be called")
}
// - (NSString *)stringByAppendingPathExtension:(NSString *)ext
/// Returns a new string made by appending to the `String` an
/// extension separator followed by a given extension.
@available(*, unavailable, message: "Use appendingPathExtension on URL instead.")
public func appendingPathExtension(_ ext: String) -> String? {
fatalError("unavailable function can't be called")
}
// @property NSString* stringByDeletingLastPathComponent;
/// Returns a new string made by deleting the last path
/// component from the `String`, along with any final path
/// separator.
@available(*, unavailable, message: "Use deletingLastPathComponent on URL instead.")
public var deletingLastPathComponent: String {
fatalError("unavailable function can't be called")
}
// @property NSString* stringByDeletingPathExtension;
/// Returns a new string made by deleting the extension (if
/// any, and only the last) from the `String`.
@available(*, unavailable, message: "Use deletingPathExtension on URL instead.")
public var deletingPathExtension: String {
fatalError("unavailable function can't be called")
}
// @property NSString* stringByExpandingTildeInPath;
/// Returns a new string made by expanding the initial
/// component of the `String` to its full path value.
@available(*, unavailable, message: "Use expandingTildeInPath on NSString instead.")
public var expandingTildeInPath: String {
fatalError("unavailable function can't be called")
}
// - (NSString *)
// stringByFoldingWithOptions:(StringCompareOptions)options
// locale:(Locale *)locale
@available(*, unavailable, renamed: "folding(options:locale:)")
public func folding(
_ options: String.CompareOptions = [], locale: Locale?
) -> String {
fatalError("unavailable function can't be called")
}
// @property NSString* stringByResolvingSymlinksInPath;
/// Returns a new string made from the `String` by resolving
/// all symbolic links and standardizing path.
@available(*, unavailable, message: "Use resolvingSymlinksInPath on URL instead.")
public var resolvingSymlinksInPath: String {
fatalError("unavailable property")
}
// @property NSString* stringByStandardizingPath;
/// Returns a new string made by removing extraneous path
/// components from the `String`.
@available(*, unavailable, message: "Use standardizingPath on URL instead.")
public var standardizingPath: String {
fatalError("unavailable function can't be called")
}
// - (NSArray *)stringsByAppendingPaths:(NSArray *)paths
/// Returns an array of strings made by separately appending
/// to the `String` each string in a given array.
@available(*, unavailable, message: "Map over paths with appendingPathComponent instead.")
public func strings(byAppendingPaths paths: [String]) -> [String] {
fatalError("unavailable function can't be called")
}
}
// Pre-Swift-3 method names
extension String {
@available(*, unavailable, renamed: "localizedName(of:)")
public static func localizedNameOfStringEncoding(
_ encoding: String.Encoding
) -> String {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, message: "Use fileURL(withPathComponents:) on URL instead.")
public static func pathWithComponents(_ components: [String]) -> String {
fatalError("unavailable function can't be called")
}
// + (NSString *)pathWithComponents:(NSArray *)components
/// Returns a string built from the strings in a given array
/// by concatenating them with a path separator between each pair.
@available(*, unavailable, message: "Use fileURL(withPathComponents:) on URL instead.")
public static func path(withComponents components: [String]) -> String {
fatalError("unavailable function can't be called")
}
}
extension StringProtocol {
@available(*, unavailable, renamed: "canBeConverted(to:)")
public func canBeConvertedToEncoding(_ encoding: String.Encoding) -> Bool {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed: "capitalizedString(with:)")
public func capitalizedStringWith(_ locale: Locale?) -> String {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed: "commonPrefix(with:options:)")
public func commonPrefixWith(
_ aString: String, options: String.CompareOptions) -> String {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed: "completePath(into:outputName:caseSensitive:matchesInto:filterTypes:)")
public func completePathInto(
_ outputName: UnsafeMutablePointer<String>? = nil,
caseSensitive: Bool,
matchesInto matchesIntoArray: UnsafeMutablePointer<[String]>? = nil,
filterTypes: [String]? = nil
) -> Int {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed: "components(separatedBy:)")
public func componentsSeparatedByCharactersIn(
_ separator: CharacterSet
) -> [String] {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed: "components(separatedBy:)")
public func componentsSeparatedBy(_ separator: String) -> [String] {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed: "cString(usingEncoding:)")
public func cStringUsingEncoding(_ encoding: String.Encoding) -> [CChar]? {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed: "data(usingEncoding:allowLossyConversion:)")
public func dataUsingEncoding(
_ encoding: String.Encoding,
allowLossyConversion: Bool = false
) -> Data? {
fatalError("unavailable function can't be called")
}
#if !DEPLOYMENT_RUNTIME_SWIFT
@available(*, unavailable, renamed: "enumerateLinguisticTags(in:scheme:options:orthography:_:)")
public func enumerateLinguisticTagsIn(
_ range: Range<Index>,
scheme tagScheme: String,
options opts: NSLinguisticTagger.Options,
orthography: NSOrthography?,
_ body:
(String, Range<Index>, Range<Index>, inout Bool) -> Void
) {
fatalError("unavailable function can't be called")
}
#endif
@available(*, unavailable, renamed: "enumerateSubstrings(in:options:_:)")
public func enumerateSubstringsIn(
_ range: Range<Index>,
options opts: String.EnumerationOptions = [],
_ body: (
_ substring: String?, _ substringRange: Range<Index>,
_ enclosingRange: Range<Index>, inout Bool
) -> Void
) {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed: "getBytes(_:maxLength:usedLength:encoding:options:range:remaining:)")
public func getBytes(
_ buffer: inout [UInt8],
maxLength maxBufferCount: Int,
usedLength usedBufferCount: UnsafeMutablePointer<Int>,
encoding: String.Encoding,
options: String.EncodingConversionOptions = [],
range: Range<Index>,
remainingRange leftover: UnsafeMutablePointer<Range<Index>>
) -> Bool {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed: "getLineStart(_:end:contentsEnd:for:)")
public func getLineStart(
_ start: UnsafeMutablePointer<Index>,
end: UnsafeMutablePointer<Index>,
contentsEnd: UnsafeMutablePointer<Index>,
forRange: Range<Index>
) {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed: "getParagraphStart(_:end:contentsEnd:for:)")
public func getParagraphStart(
_ start: UnsafeMutablePointer<Index>,
end: UnsafeMutablePointer<Index>,
contentsEnd: UnsafeMutablePointer<Index>,
forRange: Range<Index>
) {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed: "lengthOfBytes(using:)")
public func lengthOfBytesUsingEncoding(_ encoding: String.Encoding) -> Int {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed: "lineRange(for:)")
public func lineRangeFor(_ aRange: Range<Index>) -> Range<Index> {
fatalError("unavailable function can't be called")
}
#if !DEPLOYMENT_RUNTIME_SWIFT
@available(*, unavailable, renamed: "linguisticTags(in:scheme:options:orthography:tokenRanges:)")
public func linguisticTagsIn(
_ range: Range<Index>,
scheme tagScheme: String,
options opts: NSLinguisticTagger.Options = [],
orthography: NSOrthography? = nil,
tokenRanges: UnsafeMutablePointer<[Range<Index>]>? = nil
) -> [String] {
fatalError("unavailable function can't be called")
}
#endif
@available(*, unavailable, renamed: "lowercased(with:)")
public func lowercaseStringWith(_ locale: Locale?) -> String {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed: "maximumLengthOfBytes(using:)")
public
func maximumLengthOfBytesUsingEncoding(_ encoding: String.Encoding) -> Int {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed: "paragraphRange(for:)")
public func paragraphRangeFor(_ aRange: Range<Index>) -> Range<Index> {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed: "rangeOfCharacter(from:options:range:)")
public func rangeOfCharacterFrom(
_ aSet: CharacterSet,
options mask: String.CompareOptions = [],
range aRange: Range<Index>? = nil
) -> Range<Index>? {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed: "rangeOfComposedCharacterSequence(at:)")
public
func rangeOfComposedCharacterSequenceAt(_ anIndex: Index) -> Range<Index> {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed: "rangeOfComposedCharacterSequences(for:)")
public func rangeOfComposedCharacterSequencesFor(
_ range: Range<Index>
) -> Range<Index> {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed: "range(of:options:range:locale:)")
public func rangeOf(
_ aString: String,
options mask: String.CompareOptions = [],
range searchRange: Range<Index>? = nil,
locale: Locale? = nil
) -> Range<Index>? {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed: "localizedStandardRange(of:)")
public func localizedStandardRangeOf(_ string: String) -> Range<Index>? {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed: "addingPercentEncoding(withAllowedCharacters:)")
public func addingPercentEncodingWithAllowedCharacters(
_ allowedCharacters: CharacterSet
) -> String? {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed: "addingPercentEscapes(using:)")
public func addingPercentEscapesUsingEncoding(
_ encoding: String.Encoding
) -> String? {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed: "appendingFormat")
public func stringByAppendingFormat(
_ format: String, _ arguments: CVarArg...
) -> String {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed: "padding(toLength:with:startingAt:)")
public func byPaddingToLength(
_ newLength: Int, withString padString: String, startingAt padIndex: Int
) -> String {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed: "replacingCharacters(in:with:)")
public func replacingCharactersIn(
_ range: Range<Index>, withString replacement: String
) -> String {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed: "replacingOccurrences(of:with:options:range:)")
public func replacingOccurrencesOf(
_ target: String,
withString replacement: String,
options: String.CompareOptions = [],
range searchRange: Range<Index>? = nil
) -> String {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed: "replacingPercentEscapes(usingEncoding:)")
public func replacingPercentEscapesUsingEncoding(
_ encoding: String.Encoding
) -> String? {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed: "trimmingCharacters(in:)")
public func byTrimmingCharactersIn(_ set: CharacterSet) -> String {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed: "strings(byAppendingPaths:)")
public func stringsByAppendingPaths(_ paths: [String]) -> [String] {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed: "substring(from:)")
public func substringFrom(_ index: Index) -> String {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed: "substring(to:)")
public func substringTo(_ index: Index) -> String {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed: "substring(with:)")
public func substringWith(_ aRange: Range<Index>) -> String {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed: "uppercased(with:)")
public func uppercaseStringWith(_ locale: Locale?) -> String {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed: "write(toFile:atomically:encoding:)")
public func writeToFile(
_ path: String, atomically useAuxiliaryFile:Bool,
encoding enc: String.Encoding
) throws {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed: "write(to:atomically:encoding:)")
public func writeToURL(
_ url: URL, atomically useAuxiliaryFile: Bool,
encoding enc: String.Encoding
) throws {
fatalError("unavailable function can't be called")
}
}
| f6814cc5f0068a469b66259125e2374d | 34.442343 | 279 | 0.677078 | false | false | false | false |
avito-tech/Marshroute | refs/heads/master | Marshroute/Sources/Routers/BaseImpls/BaseRouter/BaseRouter.swift | mit | 1 | import UIKit
/// Роутер, управляющий одним экраном (одним UINavigationController'ом)
/// Работает с одим обработчиком переходов (detail).
/// Например, роутер обычного экрана iPhone-приложения или роутер экрана внутри UIPopoverController'а
open class BaseRouter:
TransitionsHandlersProviderHolder,
TransitionIdGeneratorHolder,
RouterIdentifiable,
RouterPresentable,
RouterTransitionable,
ModalPresentationRouter,
PopoverPresentationRouter,
EndpointRouter,
RouterFocusable,
RouterDismissable,
DetailRouterTransitionable,
DetailRouter,
RouterControllersProviderHolder
{
public let transitionsHandlerBox: RouterTransitionsHandlerBox
public let transitionId: TransitionId
open fileprivate(set) weak var presentingTransitionsHandler: TransitionsHandler?
public let transitionsHandlersProvider: TransitionsHandlersProvider
public let transitionIdGenerator: TransitionIdGenerator
public let controllersProvider: RouterControllersProvider
public init(routerSeed seed: RouterSeed)
{
self.transitionId = seed.transitionId
self.transitionsHandlerBox = seed.transitionsHandlerBox
self.presentingTransitionsHandler = seed.presentingTransitionsHandler
self.transitionsHandlersProvider = seed.transitionsHandlersProvider
self.transitionIdGenerator = seed.transitionIdGenerator
self.controllersProvider = seed.controllersProvider
}
// MARK: - DetailRouterTransitionable
open var detailTransitionsHandlerBox: RouterTransitionsHandlerBox {
return transitionsHandlerBox
}
}
| 78285b184883f6918b41bfc43be1f562 | 37.52381 | 101 | 0.78801 | false | false | false | false |
BradLarson/GPUImage2 | refs/heads/master | framework/Source/Operations/CrosshairGenerator.swift | bsd-3-clause | 1 | #if canImport(OpenGL)
import OpenGL.GL
#endif
#if canImport(OpenGLES)
import OpenGLES
#endif
#if canImport(COpenGLES)
import COpenGLES.gles2
#endif
#if canImport(COpenGL)
import COpenGL
#endif
public class CrosshairGenerator: ImageGenerator {
public var crosshairWidth:Float = 5.0 { didSet { uniformSettings["crosshairWidth"] = crosshairWidth } }
public var crosshairColor:Color = Color.green { didSet { uniformSettings["crosshairColor"] = crosshairColor } }
let crosshairShader:ShaderProgram
var uniformSettings = ShaderUniformSettings()
public override init(size:Size) {
crosshairShader = crashOnShaderCompileFailure("CrosshairGenerator"){try sharedImageProcessingContext.programForVertexShader(CrosshairVertexShader, fragmentShader:CrosshairFragmentShader)}
super.init(size:size)
({crosshairWidth = 5.0})()
({crosshairColor = Color.green})()
}
public func renderCrosshairs(_ positions:[Position]) {
imageFramebuffer.activateFramebufferForRendering()
imageFramebuffer.timingStyle = .stillImage
#if canImport(OpenGL) || canImport(COpenGL)
glEnable(GLenum(GL_POINT_SPRITE))
glEnable(GLenum(GL_VERTEX_PROGRAM_POINT_SIZE))
#else
glEnable(GLenum(GL_POINT_SPRITE_OES))
#endif
crosshairShader.use()
uniformSettings.restoreShaderSettings(crosshairShader)
clearFramebufferWithColor(Color.transparent)
guard let positionAttribute = crosshairShader.attributeIndex("position") else { fatalError("A position attribute was missing from the shader program during rendering.") }
let convertedPositions = positions.flatMap{$0.toGLArray()}
glVertexAttribPointer(positionAttribute, 2, GLenum(GL_FLOAT), 0, 0, convertedPositions)
glDrawArrays(GLenum(GL_POINTS), 0, GLsizei(positions.count))
notifyTargets()
}
}
| 958183257a18cd75cea0afc0458e1b57 | 31.508475 | 195 | 0.720021 | false | false | false | false |
StYaphet/firefox-ios | refs/heads/master | Storage/Rust/RustLogins.swift | mpl-2.0 | 2 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import Shared
@_exported import MozillaAppServices
private let log = Logger.syncLogger
public extension LoginRecord {
convenience init(credentials: URLCredential, protectionSpace: URLProtectionSpace) {
let hostname: String
if let _ = protectionSpace.`protocol` {
hostname = protectionSpace.urlString()
} else {
hostname = protectionSpace.host
}
let httpRealm = protectionSpace.realm
let username = credentials.user
let password = credentials.password
self.init(fromJSONDict: [
"hostname": hostname,
"httpRealm": httpRealm as Any,
"username": username ?? "",
"password": password ?? ""
])
}
var credentials: URLCredential {
return URLCredential(user: username, password: password, persistence: .forSession)
}
var protectionSpace: URLProtectionSpace {
return URLProtectionSpace.fromOrigin(hostname)
}
var hasMalformedHostname: Bool {
let hostnameURL = hostname.asURL
guard let _ = hostnameURL?.host else {
return true
}
return false
}
var isValid: Maybe<()> {
// Referenced from https://mxr.mozilla.org/mozilla-central/source/toolkit/components/passwordmgr/nsLoginManager.js?rev=f76692f0fcf8&mark=280-281#271
// Logins with empty hostnames are not valid.
if hostname.isEmpty {
return Maybe(failure: LoginRecordError(description: "Can't add a login with an empty hostname."))
}
// Logins with empty passwords are not valid.
if password.isEmpty {
return Maybe(failure: LoginRecordError(description: "Can't add a login with an empty password."))
}
// Logins with both a formSubmitURL and httpRealm are not valid.
if let _ = formSubmitURL, let _ = httpRealm {
return Maybe(failure: LoginRecordError(description: "Can't add a login with both a httpRealm and formSubmitURL."))
}
// Login must have at least a formSubmitURL or httpRealm.
if (formSubmitURL == nil) && (httpRealm == nil) {
return Maybe(failure: LoginRecordError(description: "Can't add a login without a httpRealm or formSubmitURL."))
}
// All good.
return Maybe(success: ())
}
}
public class LoginRecordError: MaybeErrorType {
public let description: String
public init(description: String) {
self.description = description
}
}
public class RustLogins {
let databasePath: String
let encryptionKey: String
let salt: String
let queue: DispatchQueue
let storage: LoginsStorage
fileprivate(set) var isOpen: Bool = false
private var didAttemptToMoveToBackup = false
public init(databasePath: String, encryptionKey: String, salt: String) {
self.databasePath = databasePath
self.encryptionKey = encryptionKey
self.salt = salt
self.queue = DispatchQueue(label: "RustLogins queue: \(databasePath)", attributes: [])
self.storage = LoginsStorage(databasePath: databasePath)
}
// Migrate and return the salt, or create a new salt
// Also, in the event of an error, returns a new salt.
public static func setupPlaintextHeaderAndGetSalt(databasePath: String, encryptionKey: String) -> String {
do {
if FileManager.default.fileExists(atPath: databasePath) {
let db = LoginsStorage(databasePath: databasePath)
let salt = try db.getDbSaltForKey(key: encryptionKey)
try db.migrateToPlaintextHeader(key: encryptionKey, salt: salt)
return salt
}
} catch {
print(error)
Sentry.shared.send(message: "setupPlaintextHeaderAndGetSalt failed", tag: SentryTag.rustLogins, severity: .error, description: error.localizedDescription)
}
let saltOf32Chars = UUID().uuidString.replacingOccurrences(of: "-", with: "")
return saltOf32Chars
}
// Open the db, and if it fails, it moves the db and creates a new db file and opens it.
private func open() -> NSError? {
do {
try storage.unlockWithKeyAndSalt(key: encryptionKey, salt: salt)
isOpen = true
return nil
} catch let err as NSError {
if let loginsStoreError = err as? LoginsStoreError {
switch loginsStoreError {
// The encryption key is incorrect, or the `databasePath`
// specified is not a valid database. This is an unrecoverable
// state unless we can move the existing file to a backup
// location and start over.
case .invalidKey(let message):
log.error(message)
if !didAttemptToMoveToBackup {
RustShared.moveDatabaseFileToBackupLocation(databasePath: databasePath)
didAttemptToMoveToBackup = true
return open()
}
case .panic(let message):
Sentry.shared.sendWithStacktrace(message: "Panicked when opening Rust Logins database", tag: SentryTag.rustLogins, severity: .error, description: message)
default:
Sentry.shared.sendWithStacktrace(message: "Unspecified or other error when opening Rust Logins database", tag: SentryTag.rustLogins, severity: .error, description: loginsStoreError.localizedDescription)
}
} else {
Sentry.shared.sendWithStacktrace(message: "Unknown error when opening Rust Logins database", tag: SentryTag.rustLogins, severity: .error, description: err.localizedDescription)
}
return err
}
}
private func close() -> NSError? {
do {
try storage.lock()
isOpen = false
return nil
} catch let err as NSError {
Sentry.shared.sendWithStacktrace(message: "Unknown error when closing Logins database", tag: SentryTag.rustLogins, severity: .error, description: err.localizedDescription)
return err
}
}
public func reopenIfClosed() -> NSError? {
var error: NSError?
queue.sync {
guard !isOpen else { return }
error = open()
}
return error
}
public func interrupt() {
do {
try storage.interrupt()
} catch let err as NSError {
Sentry.shared.sendWithStacktrace(message: "Error interrupting Logins database", tag: SentryTag.rustLogins, severity: .error, description: err.localizedDescription)
}
}
public func forceClose() -> NSError? {
var error: NSError?
interrupt()
queue.sync {
guard isOpen else { return }
error = close()
}
return error
}
public func sync(unlockInfo: SyncUnlockInfo) -> Success {
let deferred = Success()
queue.async {
guard self.isOpen else {
let error = LoginsStoreError.unspecified(message: "Database is closed")
deferred.fill(Maybe(failure: error as MaybeErrorType))
return
}
do {
try _ = self.storage.sync(unlockInfo: unlockInfo)
deferred.fill(Maybe(success: ()))
} catch let err as NSError {
if let loginsStoreError = err as? LoginsStoreError {
switch loginsStoreError {
case .panic(let message):
Sentry.shared.sendWithStacktrace(message: "Panicked when syncing Logins database", tag: SentryTag.rustLogins, severity: .error, description: message)
default:
Sentry.shared.sendWithStacktrace(message: "Unspecified or other error when syncing Logins database", tag: SentryTag.rustLogins, severity: .error, description: loginsStoreError.localizedDescription)
}
}
deferred.fill(Maybe(failure: err))
}
}
return deferred
}
public func get(id: String) -> Deferred<Maybe<LoginRecord?>> {
let deferred = Deferred<Maybe<LoginRecord?>>()
queue.async {
guard self.isOpen else {
let error = LoginsStoreError.unspecified(message: "Database is closed")
deferred.fill(Maybe(failure: error as MaybeErrorType))
return
}
do {
let record = try self.storage.get(id: id)
deferred.fill(Maybe(success: record))
} catch let err as NSError {
deferred.fill(Maybe(failure: err))
}
}
return deferred
}
public func searchLoginsWithQuery(_ query: String?) -> Deferred<Maybe<Cursor<LoginRecord>>> {
return list().bind({ result in
if let error = result.failureValue {
return deferMaybe(error)
}
guard let records = result.successValue else {
return deferMaybe(ArrayCursor(data: []))
}
guard let query = query?.lowercased(), !query.isEmpty else {
return deferMaybe(ArrayCursor(data: records))
}
let filteredRecords = records.filter({
$0.hostname.lowercased().contains(query) || $0.username.lowercased().contains(query)
})
return deferMaybe(ArrayCursor(data: filteredRecords))
})
}
public func getLoginsForProtectionSpace(_ protectionSpace: URLProtectionSpace, withUsername username: String? = nil) -> Deferred<Maybe<Cursor<LoginRecord>>> {
return list().bind({ result in
if let error = result.failureValue {
return deferMaybe(error)
}
guard let records = result.successValue else {
return deferMaybe(ArrayCursor(data: []))
}
let filteredRecords: [LoginRecord]
if let username = username {
filteredRecords = records.filter({
$0.username == username && (
$0.hostname == protectionSpace.urlString() ||
$0.hostname == protectionSpace.host
)
})
} else {
filteredRecords = records.filter({
$0.hostname == protectionSpace.urlString() ||
$0.hostname == protectionSpace.host
})
}
return deferMaybe(ArrayCursor(data: filteredRecords))
})
}
public func hasSyncedLogins() -> Deferred<Maybe<Bool>> {
return list().bind({ result in
if let error = result.failureValue {
return deferMaybe(error)
}
return deferMaybe((result.successValue?.count ?? 0) > 0)
})
}
public func list() -> Deferred<Maybe<[LoginRecord]>> {
let deferred = Deferred<Maybe<[LoginRecord]>>()
queue.async {
guard self.isOpen else {
let error = LoginsStoreError.unspecified(message: "Database is closed")
deferred.fill(Maybe(failure: error as MaybeErrorType))
return
}
do {
let records = try self.storage.list()
deferred.fill(Maybe(success: records))
} catch let err as NSError {
deferred.fill(Maybe(failure: err))
}
}
return deferred
}
public func add(login: LoginRecord) -> Deferred<Maybe<String>> {
let deferred = Deferred<Maybe<String>>()
queue.async {
guard self.isOpen else {
let error = LoginsStoreError.unspecified(message: "Database is closed")
deferred.fill(Maybe(failure: error as MaybeErrorType))
return
}
do {
let id = try self.storage.add(login: login)
deferred.fill(Maybe(success: id))
} catch let err as NSError {
deferred.fill(Maybe(failure: err))
}
}
return deferred
}
public func use(login: LoginRecord) -> Success {
login.timesUsed += 1
login.timeLastUsed = Int64(Date.nowMicroseconds())
return update(login: login)
}
public func update(login: LoginRecord) -> Success {
let deferred = Success()
queue.async {
guard self.isOpen else {
let error = LoginsStoreError.unspecified(message: "Database is closed")
deferred.fill(Maybe(failure: error as MaybeErrorType))
return
}
do {
try self.storage.update(login: login)
deferred.fill(Maybe(success: ()))
} catch let err as NSError {
deferred.fill(Maybe(failure: err))
}
}
return deferred
}
public func delete(ids: [String]) -> Deferred<[Maybe<Bool>]> {
return all(ids.map({ delete(id: $0) }))
}
public func delete(id: String) -> Deferred<Maybe<Bool>> {
let deferred = Deferred<Maybe<Bool>>()
queue.async {
guard self.isOpen else {
let error = LoginsStoreError.unspecified(message: "Database is closed")
deferred.fill(Maybe(failure: error as MaybeErrorType))
return
}
do {
let existed = try self.storage.delete(id: id)
deferred.fill(Maybe(success: existed))
} catch let err as NSError {
deferred.fill(Maybe(failure: err))
}
}
return deferred
}
public func reset() -> Success {
let deferred = Success()
queue.async {
guard self.isOpen else {
let error = LoginsStoreError.unspecified(message: "Database is closed")
deferred.fill(Maybe(failure: error as MaybeErrorType))
return
}
do {
try self.storage.reset()
deferred.fill(Maybe(success: ()))
} catch let err as NSError {
deferred.fill(Maybe(failure: err))
}
}
return deferred
}
public func wipeLocal() -> Success {
let deferred = Success()
queue.async {
guard self.isOpen else {
let error = LoginsStoreError.unspecified(message: "Database is closed")
deferred.fill(Maybe(failure: error as MaybeErrorType))
return
}
do {
try self.storage.wipeLocal()
deferred.fill(Maybe(success: ()))
} catch let err as NSError {
deferred.fill(Maybe(failure: err))
}
}
return deferred
}
}
| 8f73aa37d46ae14a0b0589219e99a258 | 33.162584 | 222 | 0.569789 | false | false | false | false |
NachoSoto/AsyncImageView | refs/heads/master | AsyncImageView/Renderers/RemoteOrLocalImageRenderer.swift | mit | 1 | //
// RemoteOrLocalImageRenderer.swift
// AsyncImageView
//
// Created by Nacho Soto on 2/17/17.
// Copyright © 2017 Nacho Soto. All rights reserved.
//
import UIKit
import ReactiveSwift
public enum RemoteOrLocalRenderData<Local: LocalRenderDataType, Remote: RemoteRenderDataType>: RenderDataType {
case local(Local)
case remote(Remote)
}
/// `RendererType` which downloads images and/or loads images from the bundle.
///
/// - seealso: RemoteImageRenderer
/// - seealso: LocalImageRenderer
public final class RemoteOrLocalImageRenderer<Local: LocalRenderDataType, Remote: RemoteRenderDataType>: RendererType {
public typealias Data = RemoteOrLocalRenderData<Local, Remote>
private let remoteRenderer: RemoteImageRenderer<Remote>
private let localRenderer: LocalImageRenderer<Local>
public init(session: URLSession, scheduler: Scheduler = QueueScheduler()) {
self.remoteRenderer = RemoteImageRenderer(session: session)
self.localRenderer = LocalImageRenderer(scheduler: scheduler)
}
public func renderImageWithData(_ data: Data) -> SignalProducer<UIImage, RemoteImageRendererError> {
switch data {
case let .remote(data):
return self.remoteRenderer
.renderImageWithData(data)
case let .local(data):
return self.localRenderer
.renderImageWithData(data)
.promoteError(RemoteImageRendererError.self)
}
}
}
extension RemoteOrLocalRenderData {
public func hash(into hasher: inout Hasher) {
switch self {
case let .local(data): hasher.combine(data)
case let .remote(data): hasher.combine(data)
}
}
public static func == (lhs: RemoteOrLocalRenderData, rhs: RemoteOrLocalRenderData) -> Bool {
switch (lhs, rhs) {
case let (.local(lhs), .local(rhs)): return lhs == rhs
case let (.remote(lhs), .remote(rhs)): return lhs == rhs
default: return false
}
}
public var size: CGSize {
switch self {
case let .local(data): return data.size
case let .remote(data): return data.size
}
}
}
| 6db365766fac575d90b3c55d508951f5 | 30.528571 | 119 | 0.661078 | false | false | false | false |
ustwo/github-scanner | refs/heads/master | Sources/GitHubScannerKit/Command/ScanOptions.swift | mit | 1 | //
// ScanOptions.swift
// GitHub Scanner
//
// Created by Aaron McTavish on 15/02/2017.
// Copyright © 2017 ustwo Fampany Ltd. All rights reserved.
//
import Commandant
import Foundation
import GitHubKit
import Result
/// Options for the `scan` command.
public struct ScanOptions: OptionsProtocol {
// MARK: - Properties
// Arguments
/// Category of repositories. Must be a `String` representation of `ScanCategory`.
public let category: String
/// Owner of the repositories. Default is an empty string.
public let owner: String
// Options
/// Open-source license on which to filter repositories.
/// Default is an empty string, which does no filtering.
/// To filter for repositories with no license, use "NULL".
public let license: String
/// OAuth token to use for authorization.
/// Default is an empty string, which means the requests will not be authorized.
public let oauthToken: String
/// Primary programming language on which to filter repositories.
/// Default is an empty string, which does no filtering.
/// To filter for repositories with no primary language, use "NULL".
public let primaryLanguage: String
/// Type of repositories to filter.
/// Must be a `String` representation of `SelfRepositoriesType`, `UserRepositoriesType`,
/// or `OrganizationRepositoriesType` depending on `category` and `owner`.
public let repositoryType: String
// MARK: - Validate Options
/// Validates the all of the options.
///
/// - Returns: Returns a `Result` type with a void success or a `ScanOptionsError`
/// if failure indicating the failure reason.
public func validateConfiguration() -> Result<(), ScanOptionsError> {
do {
let categoryType = try validateCategory()
try validateOwner(categoryType: categoryType)
try validateRepositoryType(categoryType: categoryType)
return .success()
} catch let error as ScanOptionsError {
return .failure(error)
} catch {
return .failure(ScanOptionsError.unknown(error: error))
}
}
/// Validates the `category` option.
///
/// - Returns: Returns a deserialized `ScanCategory` if it is a valid option.
/// - Throws: `ScanOptionsError` if the `category` option is not valid.
@discardableResult
private func validateCategory() throws -> ScanCategory {
guard let categoryType = ScanCategory(rawValue: category) else {
throw ScanOptionsError.invalidCategory(value: category)
}
return categoryType
}
/// Validates the `owner` option.
///
/// - Parameter categoryType: The `ScanCategory` type to which the owner belongs.
/// - Throws: `ScanOptionsError` if the `owner` option is not valid.
private func validateOwner(categoryType: ScanCategory) throws {
switch categoryType {
case .organization:
guard !owner.isEmpty else {
throw ScanOptionsError.missingOwner
}
case .user:
guard !(owner.isEmpty && oauthToken.isEmpty) else {
throw ScanOptionsError.missingAuthorization
}
}
}
/// Validates the `repositoryType` option.
///
/// - Parameter categoryType: The `ScanCategory` type to which the repositories belong.
/// - Throws: `ScanOptionsError` if the `repositoryType` option is not valid.
private func validateRepositoryType(categoryType: ScanCategory) throws {
switch categoryType {
case .organization:
try validateRepositoryType(type: OrganizationRepositoriesType.self)
case .user:
if owner.isEmpty {
try validateRepositoryType(type: SelfRepositoriesType.self)
} else {
try validateRepositoryType(type: UserRepositoriesType.self)
}
}
}
private func validateRepositoryType<T: RawRepresentable>(type: T.Type) throws where T.RawValue == String {
guard T(rawValue: repositoryType) != nil else {
throw ScanOptionsError.invalidRepositoryType(value: repositoryType)
}
}
// MARK: - OptionsProtocol
public static func create(_ license: String) -> (_ oauthToken: String) ->
(_ primaryLanguage: String) -> (_ repositoryType: String) -> (_ category: String) ->
(_ owner: String) -> ScanOptions {
return { oauthToken in { primaryLanguage in { repositoryType in { category in { owner in
self.init(category: category,
owner: owner,
license: license,
oauthToken: oauthToken,
primaryLanguage: primaryLanguage,
repositoryType: repositoryType)
}}}}}
}
public static func evaluate(_ mode: CommandMode) -> Result<ScanOptions, CommandantError<GitHubScannerError>> {
return create
<*> mode <| Option(key: "license",
defaultValue: "",
usage: "the license type of the repositories (e.g. 'MIT License'). " +
"requires authorization")
<*> mode <| Option(key: "oauth",
defaultValue: "",
usage: "the OAuth token to use for searching repositories")
<*> mode <| Option(key: "primary-language",
defaultValue: "",
usage: "the primary programming language of the repository")
<*> mode <| Option(key: "type",
defaultValue: "all",
usage: "the type of repository. default value 'all'. may require authorization")
<*> mode <| Argument(usage: "the category of repositories to scan \(ScanCategory.allValuesList)")
<*> mode <| Argument(defaultValue: "",
usage: "the owner of repositories to scan (e.g. organization name or username)")
}
}
/// Category of repositories.
public enum ScanCategory: String {
case organization
case user
static let allValues: [ScanCategory] = [.organization, .user]
static let allValuesList: String = {
ScanCategory.allValues.map({ $0.rawValue }).joined(separator: ", ")
}()
}
/// Type of repositories to filter when searching own repositories.
public enum SelfRepositoriesType: String {
case all
case `private`
case `public`
static let allValues: [SelfRepositoriesType] = [.all, .private, .public]
static let allValuesList: String = {
SelfRepositoriesType.allValues.map({ $0.rawValue }).joined(separator: ", ")
}()
}
/// Type of repositories to filter when searching a user's repositories.
public enum UserRepositoriesType: String {
case all
case member
case owner
static let allValues: [UserRepositoriesType] = [.all, .member, .owner]
static let allValuesList: String = {
UserRepositoriesType.allValues.map({ $0.rawValue }).joined(separator: ", ")
}()
}
/// Type of repositories to filter when searching an organization's repositories.
public enum OrganizationRepositoriesType: String {
case all
case forks
case member
case `private`
case `public`
case sources
static let allValues: [OrganizationRepositoriesType] = [.all, .forks, .member, .private, .public, .sources]
static let allValuesList: String = {
OrganizationRepositoriesType.allValues.map({ $0.rawValue }).joined(separator: ", ")
}()
}
| 3890ca9376e961be7ae5548f988274c0 | 34.906542 | 114 | 0.621812 | false | false | false | false |
paiv/AngleGradientLayer | refs/heads/master | ConicSample/ConicSample/Gradients/UserGradient2.swift | mit | 1 | import UIKit
class UserGradient2 : UIControl {
override class var layerClass: AnyClass {
return CAGradientLayer.self
}
required init?(coder: NSCoder) {
super.init(coder: coder)
var colors: [CGColor] = []
colors.append(UIColor(white:0.65, alpha: 1).cgColor)
colors.append(UIColor(white:0.55, alpha: 1).cgColor)
colors.append(UIColor(white:0.35, alpha: 1).cgColor)
colors.append(UIColor(white:0.75, alpha: 1).cgColor)
colors.append(UIColor(white:0.9, alpha: 1).cgColor)
colors.append(UIColor(white:0.75, alpha: 1).cgColor)
colors.append(UIColor(white:0.35, alpha: 1).cgColor)
colors.append(UIColor(white:0.75, alpha: 1).cgColor)
colors.append(UIColor(white:0.9, alpha: 1).cgColor)
colors.append(UIColor(white:0.65, alpha: 1).cgColor)
let layer = layer as! CAGradientLayer
layer.type = .conic
layer.startPoint = CGPoint(x: 0.5, y: 0.5)
layer.endPoint = CGPoint(x: 1, y: 0.5)
layer.colors = colors
layer.borderColor = UIColor(white: 0.55, alpha: 1).cgColor
layer.borderWidth = 1
}
override var frame: CGRect {
didSet {
layer.cornerRadius = bounds.width / 2
}
}
}
| 34ce02a7f07e52b7defa1da467c83917 | 32.282051 | 66 | 0.605547 | false | false | false | false |
davedufresne/SwiftParsec | refs/heads/master | Sources/SwiftParsec/String.swift | bsd-2-clause | 1 | //==============================================================================
// String.swift
// SwiftParsec
//
// Created by David Dufresne on 2015-10-10.
// Copyright © 2015 David Dufresne. All rights reserved.
//
// String extension
//==============================================================================
//==============================================================================
// Extension containing various utility methods and initializers.
extension String {
/// Initialize a `String` from a sequence of code units.
///
/// - parameters:
/// - codeUnits: Sequence of code units.
/// - codec: A unicode encoding scheme.
init?<C: UnicodeCodec, S: Sequence>(codeUnits: S, codec: C)
where S.Iterator.Element == C.CodeUnit {
var unicodeCode = codec
var str = ""
var iterator = codeUnits.makeIterator()
var done = false
while !done {
let result = unicodeCode.decode(&iterator)
switch result {
case .emptyInput: done = true
case let .scalarValue(val):
str.append(Character(val))
case .error: return nil
}
}
self = str
}
/// The last character of the string.
///
/// If the string is empty, the value of this property is `nil`.
var last: Character? {
guard !isEmpty else { return nil }
return self[index(before: endIndex)]
}
/// Return a new `String` with `c` adjoined to the end.
///
/// - parameter c: Character to append.
func appending(_ c: Character) -> String {
var mutableSelf = self
mutableSelf.append(c)
return mutableSelf
}
}
| a5a5c4644f75c6b27728f8912699b904 | 25.902778 | 80 | 0.444502 | false | false | false | false |
zwaldowski/OneTimePad | refs/heads/master | OneTimePad/Cryptor.swift | mit | 1 | //
// Cryptor.swift
// OneTimePad
//
// Created by Zachary Waldowski on 9/6/15.
// Copyright © 2015 Zachary Waldowski. All rights reserved.
//
import CommonCryptoShim.Private
/// This interface provides access to a number of symmetric encryption
/// algorithms. Symmetric encryption algorithms come in two "flavors" - block
/// ciphers, and stream ciphers. Block ciphers process data in discrete chunks
/// called blocks; stream ciphers operate on arbitrary sized data.
///
/// The type declared in this interface, `Cryptor`, provides access to both
/// block ciphers and stream ciphers with the same API; however, some options
/// are available for block ciphers that do not apply to stream ciphers.
///
/// The general operation of a cryptor is:
/// - Initialize it with raw key data and other optional fields
/// - Process input data via one or more calls to the `update` method, each of
/// which may result in output data being written to caller-supplied memory
/// - Obtain possible remaining output data with the `finalize` method.
/// - Reuse the cryptor with the same key data by calling the `reset` method.
///
/// One option for block ciphers is padding, as defined in PKCS7;
/// when padding is enabled, the total amount of data encrypted
/// does not have to be an even multiple of the block size, and
/// the actual length of plaintext is calculated during decryption.
///
/// Another option for block ciphers is Cipher Block Chaining, known as CBC
/// mode. When using CBC, an Initialization Vector (IV) is provided along with
/// the key when starting an operation. If CBC mode is selected and no IV is
/// provided, an IV of all zeroes will be used.
///
/// `Cryptor` also implements block bufferring, such that individual calls to
/// update the context do not have to provide data whose length is aligned to
/// the block size. If padding is disabled, block cipher encryption does require
/// that the *total* length of data input be aligned to the block size.
///
/// A given `Cryptor` can only be used by one thread at a time; multiple threads
/// can use safely different `Cryptor`s at the same time.
public final class Cryptor: CCPointer {
typealias RawCryptor = CCCryptorRef
private(set) var rawPointer = RawCryptor()
private struct Configuration {
let mode: CCMode
let algorithm: CCAlgorithm
let padding: CCPadding
let iv: UnsafePointer<Void>
let tweak: UnsafeBufferPointer<Void>?
let numberOfRounds: Int32?
}
private static func createCryptor(operation op: CCOperation, configuration c: Configuration, key: UnsafeBufferPointer<Void>, inout cryptor: RawCryptor) throws {
try call {
CCCryptorCreateWithMode(op, c.mode, c.algorithm, c.padding, c.iv, key.baseAddress, key.count, c.tweak?.baseAddress ?? nil, c.tweak?.count ?? 0, c.numberOfRounds ?? 0, [], &cryptor)
}
}
private init(operation op: CCOperation, configuration c: Configuration, key: UnsafeBufferPointer<Void>) throws {
try Cryptor.createCryptor(operation: op, configuration: c, key: key, cryptor: &rawPointer)
}
deinit {
CCCryptorRelease(rawPointer)
}
/// Process (encrypt or decrypt) some data. The result, if any, is written
/// to a caller-provided buffer.
///
/// This method can be called multiple times. The caller does not need to
/// align the size of input data to block sizes; input is buffered as
/// as necessary for block ciphers.
///
/// When performing symmetric encryption with block ciphers and padding is
/// enabled, the total number of bytes provided by all calls to this method
/// when encrypting can be arbitrary (i.e., the total number of bytes does
/// not have to be block aligned). However, if padding is disabled, or when
/// decrypting, the total number of bytes does have to be aligned to the
/// block size; otherwise `finalize` will throw an error.
///
/// A general rule for the size of the output buffer which must be provided
/// is that for block ciphers, the output length is never larger than the
/// input length plus the block size. For stream ciphers, the output length
/// is always exactly the same as the input length.
///
/// Generally, when all data has been processed, call `finalize`. In the
/// following cases, finalizing is superfluous as it will not yield any
/// data, nor return an error:
/// - Encrypting or decrypting with a block cipher with padding
/// disabled, when the total amount of data provided to `update` is an
/// an integral multiple of the block size.
/// - Encrypting or decrypting with a stream cipher.
///
/// - parameter data: Data to process.
/// - parameter output: The result, if any, is written here. Must be
/// allocated by the caller. Encryption and decryption can be performed
/// "in-place", with the same buffer used for input and output.
/// - returns: The number of bytes written to `output`.
/// - throws:
/// - `CryptoError.BufferTooSmall` to indicate insufficient space in the
/// `output` buffer. Use `outputLengthForInputLength` to determine the
/// required output buffer size in this case. The update can be retried;
/// no state has been lost.
/// - seealso: outputLengthForInputLength(_:finalizing:)
public func update(data: UnsafeBufferPointer<Void>, inout output: UnsafeMutableBufferPointer<Void>!) throws -> Int {
return try call {
CCCryptorUpdate($0, data.baseAddress, data.count, output?.baseAddress ?? nil, output?.count ?? 0, $1)
}
}
/// Finish an encrypt or decrypt operation, and obtain final data output.
///
/// Upon successful return, the `Cryptor` can no longer be used for
/// subsequent operations unless `reset` is called on it.
///
/// It is not necessary to call this method when performing symmetric
/// encryption with padding disabled, or when using a stream cipher.
///
/// It is not necessary to call this method when aborting an operation.
///
/// - parameter output: The result, if any, is written here. Must be
/// allocated by the caller.
/// - returns: The number of bytes written to `output`.
/// - throws: CryptoError.BufferTooSmall to indicate insufficient space
/// in the `output` buffer. Use `outputLengthForInputLength` to determine
/// to determine the required output buffer size in this case. The update
/// can be re-tried; no state has been lost.
/// - throws: CryptoError.MisalignedMemory if the total number of bytes
/// provided to `update` is not an integral multiple of the current
/// algorithm's block size.
/// - throws:
/// - `CryptoError.DecodingFailure` to indicate garbled ciphertext or
/// the wrong key during decryption.
/// - seealso: outputLengthForInputLength(_:finalizing:)
public func finalize(inout output: UnsafeMutableBufferPointer<Void>) throws -> Int {
return try call {
CCCryptorFinal($0, output.baseAddress, output.count, $1)
}
}
/// Reinitialize an existing `Cryptor`, possibly with a new initialization
/// vector.
///
/// This can be called on a `Cryptor` with data pending (i.e. in a padded
/// mode operation before finalized); any pending data will be lost.
///
/// - note: Not implemented for stream ciphers.
/// - parameter iv: New initialization vector, optional. If present, must
/// be the same size as the current algorithm's block size.
/// - throws:
/// - `CryptoError.InvalidParameters` to indicate an invalid IV.
/// - `CryptoError.Unimplemented` for stream ciphers.
public func reset(iv: UnsafePointer<Void> = nil) throws {
return try call {
CCCryptorReset($0, iv)
}
}
/// Determine output buffer size required to process a given input size.
///
/// Some general rules apply that allow callers to know a priori how much
/// output buffer space will be required generally:
/// - For stream ciphers, the output size is always equal to the input
/// size.
/// - For block ciphers, the output size will always be less than or equal
/// to the input size plus the size of one block. For block ciphers, if
/// the input size provided to each call to `update` is is an integral
/// multiple of the block size, then the output size for each call to
/// `update` is less than or equal to the input size for that call.
///
/// `finalize` only produces output when using a block cipher with padding
/// enabled.
///
/// - parameter inputLength: The length of data which will be provided to
/// `update`.
/// - parameter finalizing: If `false`, the size will indicate the
/// space needed when 'inputLength' bytes are provided to `update`.
/// If `true`, the size will indicate the space needed when 'inputLength'
/// bytes are provided to `update`, prior to a call to `finalize`.
/// - returns: The maximum buffer space need to perform `update` and
/// optionally `finalize`.
public func outputLengthForInputLength(inputLength: Int, finalizing: Bool = false) -> Int {
return CCCryptorGetOutputLength(rawPointer, inputLength, finalizing)
}
}
public extension Cryptor {
/// Padding for Block Ciphers
enum Padding {
/// No padding.
case None
/// Padding, as defined in PKCS#7 (RFC #2315)
case PKCS7
}
enum Mode {
/// Electronic Code Book Mode
case ECB
/// Cipher Block Chaining Mode
///
/// If the IV is `nil`, an all zeroes IV will be used.
case CBC(iv: UnsafePointer<Void>)
/// Output Feedback Mode.
///
/// If the IV is `nil`, an all zeroes IV will be used.
case CFB(iv: UnsafePointer<Void>)
/// Counter Mode
///
/// If the IV is `nil`, an all zeroes IV will be used.
case CTR(iv: UnsafePointer<Void>)
/// Output Feedback Mode
///
/// If the IV is `nil`, an all zeroes IV will be used.
case OFB(iv: UnsafePointer<Void>)
/// XEX-based Tweaked CodeBook Mode
case XTS(tweak: UnsafeBufferPointer<Void>)
/// Cipher Feedback Mode producing 8 bits per round.
///
/// If the IV is `nil`, an all zeroes IV will be used.
case CFB8(iv: UnsafePointer<Void>, numberOfRounds: Int32)
}
enum Algorithm {
/// Advanced Encryption Standard, 128-bit block
case AES(Mode, Padding)
/// Data Encryption Standard
case DES(Mode, Padding)
/// Triple-DES, three key, EDE configuration
case TripleDES(Mode, Padding)
/// CAST
case CAST(Mode, Padding)
/// RC4 stream cipher
case RC4
/// Blowfish block cipher
case Blowfish(Mode, Padding)
}
}
public extension Cryptor.Algorithm {
/// Block size, in bytes, for supported algorithms.
var blockSize: Int {
switch self {
case .AES:
return kCCBlockSizeAES128
case .DES:
return kCCBlockSizeDES
case .TripleDES:
return kCCBlockSize3DES
case .CAST:
return kCCBlockSizeCAST
case .RC4:
return kCCBlockSizeRC4
case .Blowfish:
return kCCBlockSizeBlowfish
}
}
/// Key sizes, in bytes, for supported algorithms. Use this range to select
/// key-size variants you wish to use.
///
/// - DES and TripleDES have fixed key sizes.
/// - AES has three discrete key sizes in 64-bit increments.
/// - CAST and RC4 have variable key sizes.
var validKeySizes: ClosedInterval<Int> {
switch self {
case .AES:
return kCCKeySizeAES128...kCCKeySizeAES256
case .DES:
return kCCKeySizeDES...kCCKeySizeDES
case .TripleDES:
return kCCKeySize3DES...kCCKeySize3DES
case .CAST:
return kCCKeySizeMinCAST...kCCKeySizeMaxCAST
case .RC4:
return kCCKeySizeMinRC4...kCCKeySizeMaxRC4
case .Blowfish:
return kCCKeySizeMinBlowfish...kCCKeySizeMaxBlowfish
}
}
}
private extension Cryptor.Padding {
var rawValue: CCPadding {
switch self {
case .None: return .None
case .PKCS7: return .PKCS7
}
}
}
private extension Cryptor.Configuration {
init(_ alg: CCAlgorithm, mode: Cryptor.Mode, padding: Cryptor.Padding) {
let pad = padding.rawValue
switch mode {
case .ECB:
self.init(mode: .ECB, algorithm: alg, padding: pad, iv: nil, tweak: nil, numberOfRounds: nil)
case let .CBC(iv):
self.init(mode: .CBC, algorithm: alg, padding: pad, iv: iv, tweak: nil, numberOfRounds: nil)
case let .CFB(iv):
self.init(mode: .CFB, algorithm: alg, padding: pad, iv: iv, tweak: nil, numberOfRounds: nil)
case let .CTR(iv):
self.init(mode: .CTR, algorithm: alg, padding: pad, iv: iv, tweak: nil, numberOfRounds: nil)
case let .OFB(iv):
self.init(mode: .OFB, algorithm: alg, padding: pad, iv: iv, tweak: nil, numberOfRounds: nil)
case let .XTS(tweak):
self.init(mode: .XTS, algorithm: alg, padding: pad, iv: nil, tweak: tweak, numberOfRounds: nil)
case let .CFB8(iv, numberOfRounds):
self.init(mode: .CFB8, algorithm: alg, padding: pad, iv: iv, tweak: nil, numberOfRounds: numberOfRounds)
}
}
init(_ conf: Cryptor.Algorithm) {
switch conf {
case .RC4:
self.init(mode: .RC4, algorithm: .RC4, padding: .None, iv: nil, tweak: nil, numberOfRounds: nil)
case let .AES(mode, padding):
self.init(.AES, mode: mode, padding: padding)
case let .DES(mode, padding):
self.init(.DES, mode: mode, padding: padding)
case let .TripleDES(mode, padding):
self.init(.TripleDES, mode: mode, padding: padding)
case let .CAST(mode, padding):
self.init(.CAST, mode: mode, padding: padding)
case let .Blowfish(mode, padding):
self.init(.Blowfish, mode: mode, padding: padding)
}
}
}
public extension Cryptor {
/// Create a context for encryption.
///
/// - parameter algorithm: Defines the algorithm and its mode.
/// - parameter key: Raw key material. Length must be appropriate for the
/// selected algorithm; some algorithms provide for varying key lengths.
/// - throws:
/// - `CryptoError.InvalidParameters`
/// - `CryptoError.CouldNotAllocateMemory`
convenience init(forEncryption algorithm: Algorithm, key: UnsafeBufferPointer<Void>) throws {
try self.init(operation: .Encrypt, configuration: Configuration(algorithm), key: key)
}
/// Create a context for decryption.
///
/// - parameter algorithm: Defines the algorithm and its mode.
/// - parameter key: Raw key material. Length must be appropriate for the
/// selected algorithm; some algorithms provide for varying key lengths.
/// - throws:
/// - `CryptoError.InvalidParameters`
/// - `CryptoError.CouldNotAllocateMemory`
convenience init(forDecryption algorithm: Algorithm, key: UnsafeBufferPointer<Void>) throws {
try self.init(operation: .Decrypt, configuration: Configuration(algorithm), key: key)
}
}
public extension Cryptor {
public enum OneShotError: ErrorType {
/// Insufficent buffer provided for specified operation.
case BufferTooSmall(Int)
}
private static func cryptWithAlgorithm(operation op: CCOperation, configuration c: Configuration, key: UnsafeBufferPointer<Void>, input: UnsafeBufferPointer<Void>, inout output: UnsafeMutableBufferPointer<Void>!) throws -> Int {
var cryptor = RawCryptor()
try createCryptor(operation: op, configuration: c, key: key, cryptor: &cryptor)
defer {
CCCryptorRelease(cryptor)
}
var dataOut = output.baseAddress
var dataOutAvailable = output.count
var updateLen = 0
var finalLen = 0
let needed = CCCryptorGetOutputLength(cryptor, input.count, true)
guard needed > output.count else {
throw OneShotError.BufferTooSmall(needed)
}
do {
try call {
CCCryptorUpdate(cryptor, input.baseAddress, input.count, dataOut, dataOutAvailable, &updateLen)
}
} catch CryptoError.BufferTooSmall {
throw OneShotError.BufferTooSmall(needed)
}
dataOut += updateLen
dataOutAvailable -= updateLen
do {
try call {
CCCryptorFinal(cryptor, dataOut, dataOutAvailable, &finalLen)
}
} catch CryptoError.BufferTooSmall {
throw OneShotError.BufferTooSmall(needed)
}
return updateLen + finalLen
}
/// Stateless, one-shot encryption.
///
/// This basically performs a sequence of `Cryptor.init()`, `update`, and
/// `finalize`.
///
/// - parameter algorithm: Defines the algorithm and its mode.
/// - parameter key: Raw key material. Length must be appropriate for the
/// selected algorithm; some algorithms provide for varying key lengths.
/// - parameter input: Data to encrypt or decrypt.
/// - parameter output: The result, is written here. Must be allocated by
/// the caller. Encryption and decryption can be performed "in-place",
/// with the same buffer used for input and output.
/// - returns: The number of bytes written to `output`.
/// - throws:
/// - A special `Cryptor.OneShotError.BufferToSmall` indicates insufficent
/// space in the output buffer, with the minimum size attached. The
/// operation can be retried with minimal runtime penalty.
/// - `CryptoError.MisalignedMemory` if the number of bytes provided
/// is not an integral multiple of the algorithm's block size.
static func encryptWithAlgorithm(algorithm alg: Algorithm, key: UnsafeBufferPointer<Void>, input: UnsafeBufferPointer<Void>, inout output: UnsafeMutableBufferPointer<Void>!) throws -> Int {
return try cryptWithAlgorithm(operation: .Encrypt, configuration: Configuration(alg), key: key, input: input, output: &output)
}
/// Stateless, one-shot decryption.
///
/// This basically performs a sequence of `Cryptor.init()`, `update`, and
/// `finalize`.
///
/// - parameter algorithm: Defines the algorithm and its mode.
/// - parameter key: Raw key material. Length must be appropriate for the
/// selected algorithm; some algorithms provide for varying key lengths.
/// - parameter input: Data to encrypt or decrypt.
/// - parameter output: The result, is written here. Must be allocated by
/// the caller. Encryption and decryption can be performed "in-place",
/// with the same buffer used for input and output.
/// - returns: The number of bytes written to `output`.
/// - throws:
/// - A special `Cryptor.OneShotError.BufferToSmall` indicates insufficent
/// space in the output buffer, with the minimum size attached. The
/// operation can be retried with minimal runtime penalty.
/// - `CryptoError.MisalignedMemory` if the number of bytes provided
/// is not an integral multiple of the algorithm's block size.
/// - `CryptoError.DecodingFailure` Indicates improperly formatted
/// ciphertext or a "wrong key" error.
static func decryptWithAlgorithm(algorithm alg: Algorithm, key: UnsafeBufferPointer<Void>, input: UnsafeBufferPointer<Void>, inout output: UnsafeMutableBufferPointer<Void>!) throws -> Int {
return try cryptWithAlgorithm(operation: .Decrypt, configuration: Configuration(alg), key: key, input: input, output: &output)
}
}
| 4d4619f78675a81c3f092fc41259539f | 42.618026 | 232 | 0.647643 | false | false | false | false |
FromPointer/VPNOn | refs/heads/develop | TodayWidget/TodayViewController.swift | mit | 18 | //
// TodayViewController.swift
// TodayWidget
//
// Created by Lex Tang on 12/10/14.
// Copyright (c) 2014 LexTang.com. All rights reserved.
//
import UIKit
import NotificationCenter
import NetworkExtension
import VPNOnKit
import CoreData
let kVPNOnSelectedIDInToday = "kVPNOnSelectedIDInToday"
let kVPNOnExpanedInToday = "kVPNOnExpanedInToday"
let kVPNOnWidgetNormalHeight: CGFloat = 148
class TodayViewController: UIViewController, NCWidgetProviding, UICollectionViewDelegate, UICollectionViewDataSource {
@IBOutlet weak var leftMarginView: ModeButton!
@IBOutlet weak var collectionView: UICollectionView!
var hasSignaled = false
private var _complitionHandler: (NCUpdateResult -> Void)? = nil
var vpns: [VPN] {
get {
return VPNDataManager.sharedManager.allVPN()
}
}
var selectedID: String? {
get {
return NSUserDefaults.standardUserDefaults().objectForKey(kVPNOnSelectedIDInToday) as! String?
}
set {
if let newID = newValue {
NSUserDefaults.standardUserDefaults().setObject(newID, forKey: kVPNOnSelectedIDInToday)
} else {
NSUserDefaults.standardUserDefaults().removeObjectForKey(kVPNOnSelectedIDInToday)
}
}
}
var expanded: Bool {
get {
return NSUserDefaults.standardUserDefaults().boolForKey(kVPNOnExpanedInToday) as Bool
}
set {
NSUserDefaults.standardUserDefaults().setBool(newValue, forKey: kVPNOnExpanedInToday)
if newValue {
self.preferredContentSize = self.collectionView.contentSize
} else {
self.preferredContentSize = CGSizeMake(self.view.bounds.size.width, kVPNOnWidgetNormalHeight)
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
preferredContentSize = CGSizeMake(0, 82)
let tapGasture = UITapGestureRecognizer(target: self, action: Selector("didTapLeftMargin:"))
tapGasture.numberOfTapsRequired = 1
tapGasture.numberOfTouchesRequired = 1
leftMarginView.userInteractionEnabled = true
leftMarginView.addGestureRecognizer(tapGasture)
leftMarginView.backgroundColor = UIColor(white: 1.0, alpha: 0.005)
leftMarginView.displayMode = VPNManager.sharedManager.displayFlags ? .FlagMode : .SwitchMode
NSNotificationCenter.defaultCenter().addObserver(
self,
selector: Selector("coreDataDidSave:"),
name: NSManagedObjectContextDidSaveNotification,
object: nil)
NSNotificationCenter.defaultCenter().addObserver(
self,
selector: Selector("VPNStatusDidChange:"),
name: NEVPNStatusDidChangeNotification,
object: nil)
NSNotificationCenter.defaultCenter().addObserver(
self,
selector: Selector("pingDidUpdate:"),
name: kPingDidUpdate,
object: nil)
}
deinit {
NSNotificationCenter.defaultCenter().removeObserver(
self,
name: NSManagedObjectContextDidSaveNotification,
object: nil)
NSNotificationCenter.defaultCenter().removeObserver(
self,
name: NEVPNStatusDidChangeNotification,
object: nil)
NSNotificationCenter.defaultCenter().removeObserver(
self,
name: kPingDidUpdate,
object: nil)
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
LTPingQueue.sharedQueue.restartPing()
collectionView.dataSource = nil
updateContent()
collectionView.dataSource = self
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
if collectionView.visibleCells().count > vpns.count {
leftMarginView.expandIconView.hidden = true
self.expanded = false
} else {
leftMarginView.expandIconView.hidden = false
}
if self.expanded {
preferredContentSize = collectionView.contentSize
} else {
preferredContentSize = CGSizeMake(collectionView.contentSize.width, min(kVPNOnWidgetNormalHeight, collectionView.contentSize.height))
}
}
// Note: A workaround to ensure the widget is interactable.
// @see: http://stackoverflow.com/questions/25961513/ios-8-today-widget-stops-working-after-a-while
func singalComplete(updateResult: NCUpdateResult) {
hasSignaled = true
if let handler = _complitionHandler {
handler(updateResult)
}
}
override func viewDidDisappear(animated: Bool) {
super.viewDidDisappear(animated)
if !hasSignaled {
singalComplete(NCUpdateResult.Failed)
}
}
func updateContent() {
// Note: In order to get the latest data.
// @see: http://stackoverflow.com/questions/25924223/core-data-ios-8-today-widget-issue
VPNDataManager.sharedManager.managedObjectContext?.reset()
}
func widgetPerformUpdateWithCompletionHandler(completionHandler: ((NCUpdateResult) -> Void)!) {
// Perform any setup necessary in order to update the view.
// If an error is encountered, use NCUpdateResult.Failed
// If there's no update required, use NCUpdateResult.NoData
// If there's an update, use NCUpdateResult.NewData
_complitionHandler = completionHandler
completionHandler(NCUpdateResult.NewData)
}
// MARK: - Layout
func widgetMarginInsetsForProposedMarginInsets(defaultMarginInsets: UIEdgeInsets) -> UIEdgeInsets
{
return UIEdgeInsetsZero
}
// MARK: - Collection View Data source
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int
{
return vpns.count + 1
}
// The cell that is returned must be retrieved from a call to -dequeueReusableCellWithReuseIdentifier:forIndexPath:
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell
{
if indexPath.row == vpns.count {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("addCell", forIndexPath: indexPath) as! AddCell
return cell
} else {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("vpnCell", forIndexPath: indexPath) as! VPNCell
let vpn = vpns[indexPath.row]
let selected = Bool(selectedID == vpn.ID)
cell.configureWithVPN(vpns[indexPath.row], selected: selected)
if selected {
cell.status = VPNManager.sharedManager.status
} else {
cell.status = .Disconnected
}
cell.latency = LTPingQueue.sharedQueue.latencyForHostname(vpn.server)
return cell
}
}
// MARK: - Collection View Delegate
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath)
{
if indexPath.row == vpns.count {
didTapAdd()
return
}
let vpn = vpns[indexPath.row]
if VPNManager.sharedManager.status == .Connected {
if selectedID == vpn.ID {
// Do not connect it again if tap the same one
return
}
}
selectedID = vpn.ID
let cell = collectionView.cellForItemAtIndexPath(indexPath)! as! VPNCell
let passwordRef = VPNKeychainWrapper.passwordForVPNID(vpn.ID)
let secretRef = VPNKeychainWrapper.secretForVPNID(vpn.ID)
let certificate = VPNKeychainWrapper.certificateForVPNID(vpn.ID)
let titleWithSubfix = "Widget - \(vpn.title)"
if vpn.ikev2 {
VPNManager.sharedManager.connectIKEv2(titleWithSubfix,
server: vpn.server,
account: vpn.account,
group: vpn.group,
alwaysOn: vpn.alwaysOn,
passwordRef: passwordRef,
secretRef: secretRef,
certificate: certificate)
} else {
VPNManager.sharedManager.connectIPSec(titleWithSubfix,
server: vpn.server,
account: vpn.account,
group: vpn.group,
alwaysOn: vpn.alwaysOn,
passwordRef: passwordRef,
secretRef: secretRef,
certificate: certificate)
}
}
func collectionView(collectionView: UICollectionView, shouldHighlightItemAtIndexPath indexPath: NSIndexPath) -> Bool {
if indexPath.row == vpns.count {
return true
}
let cell = collectionView.cellForItemAtIndexPath(indexPath) as! VPNCell
switch VPNManager.sharedManager.status {
case .Connected, .Connecting:
VPNManager.sharedManager.disconnect()
default: ()
}
return true
}
// MARK: - Left margin
func didTapLeftMargin(gesture: UITapGestureRecognizer) {
var tappedBottom = Bool(gesture.locationInView(leftMarginView).y > leftMarginView.frame.size.height / 3 * 2)
if !self.expanded && collectionView.contentSize.height == preferredContentSize.height {
tappedBottom = false
}
if tappedBottom {
self.expanded = !self.expanded
} else {
LTPingQueue.sharedQueue.restartPing()
VPNManager.sharedManager.displayFlags = !VPNManager.sharedManager.displayFlags
collectionView.reloadData()
leftMarginView.displayMode = VPNManager.sharedManager.displayFlags ? .FlagMode : .SwitchMode
}
}
// MARK: - Open App
func didTapAdd() {
let appURL = NSURL(string: "vpnon://")
extensionContext!.openURL(appURL!, completionHandler: {
(complete: Bool) -> Void in
})
}
// MARK: - Notification
func pingDidUpdate(notification: NSNotification) {
collectionView.reloadData()
}
func coreDataDidSave(notification: NSNotification) {
VPNDataManager.sharedManager.managedObjectContext?.mergeChangesFromContextDidSaveNotification(notification)
updateContent()
}
func VPNStatusDidChange(notification: NSNotification?) {
collectionView.reloadData()
if VPNManager.sharedManager.status == .Disconnected {
LTPingQueue.sharedQueue.restartPing()
}
}
}
| 83d34b186952a87c785cb91b6b15ca0a | 33.698413 | 145 | 0.624245 | false | false | false | false |
Palleas/BetaSeriesKit | refs/heads/master | BetaSeriesKit/AuthenticatedClient.swift | mit | 1 | //
// AuthenticatedClient.swift
// BetaSeriesKit
//
// Created by Romain Pouclet on 2016-02-14.
// Copyright © 2016 Perfectly-Cooked. All rights reserved.
//
import UIKit
import ReactiveCocoa
public class AuthenticatedClient: NSObject {
public enum AuthenticatedClientError: ErrorType {
case InternalError(actualError: RequestError)
}
private static let baseURL = NSURL(string: "https://api.betaseries.com")!
let key: String
public let token: String
public init(key: String, token: String) {
self.key = key
self.token = token
}
public func fetchMemberInfos() -> SignalProducer<Member, AuthenticatedClientError> {
return FetchMemberInfos()
.send(NSURLSession.sharedSession(), baseURL: AuthenticatedClient.baseURL, key: key, token: token)
.flatMapError {
return SignalProducer(error: AuthenticatedClientError.InternalError(actualError: $0))
}
}
public func fetchShows() -> SignalProducer<Show, AuthenticatedClientError> {
let request = FetchMemberInfos().send(NSURLSession.sharedSession(), baseURL: AuthenticatedClient.baseURL, key: key, token: token)
let showsSignalProducer = request.flatMap(.Latest) { (member) -> SignalProducer<Show, RequestError> in
return SignalProducer(values: member.shows)
}
return showsSignalProducer.flatMapError {
return SignalProducer(error: AuthenticatedClientError.InternalError(actualError: $0))
}
}
public func fetchEpisodes(id: Int) -> SignalProducer<Episode, AuthenticatedClientError> {
let request = FetchEpisodes(id: id)
.send(NSURLSession.sharedSession(), baseURL: AuthenticatedClient.baseURL, key: key, token: token)
return request.flatMapError {
return SignalProducer(error: AuthenticatedClientError.InternalError(actualError: $0))
}
}
public func fetchImageForEpisode(id: Int, width: Int, height: Int) -> SignalProducer<UIImage, AuthenticatedClientError> {
return FetchEpisodePicture(id: id, width: width, height: height)
.send(NSURLSession.sharedSession(), baseURL: AuthenticatedClient.baseURL, key: key, token: token)
.flatMapError {
return SignalProducer(error: AuthenticatedClientError.InternalError(actualError: $0))
}
}
}
| e2d7bce6c1f661f062df3bcb2c99ef21 | 37.603175 | 137 | 0.676398 | false | false | false | false |
JGiola/swift-package-manager | refs/heads/master | Sources/Basic/ProcessSet.swift | apache-2.0 | 3 | /*
This source file is part of the Swift.org open source project
Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
Licensed under Apache License v2.0 with Runtime Library Exception
See http://swift.org/LICENSE.txt for license information
See http://swift.org/CONTRIBUTORS.txt for Swift project authors
*/
import Dispatch
import Foundation
public enum ProcessSetError: Swift.Error {
/// The process group was cancelled and doesn't allow adding more processes.
case cancelled
}
/// A process set is a small wrapper for collection of processes.
///
/// This class is thread safe.
public final class ProcessSet {
/// Array to hold the processes.
private var processes: Set<Process> = []
/// Queue to mutate internal states of the process group.
private let serialQueue = DispatchQueue(label: "org.swift.swiftpm.process-set")
/// If the process group was asked to cancel all active processes.
private var cancelled = false
/// The timeout (in seconds) after which the processes should be killed if they don't respond to SIGINT.
public let killTimeout: Double
/// Condition to block kill thread until timeout.
private var killingCondition = Condition()
/// Boolean predicate for killing condition.
private var shouldKill = false
/// Create a process set.
public init(killTimeout: Double = 5) {
self.killTimeout = killTimeout
}
/// Add a process to the process set. This method will throw if the process set is terminated using the terminate()
/// method.
///
/// Call remove() method to remove the process from set once it has terminated.
///
/// - Parameters:
/// - process: The process to add.
/// - Throws: ProcessGroupError
public func add(_ process: Basic.Process) throws {
return try serialQueue.sync {
guard !cancelled else {
throw ProcessSetError.cancelled
}
self.processes.insert(process)
}
}
/// Terminate all the processes. This method blocks until all processes in the set are terminated.
///
/// A process set cannot be used once it has been asked to terminate.
public func terminate() {
// Mark a process set as cancelled.
serialQueue.sync {
cancelled = true
}
// Interrupt all processes.
signalAll(SIGINT)
// Create a thread that will kill all processes after a timeout.
let thread = Basic.Thread {
// Compute the timeout date.
let timeout = Date() + self.killTimeout
// Block until we timeout or notification.
self.killingCondition.whileLocked {
while !self.shouldKill {
// Block until timeout expires.
let timeLimitReached = !self.killingCondition.wait(until: timeout)
// Set should kill to true if time limit was reached.
if timeLimitReached {
self.shouldKill = true
}
}
}
// Send kill signal to all processes.
self.signalAll(SIGKILL)
}
thread.start()
// Wait until all processes terminate and notify the kill thread
// if everyone exited to avoid waiting till timeout.
for process in self.processes {
_ = try? process.waitUntilExit()
}
killingCondition.whileLocked {
shouldKill = true
killingCondition.signal()
}
// Join the kill thread so we don't exit before everything terminates.
thread.join()
}
/// Sends signal to all processes in the set.
private func signalAll(_ signal: Int32) {
serialQueue.sync {
// Signal all active processes.
for process in self.processes {
process.signal(signal)
}
}
}
}
| 7543f2fd45b0d93b88d95a1751a36d06 | 32.083333 | 119 | 0.617632 | false | false | false | false |
malaonline/iOS | refs/heads/master | mala-ios/Model/Course/StudentCourseModel.swift | mit | 1 | //
// StudentCourseModel.swift
// mala-ios
//
// Created by 王新宇 on 3/17/16.
// Copyright © 2016 Mala Online. All rights reserved.
//
import UIKit
open class StudentCourseModel: BaseObjectModel {
// MARK: - Property
/// 上课时间
var start: TimeInterval = 0
/// 下课时间
var end: TimeInterval = 0
/// 学科
var subject: String = ""
/// 年级
var grade: String = ""
/// 上课地点
var school: String = ""
/// 上课地点 - 详细地址
var schoolAddress: String = ""
/// 是否完成标记
var isPassed: Bool = false
/// 授课老师
var teacher: TeacherModel?
/// 课程评价
var comment: CommentModel?
/// 是否过期标记
var isExpired: Bool = false
/// 主讲老师
var lecturer: TeacherModel?
/// 是否时直播课程标记
var isLiveCourse: Bool? = false
// MARK: Convenience Property
/// 是否评价标记
var isCommented: Bool? = false
/// 日期对象
var date: Date {
get {
return Date(timeIntervalSince1970: end)
}
}
/// 课程状态
var status: CourseStatus {
get {
// 设置课程状态
if date.isToday && !isPassed {
return .Today
}else if date.isEarlierThanOrEqual(to: Date()) || isPassed {
return .Past
}else {
return .Future
}
}
}
var attrAddressString: NSMutableAttributedString {
get {
return makeAddressAttrString(school, schoolAddress)
}
}
// MARK: - Constructed
override init() {
super.init()
}
required public init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override init(dict: [String: Any]) {
super.init(dict: dict)
setValuesForKeys(dict)
}
// MARK: - Override
open override func setValue(_ value: Any?, forKey key: String) {
if key == "is_passed", let bool = value as? Bool {
isPassed = bool
return
}
if key == "is_expired", let bool = value as? Bool {
isExpired = bool
return
}
if key == "is_live", let bool = value as? Bool {
isLiveCourse = bool
return
}
if key == "teacher", let dict = value as? [String: AnyObject] {
teacher = TeacherModel(dict: dict)
return
}
if key == "comment", let dict = value as? [String: AnyObject] {
comment = CommentModel(dict: dict)
return
}
if key == "lecturer", let dict = value as? [String: AnyObject] {
lecturer = TeacherModel(dict: dict)
return
}
if key == "school_address", let string = value as? String {
schoolAddress = string
return
}
super.setValue(value, forKey: key)
}
override open func setValue(_ value: Any?, forUndefinedKey key: String) {
println("StudentCourseModel - Set for UndefinedKey: \(key)")
}
}
| 1fbd8eb3bbb6cfde6bdfff51a30d44bc | 22.014815 | 77 | 0.511104 | false | false | false | false |
q231950/appwatch | refs/heads/master | AppWatchLogic/AppWatchLogic/TimeBox.swift | mit | 1 | //
// TimeBox.swift
// AppWatch
//
// Created by Martin Kim Dung-Pham on 15.08.15.
// Copyright © 2015 Martin Kim Dung-Pham. All rights reserved.
//
import Foundation
public class TimeBox {
public var startDate = NSDate()
public var endDate = NSDate()
public init() {
}
init(withString string: String) {
let components = string.componentsSeparatedByString("\t")
if 2 <= components.count {
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss ZZZ"
startDate = dateFormatter.dateFromString(components[0] as String)!
endDate = dateFormatter.dateFromString(components[1] as String)!
}
}
} | 104c9cf11113ff49866ad22d4a1919f6 | 24.5 | 78 | 0.603403 | false | false | false | false |
SSamanta/SSHTTPClient | refs/heads/master | SSHTTPClient/SSHTTPClient/SSHTTPClient.swift | mit | 1 | //
// SSHTTPClient.swift
// SSHTTPClient
//
// Created by Susim on 11/17/14.
// Copyright (c) 2014 Susim. All rights reserved.
//
import Foundation
public typealias SSHTTPResponseHandler = (_ responseObject : Any? , _ error : Error?) -> Void
open class SSHTTPClient : NSObject {
var httpMethod,url,httpBody: String?
var headerFieldsAndValues : [String:String]?
//Initializer Method with url string , method, body , header field and values
public init(url:String?, method:String?, httpBody: String?, headerFieldsAndValues: [String:String]?) {
self.url = url
self.httpMethod = method
self.httpBody = httpBody
self.headerFieldsAndValues = headerFieldsAndValues
}
//Get formatted JSON
public func getJsonData(_ httpResponseHandler : @escaping SSHTTPResponseHandler) {
getResponseData { (data, error) in
if error != nil {
httpResponseHandler(nil,error)
}else if let datObject = data as? Data {
let json = try? JSONSerialization.jsonObject(with: datObject, options: [])
httpResponseHandler(json,nil)
}
}
}
//Get Response in Data format
public func getResponseData(_ httpResponseHandler : @escaping SSHTTPResponseHandler) {
var request: URLRequest?
if let urlString = self.url {
if let url = URL(string: urlString) {
request = URLRequest(url: url)
}
}
if let method = self.httpMethod {
request?.httpMethod = method
}
if let headerKeyValues = self.headerFieldsAndValues {
for key in headerKeyValues.keys {
request?.setValue(headerKeyValues[key] , forHTTPHeaderField: key)
}
}
if let body = self.httpBody {
request?.httpBody = body.data(using: String.Encoding.utf8)
}
if let requestObject = request {
let session = URLSession.shared
let task = session.dataTask(with: requestObject, completionHandler: { (data, response, error) in
if error != nil {
httpResponseHandler(nil,error)
}else {
httpResponseHandler (data as Any?, nil)
}
})
task.resume()
}
}
//Cancel Request
open func cancelRequest()->Void{
let session = URLSession.shared
session.invalidateAndCancel()
}
}
| 26083c5c21c5afd87abb029bc86fe392 | 33.424658 | 108 | 0.590131 | false | false | false | false |
itsaboutcode/WordPress-iOS | refs/heads/develop | WordPress/Classes/ViewRelated/Stats/Charts/Charts+AxisFormatters.swift | gpl-2.0 | 1 |
import Foundation
import Charts
// MARK: - HorizontalAxisFormatter
/// This formatter requires some explanation. The framework does not necessarily respond well to large values, and/or
/// large ranges of values as originally encountered using the naive TimeInterval representation of current dates.
/// The side effect is that bars appear quite narrow.
///
/// The bug is documented in the following issues:
/// https://github.com/danielgindi/Charts/issues/1716
/// https://github.com/danielgindi/Charts/issues/1742
/// https://github.com/danielgindi/Charts/issues/2410
/// https://github.com/danielgindi/Charts/issues/2680
///
/// The workaround employed here (recommended in 2410 above) relies on the time series data being ordered, and simply
/// transforms the adjusted values by the time interval associated with the first date in the series.
///
class HorizontalAxisFormatter: IAxisValueFormatter {
// MARK: Properties
private let initialDateInterval: TimeInterval
private let period: StatsPeriodUnit
private let periodHelper = StatsPeriodHelper()
private lazy var formatter = DateFormatter()
// MARK: HorizontalAxisFormatter
init(initialDateInterval: TimeInterval, period: StatsPeriodUnit = .day) {
self.initialDateInterval = initialDateInterval
self.period = period
}
// MARK: IAxisValueFormatter
func stringForValue(_ value: Double, axis: AxisBase?) -> String {
updateFormatterTemplate()
let adjustedValue = initialDateInterval + (value < 0 ? 0 : value)
let date = Date(timeIntervalSince1970: adjustedValue)
switch period {
case .week:
return formattedDate(forWeekContaining: date)
default:
return formatter.string(from: date)
}
}
private func updateFormatterTemplate() {
formatter.setLocalizedDateFormatFromTemplate(period.dateFormatTemplate)
}
private func formattedDate(forWeekContaining date: Date) -> String {
let week = periodHelper.weekIncludingDate(date)
guard let weekStart = week?.weekStart, let weekEnd = week?.weekEnd else {
return ""
}
return "\(formatter.string(from: weekStart)) to \(formatter.string(from: weekEnd))"
}
}
// MARK: - VerticalAxisFormatter
class VerticalAxisFormatter: IAxisValueFormatter {
// MARK: Properties
private let largeValueFormatter = LargeValueFormatter()
// MARK: IAxisValueFormatter
func stringForValue(_ value: Double, axis: AxisBase?) -> String {
if value <= 0.0 {
return "0"
}
return largeValueFormatter.stringForValue(value, axis: axis)
}
// Matches WPAndroid behavior to produce neater rounded values on
// the vertical axis.
static func roundUpAxisMaximum(_ input: Double) -> Double {
if input > 100 {
return roundUpAxisMaximum(input / 10) * 10
} else {
for i in 1..<25 {
let limit = Double(4 * i)
if input < limit {
return limit
}
}
return Double(100)
}
}
}
| 9e3122c199212fada02c98018cf474a2 | 30.465347 | 117 | 0.662996 | false | false | false | false |
things-nyc/mapthethings-ios | refs/heads/master | MapTheThings/AccountViewController.swift | mit | 1 | //
// AccountViewController.swift
// MapTheThings
//
// Created by Frank on 2017/1/30.
// Copyright © 2017 The Things Network New York. All rights reserved.
//
import UIKit
import Crashlytics
import ReactiveSwift
class LoggedInViewController : UITableViewController {
var stateDisposer: Disposable?
@IBOutlet weak var provider_logo: UIImageView!
@IBOutlet weak var provider: UILabel!
@IBOutlet weak var user_id: UILabel!
@IBOutlet weak var user_name: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
var first = true
self.stateDisposer = appStateObservable.observe(on: QueueScheduler.main)
.observeValues({ (old, new) in
if let auth = new.authState, first || old.authState==nil {
self.provider.text = auth.provider.capitalized
self.user_name.text = auth.user_name
self.user_id.text = auth.user_id
first = false
}
})
}
@IBAction func logout(_ sender: UIButton) {
Answers.logCustomEvent(withName: "Logout", customAttributes: nil)
updateAppState({ (old) -> AppState in
var state = old
state.authState = nil
return state
})
}
}
class LoginViewController : UITableViewController {
@IBAction func login(_ sender: UIButton) {
Answers.logCustomEvent(withName: "Login", customAttributes: nil)
let auth = Authentication()
auth.authorize(viewController: self)
}
}
class AccountViewController: AppStateUIViewController {
@IBOutlet weak var loggedInPanel: UIView!
@IBOutlet weak var loginPanel: UIView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func renderAppState(_ oldState: AppState, state: AppState) {
let loggedIn = (state.authState != nil)
self.loginPanel.isHidden = loggedIn
self.loggedInPanel.isHidden = !loggedIn
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| 2bada50bf3680c83b9125b24953af9f3 | 29.705882 | 106 | 0.636782 | false | false | false | false |
ngageoint/anti-piracy-iOS-app | refs/heads/master | ASAM/AsamMapViewDelegate.swift | apache-2.0 | 1 | //
// AsamMapViewDelegate.swift
// anti-piracy-iOS-app
//
import Foundation
import MapKit
class AsamMapViewDelegate: NSObject, MKMapViewDelegate {
var delegate : AsamSelectDelegate!
let defaults = UserDefaults.standard
let offlineMap:OfflineMap = OfflineMap()
//Offline Map Polygons
func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
let polygonRenderer = MKPolygonRenderer(overlay: overlay);
if "ocean" == overlay.title! {
polygonRenderer.fillColor = UIColor(red: 127/255.0, green: 153/255.0, blue: 171/255.0, alpha: 1.0)
polygonRenderer.strokeColor = UIColor.clear
polygonRenderer.lineWidth = 0.0
} else {
polygonRenderer.fillColor = UIColor(red: 221/255.0, green: 221/255.0, blue: 221/255.0, alpha: 1.0)
polygonRenderer.strokeColor = UIColor.clear
polygonRenderer.lineWidth = 0.0
}
return polygonRenderer
}
func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView) {
mapView.deselectAnnotation(view.annotation, animated: false)
switch view.annotation {
case is MKClusterAnnotation:
let annotations = (view.annotation as! MKClusterAnnotation).memberAnnotations as! [Asam]
delegate.clusterSelected(asams: annotations)
default:
delegate.asamSelected(view.annotation as! Asam)
}
}
func mapView(_ mapView: MKMapView, regionDidChangeAnimated animated: Bool) {
//persisting map center and span so that the map will return to this location.
defaults.set(mapView.region.center.latitude, forKey: MapView.LATITUDE)
defaults.set(mapView.region.center.longitude, forKey: MapView.LONGITUDE)
defaults.set(mapView.region.span.latitudeDelta, forKey: MapView.LAT_DELTA)
defaults.set(mapView.region.span.latitudeDelta, forKey: MapView.LON_DELTA)
}
}
| c5b66147d3ee9126d9fe188f24912d1b | 37.923077 | 110 | 0.662549 | false | false | false | false |
narner/AudioKit | refs/heads/master | Examples/iOS/SequencerDemo/SequencerDemo/ViewController.swift | mit | 1 | //
// ViewController.swift
// SequencerDemo
//
// Created by Kanstantsin Linou on 6/30/16.
// Copyright © 2016 AudioKit. All rights reserved.
//
import AudioKit
import AudioKitUI
import UIKit
class ViewController: UIViewController {
@IBOutlet private var melodyButton: UIButton!
@IBOutlet private var bassButton: UIButton!
@IBOutlet private var snareButton: UIButton!
@IBOutlet private var tempoLabel: UILabel!
@IBOutlet private var tempoSlider: AKSlider!
let conductor = Conductor()
func setupUI() {
[melodyButton, bassButton, snareButton].forEach({
$0?.setTitleColor(UIColor.white, for: UIControlState())
$0?.setTitleColor(UIColor.lightGray, for: UIControlState.disabled)
})
tempoSlider.callback = updateTempo
tempoSlider.range = 40 ... 200
tempoSlider.value = 110
tempoSlider.format = "%0.1f BPM"
}
override func viewDidLoad() {
super.viewDidLoad()
setupUI()
conductor.setupTracks()
}
@IBAction func clearMelodySequence(_ sender: UIButton) {
conductor.clear(Sequence.melody)
melodyButton?.isEnabled = false
}
@IBAction func clearBassDrumSequence(_ sender: UIButton) {
conductor.clear(Sequence.bassDrum)
bassButton?.isEnabled = false
}
@IBAction func clearSnareDrumSequence(_ sender: UIButton) {
conductor.clear(Sequence.snareDrum)
snareButton?.isEnabled = false
}
@IBAction func clearSnareDrumGhostSequence(_ sender: UIButton) {
conductor.clear(Sequence.snareGhost)
}
@IBAction func generateMajorSequence(_ sender: UIButton) {
conductor.generateNewMelodicSequence(minor: false)
melodyButton?.isEnabled = true
}
@IBAction func generateMinorSequence(_ sender: UIButton) {
conductor.generateNewMelodicSequence(minor: true)
melodyButton?.isEnabled = true
}
@IBAction func generateBassDrumSequence(_ sender: UIButton) {
conductor.generateBassDrumSequence()
bassButton?.isEnabled = true
}
@IBAction func generateBassDrumHalfSequence(_ sender: UIButton) {
conductor.generateBassDrumSequence(2)
bassButton?.isEnabled = true
}
@IBAction func generateBassDrumQuarterSequence(_ sender: UIButton) {
conductor.generateBassDrumSequence(4)
bassButton?.isEnabled = true
}
@IBAction func generateSnareDrumSequence(_ sender: UIButton) {
conductor.generateSnareDrumSequence()
snareButton?.isEnabled = true
}
@IBAction func generateSnareDrumHalfSequence(_ sender: UIButton) {
conductor.generateSnareDrumSequence(2)
snareButton?.isEnabled = true
}
@IBAction func generateSnareDrumGhostSequence(_ sender: UIButton) {
conductor.generateSnareDrumGhostSequence()
snareButton?.isEnabled = true
}
@IBAction func generateSequence(_ sender: UIButton) {
conductor.generateSequence()
melodyButton?.isEnabled = true
bassButton?.isEnabled = true
snareButton?.isEnabled = true
}
func updateTempo(value: Double) {
conductor.currentTempo = value
}
}
| 7a45dfa7efd3c7253f60147fff2ddb80 | 28.740741 | 78 | 0.67746 | false | false | false | false |
infobip/mobile-messaging-sdk-ios | refs/heads/master | Classes/Vendor/Kingsfisher/CacheSerializer.swift | apache-2.0 | 1 | //
// CacheSerializer.swift
// Kingfisher
//
// Created by Wei Wang on 2016/09/02.
//
// Copyright (c) 2018 Wei Wang <[email protected]>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
/// An `CacheSerializer` would be used to convert some data to an image object for
/// retrieving from disk cache and vice versa for storing to disk cache.
internal protocol CacheSerializer {
/// Get the serialized data from a provided image
/// and optional original data for caching to disk.
///
///
/// - parameter image: The image needed to be serialized.
/// - parameter original: The original data which is just downloaded.
/// If the image is retrieved from cache instead of
/// downloaded, it will be `nil`.
///
/// - returns: A data which will be stored to cache, or `nil` when no valid
/// data could be serialized.
func data(with image: Image, original: Data?) -> Data?
/// Get an image deserialized from provided data.
///
/// - parameter data: The data from which an image should be deserialized.
/// - parameter options: Options for deserialization.
///
/// - returns: An image deserialized or `nil` when no valid image
/// could be deserialized.
func image(with data: Data, options: KingfisherOptionsInfo?) -> Image?
}
/// `DefaultCacheSerializer` is a basic `CacheSerializer` used in default cache of
/// Kingfisher. It could serialize and deserialize PNG, JEPG and GIF images. For
/// image other than these formats, a normalized `pngRepresentation` will be used.
internal struct DefaultCacheSerializer: CacheSerializer {
internal static let `default` = DefaultCacheSerializer()
private init() {}
internal func data(with image: Image, original: Data?) -> Data? {
let imageFormat = original?.kf.imageFormat ?? .unknown
let data: Data?
switch imageFormat {
case .PNG: data = image.kf.pngRepresentation()
case .JPEG: data = image.kf.jpegRepresentation(compressionQuality: 1.0)
case .GIF: data = image.kf.gifRepresentation()
case .unknown: data = original ?? image.kf.normalized.kf.pngRepresentation()
}
return data
}
internal func image(with data: Data, options: KingfisherOptionsInfo?) -> Image? {
let options = options ?? KingfisherEmptyOptionsInfo
return Kingfisher<Image>.image(
data: data,
scale: options.scaleFactor,
preloadAllAnimationData: options.preloadAllAnimationData,
onlyFirstFrame: options.onlyLoadFirstFrame)
}
}
| b795b0d1a9b25ad29dd605ffa9fc70f7 | 41.977011 | 85 | 0.681198 | false | false | false | false |
Xiomara7/bookiao-ios | refs/heads/master | bookiao-ios/AppDelegate.swift | mit | 1 |
//
// AppDelegate.swift
// test
//
// Created by Xiomara on 9/30/14.
// Copyright (c) 2014 UPRRP. All rights reserved.
//
import UIKit
import CoreData
import Crashlytics
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow!
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
Crashlytics.startWithAPIKey("060c9c8678ed200621af5e16e3937d3d31c777be")
self.window = UIWindow(frame: UIScreen.mainScreen().bounds)
let now = NSDate()
let dateFormatter = NSDateFormatter()
DataManager.sharedManager.date = dateFormatter.stringFromDate(now)
if let window = window {
var login = LoginViewController(nibName: nil, bundle: nil)
self.window.backgroundColor = UIColor.whiteColor()
self.window.rootViewController = login
self.window.makeKeyAndVisible()
}
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.uprrp.test" in the application's documents Application Support directory.
let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
return urls[urls.count-1] as NSURL
}()
lazy var managedObjectModel: NSManagedObjectModel = {
// The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model.
let modelURL = NSBundle.mainBundle().URLForResource("test", withExtension: "momd")!
return NSManagedObjectModel(contentsOfURL: modelURL)!
}()
lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = {
// The persistent store coordinator for the application. This implementation creates and return a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail.
// Create the coordinator and store
var coordinator: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("test.sqlite")
var error: NSError? = nil
var failureReason = "There was an error creating or loading the application's saved data."
if coordinator!.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil, error: &error) == nil {
coordinator = nil
// Report any error we got.
let dict = NSMutableDictionary()
dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data"
dict[NSLocalizedFailureReasonErrorKey] = failureReason
dict[NSUnderlyingErrorKey] = error
error = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
// Replace this with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(error), \(error!.userInfo)")
abort()
}
return coordinator
}()
lazy var managedObjectContext: NSManagedObjectContext? = {
// Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail.
let coordinator = self.persistentStoreCoordinator
if coordinator == nil {
return nil
}
var managedObjectContext = NSManagedObjectContext()
managedObjectContext.persistentStoreCoordinator = coordinator
return managedObjectContext
}()
// MARK: - Core Data Saving support
func saveContext () {
if let moc = self.managedObjectContext {
var error: NSError? = nil
if moc.hasChanges && !moc.save(&error) {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(error), \(error!.userInfo)")
abort()
}
}
}
}
| c596f1734346ba6d5e52be39e462fb14 | 52.31746 | 290 | 0.699911 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.