repo_name
stringlengths 6
91
| path
stringlengths 8
968
| copies
stringclasses 210
values | size
stringlengths 2
7
| content
stringlengths 61
1.01M
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6
99.8
| line_max
int64 12
1k
| alpha_frac
float64 0.3
0.91
| ratio
float64 2
9.89
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
TabletopAssistant/DiceKit | DiceKit/NegationExpression.swift | 1 | 1438 | //
// NegationExpression.swift
// DiceKit
//
// Created by Brentley Jones on 7/18/15.
// Copyright © 2015 Brentley Jones. All rights reserved.
//
import Foundation
public struct NegationExpression<BaseExpression: protocol<ExpressionType, Equatable>>: Equatable {
public let base: BaseExpression
public init(_ base: BaseExpression) {
self.base = base
}
}
// MARK: - ExpressionType
extension NegationExpression: ExpressionType {
public typealias Result = NegationExpressionResult<BaseExpression.Result>
public func evaluate() -> Result {
return Result(base.evaluate())
}
public var probabilityMass: ExpressionProbabilityMass {
return -base.probabilityMass
}
}
// MARK: - CustomStringConvertible
extension NegationExpression: CustomStringConvertible {
public var description: String {
return "-\(base)"
}
}
// MARK: - CustomDebugStringConvertible
extension NegationExpression: CustomDebugStringConvertible {
public var debugDescription: String {
return "-\(String(reflecting: base))"
}
}
// MARK: - Equatable
public func == <E>(lhs: NegationExpression<E>, rhs: NegationExpression<E>) -> Bool {
return lhs.base == rhs.base
}
// MARK: - Operators
public prefix func - <E: protocol<ExpressionType, Equatable>>(base: E) -> NegationExpression<E> {
return NegationExpression(base)
}
| apache-2.0 | 2a130e63186a1244fca35cbea43376a7 | 20.447761 | 98 | 0.679889 | 4.504702 | false | false | false | false |
SwiftKitz/Datez | Sources/Datez/Extensions/FoundationConversion/Calendar+Conversion.swift | 1 | 1985 | //
// Calendar+Conversion.swift
// Datez
//
// Created by Mazyad Alabduljaleel on 11/7/15.
// Copyright © 2015 kitz. All rights reserved.
//
import Foundation
extension Calendar {
func components(_ units: Set<Calendar.Component>, fromTimeInterval timeInterval: TimeInterval) -> DateComponents {
let baseDate = Date(timeIntervalSinceReferenceDate: 0)
return dateComponents(units, from: baseDate, to: baseDate + timeInterval)
}
}
public extension Calendar {
static let gregorian = Calendar(identifier: .gregorian)
static let buddhist = Calendar(identifier: .buddhist)
static let chinese = Calendar(identifier: .chinese)
static let coptic = Calendar(identifier: .coptic)
static let ethiopicAmeteMihret = Calendar(identifier: .ethiopicAmeteMihret)
static let ethiopicAmeteAlem = Calendar(identifier: .ethiopicAmeteAlem)
static let hebrew = Calendar(identifier: .hebrew)
static let iso8601 = Calendar(identifier: .iso8601)
static let indian = Calendar(identifier: .indian)
static let islamic = Calendar(identifier: .islamic)
static let islamicCivil = Calendar(identifier: .islamicCivil)
static let islamicTabular = Calendar(identifier: .islamicTabular)
static let islamicUmmAlQura = Calendar(identifier: .islamicUmmAlQura)
static let japanese = Calendar(identifier: .japanese)
static let persian = Calendar(identifier: .persian)
static let republicOfChina = Calendar(identifier: .republicOfChina)
}
public extension Calendar.Component {
static var all: Set<Calendar.Component> {
return [
.calendar, .day, .era, .hour, .minute, .month, .nanosecond, .quarter, .second,
.timeZone, .weekday, .weekdayOrdinal, .weekOfMonth, .weekOfYear, .year, .yearForWeekOfYear
]
}
}
| mit | 09ff11af8b45b442eb923ba4d281ce17 | 39.489796 | 118 | 0.657258 | 4.72381 | false | false | false | false |
k-o-d-e-n/CGLayout | Example/CGLayout/SecondViewController.swift | 1 | 8023 | //
// SecondViewController.swift
// CGLayout
//
// Created by Denis Koryttsev on 01/09/2017.
// Copyright © 2017 CocoaPods. All rights reserved.
//
import UIKit
import CGLayout
/// Example extending
extension Size {
static func stringSize(_ string: String?,
options: NSStringDrawingOptions = .usesLineFragmentOrigin,
attributes: [NSAttributedString.Key: Any],
context: NSStringDrawingContext? = nil) -> Size {
return .build(StringLayoutAnchor(string: string, options: options, attributes: attributes, context: context))
}
}
extension Center {
static var centerTop: Center { return .build(CenterTop()) }
private struct CenterTop: RectBasedConstraint {
func formConstrain(sourceRect: inout CGRect, by rect: CGRect) {
sourceRect.origin.x = rect.midX - (sourceRect.width / 2)
sourceRect.origin.y = rect.midY
}
}
}
public class SecondViewController: UIViewController {
@IBOutlet weak var logoImageView: UIImageView!
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var presentationLabel: UILabel!
@IBOutlet weak var rainImageView: UIImageView!
@IBOutlet weak var rainLabel: UILabel!
@IBOutlet weak var distanceLabel: UILabel!
@IBOutlet weak var weatherImageView: UIImageView!
@IBOutlet weak var weatherLabel: UILabel!
weak var separator1Layer: CALayer!
weak var separator2Layer: CALayer!
lazy var layoutScheme: LayoutScheme = buildScheme()
var portraitSnapshot: LayoutSnapshotProtocol!
var landscapeSnapshot: LayoutSnapshotProtocol!
override public func viewDidLoad() {
super.viewDidLoad()
let separator1 = CALayer(backgroundColor: .black)
view.layer.addSublayer(separator1)
separator1Layer = separator1
let separator2 = CALayer(backgroundColor: .black)
view.layer.addSublayer(separator2)
separator2Layer = separator2
#if os(iOS)
let bounds = view.bounds
let isLandscape = UIDevice.current.orientation.isLandscape
let scheme = self.layoutScheme
DispatchQueue.global(qos: .background).async {
let portraitSnapshot = scheme.snapshot(for: isLandscape ? CGRect(x: 0, y: 0, width: bounds.height, height: bounds.width) : bounds)
let landscapeSnapshot = scheme.snapshot(for: isLandscape ? bounds : CGRect(x: 0, y: 0, width: bounds.height, height: bounds.width))
DispatchQueue.main.sync {
self.portraitSnapshot = portraitSnapshot
self.landscapeSnapshot = landscapeSnapshot
scheme.apply(snapshot: UIDevice.current.orientation.isLandscape ? landscapeSnapshot : portraitSnapshot)
}
}
#endif
}
override public func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
// layout directly
// layoutScheme.layout()
// layout in background
// let bounds = view.bounds
// DispatchQueue.global(qos: .background).async {
// let snapshot = self.layoutScheme.snapshot(for: bounds)
// DispatchQueue.main.sync {
// self.layoutScheme.apply(snapshot: snapshot)
// }
// }
// cached layout
#if os(iOS)
if UIDevice.current.orientation.isPortrait, let snapshot = portraitSnapshot {
layoutScheme.apply(snapshot: snapshot)
} else if UIDevice.current.orientation.isLandscape, let snapshot = landscapeSnapshot {
layoutScheme.apply(snapshot: snapshot)
} else {
layoutScheme.layout(in: view.layoutBounds)
}
#endif
#if os(tvOS)
layoutScheme.layout()
#endif
}
func buildScheme() -> LayoutScheme {
let topLayoutGuideConstraint: LayoutConstraint
if #available(iOS 11.0, tvOS 11.0, *) {
topLayoutGuideConstraint = view.safeAreaLayoutGuide.layoutConstraint(for: [.top(.limit(on: .inner))])
} else {
topLayoutGuideConstraint = navigationController!.navigationBar.layoutConstraint(for: [.bottom(.limit(on: .outer))])
}
let bottomLayoutGuideConstraint: LayoutConstraint
if #available(iOS 11.0, tvOS 11.0, *) {
bottomLayoutGuideConstraint = view.safeAreaLayoutGuide.layoutConstraint(for: [.bottom(.limit(on: .inner))])
} else {
bottomLayoutGuideConstraint = view.layoutConstraint(for: [.bottom(.limit(on: .inner))])
}
return LayoutScheme(blocks: [
distanceLabel.layoutBlock(
with: Layout(x: .center(), y: .bottom(50), width: .fixed(70), height: .fixed(30)),
constraints: [bottomLayoutGuideConstraint]
),
separator1Layer.layoutBlock(
with: Layout(x: .trailing(25), y: .top(), width: .fixed(1), height: .scaled(1)),
constraints: [distanceLabel.layoutConstraint(for: [.leading(.limit(on: .outer)), .top(.limit(on: .inner)), .size(.height())])]
),
separator2Layer.layoutBlock(
with: Layout(x: .leading(25), y: .bottom(), width: .fixed(1), height: .scaled(1)),
constraints: [distanceLabel.layoutConstraint(for: [.size(.height()), .trailing(.limit(on: .outer)), .bottom(.align(by: .inner))])]
),
weatherImageView.layoutBlock(
with: Layout(x: .leading(20), y: .top(), width: .fixed(30), height: .fixed(30)),
constraints: [separator2Layer.layoutConstraint(for: [.trailing(.limit(on: .outer)), .top(.limit(on: .inner))])]
),
weatherLabel.layoutBlock(
constraints: [
weatherImageView.layoutConstraint(for: [.top(.limit(on: .inner)), .trailing(.limit(on: .outer)), .size(.height())]),
weatherLabel.adjustLayoutConstraint(for: [.width()], alignment: .init(horizontal: .leading(10), vertical: .top()))
]
),
rainLabel.layoutBlock(
with: Layout(x: .trailing(20), y: .top(), width: .scaled(1), height: .fixed(30)),
constraints: [
rainLabel.adjustLayoutConstraint(for: [.width()]),
separator1Layer.layoutConstraint(for: [.top(.limit(on: .inner)), .leading(.align(by: .outer))])
]
),
rainImageView.layoutBlock(
with: Layout(x: .trailing(10), y: .top(), width: .fixed(30), height: .fixed(30)),
constraints: [rainLabel.layoutConstraint(for: [.leading(.limit(on: .outer)), .top(.limit(on: .inner))])]
),
logoImageView.layoutBlock(
with: Layout(x: .center(), y: .top(80), width: .fixed(70), height: .fixed(70)),
constraints: [topLayoutGuideConstraint]
),
/// example including other scheme to top level scheme
LayoutScheme(blocks: [
titleLabel.layoutBlock(
with: Layout(x: .center(), y: .top(5), width: .scaled(1), height: .fixed(120)),
constraints: [logoImageView.layoutConstraint(for: [.bottom(.limit(on: .outer))])]
),
nameLabel.layoutBlock(with: Layout(x: .center(), y: .center(20), width: .scaled(1), height: .fixed(30))),
presentationLabel.layoutBlock(
with: Layout(x: .center(), y: .top(20), width: .equal, height: .equal),
constraints: [
nameLabel.layoutConstraint(for: [.bottom(.limit(on: .outer))]),
presentationLabel.adjustLayoutConstraint(for: [.height()])
]
)
])
])
}
}
extension CALayer {
convenience init(backgroundColor: UIColor) {
self.init()
self.backgroundColor = backgroundColor.cgColor
}
}
| mit | 6d368ca6216bee75fc61d6715cb61ba0 | 43.566667 | 146 | 0.598853 | 4.655833 | false | false | false | false |
wxlpp/GithubSearch | GithubSearch/GithubSearch/UI/ViewModel/UserTrackerModel.swift | 1 | 2209 | //
// UserModel.swift
// GithubSearch
//
// Created by wxlpp on 2017/5/21.
// Copyright © 2017年 wxlpp. All rights reserved.
//
import Foundation
import Moya
import Moya_SwiftyJSONMapper
import RxSwift
import PINCache
struct UserListModel {
var cellModels: [UserCellModel]!
var totalCount = 0
}
struct UserTrackerModel {
let provider: RxMoyaProvider<GitHub>
static let shar = UserTrackerModel(provider: github)
func search(username: String,_ page: Int = 0) -> Observable<UserListModel> {
return provider.request(.search(username: username, page: page)).retry(3).map(to: SearchUserResponse.self).map { (r) -> UserListModel in
var listModel = UserListModel()
listModel.totalCount = r.totalCount
listModel.cellModels = r.items.map({ (item) -> UserCellModel in
let model = UserCellModel()
model.loginId = NSNumber(integerLiteral: item.id)
model.avatarPath = item.avatarUrl
model.languageStr = ""
model.name = item.login
return model
})
return listModel
}
}
func getLanguage(for username: String) -> Observable<String> {
if let language = PINCache.shared.object(forKey: username) as! String? {
return Observable<String>.create({ (observer) -> Disposable in
observer.on(.next(language))
observer.on(.completed)
return Disposables.create()
})
}
return provider.request(.repos(username: username)).map(to: [UserReposResponse.self]).map({ (repos) -> String in
var countDic = [String: Int]()
repos.forEach({ r in
if let language = r.language {
countDic[language] = (countDic[language] ?? 0) + 1
}
})
countDic.removeValue(forKey: "")
let ret = countDic.sorted(by: { (dic1, dic2) -> Bool in
dic1.value > dic2.value
})
let str = ret.count > 0 ? ret[0].key : ""
PINCache.shared.setObject(str, forKey: username)
return str
})
}
}
| mit | 8461d135e8ecca211b0ed880c0460c52 | 34.015873 | 144 | 0.574796 | 4.376984 | false | false | false | false |
mattrajca/swift-corelibs-foundation | Foundation/NSCFString.swift | 4 | 9176 | // 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
internal class _NSCFString : NSMutableString {
required init(characters: UnsafePointer<unichar>, length: Int) {
fatalError()
}
required init?(coder aDecoder: NSCoder) {
fatalError()
}
required init(extendedGraphemeClusterLiteral value: StaticString) {
fatalError()
}
required init(stringLiteral value: StaticString) {
fatalError()
}
required init(capacity: Int) {
fatalError()
}
required init(string aString: String) {
fatalError()
}
deinit {
_CFDeinit(self)
_CFZeroUnsafeIvars(&_storage)
}
override var length: Int {
return CFStringGetLength(unsafeBitCast(self, to: CFString.self))
}
override func character(at index: Int) -> unichar {
return CFStringGetCharacterAtIndex(unsafeBitCast(self, to: CFString.self), index)
}
override func replaceCharacters(in range: NSRange, with aString: String) {
CFStringReplace(unsafeBitCast(self, to: CFMutableString.self), CFRangeMake(range.location, range.length), aString._cfObject)
}
override var classForCoder: AnyClass {
return NSMutableString.self
}
}
internal final class _NSCFConstantString : _NSCFString {
internal var _ptr : UnsafePointer<UInt8> {
// FIXME: Split expression as a work-around for slow type
// checking (tracked by SR-5322).
let offTemp1 = MemoryLayout<OpaquePointer>.size + MemoryLayout<Int32>.size
let offTemp2 = MemoryLayout<Int32>.size + MemoryLayout<_CFInfo>.size
let offset = offTemp1 + offTemp2
let ptr = Unmanaged.passUnretained(self).toOpaque()
return ptr.load(fromByteOffset: offset, as: UnsafePointer<UInt8>.self)
}
private var _lenOffset : Int {
// FIXME: Split expression as a work-around for slow type
// checking (tracked by SR-5322).
let offTemp1 = MemoryLayout<OpaquePointer>.size + MemoryLayout<Int32>.size
let offTemp2 = MemoryLayout<Int32>.size + MemoryLayout<_CFInfo>.size
return offTemp1 + offTemp2 + MemoryLayout<UnsafePointer<UInt8>>.size
}
private var _lenPtr : UnsafeMutableRawPointer {
return Unmanaged.passUnretained(self).toOpaque()
}
#if arch(s390x)
internal var _length : UInt64 {
return _lenPtr.load(fromByteOffset: _lenOffset, as: UInt64.self)
}
#else
internal var _length : UInt32 {
return _lenPtr.load(fromByteOffset: _lenOffset, as: UInt32.self)
}
#endif
required init(characters: UnsafePointer<unichar>, length: Int) {
fatalError()
}
required init?(coder aDecoder: NSCoder) {
fatalError()
}
required init(extendedGraphemeClusterLiteral value: StaticString) {
fatalError()
}
required init(stringLiteral value: StaticString) {
fatalError()
}
required init(capacity: Int) {
fatalError()
}
required init(string aString: String) {
fatalError("Constant strings cannot be constructed in code")
}
deinit {
fatalError("Constant strings cannot be deallocated")
}
override var length: Int {
return Int(_length)
}
override func character(at index: Int) -> unichar {
return unichar(_ptr[index])
}
override func replaceCharacters(in range: NSRange, with aString: String) {
fatalError()
}
override var classForCoder: AnyClass {
return NSString.self
}
}
internal func _CFSwiftStringGetLength(_ string: AnyObject) -> CFIndex {
return (string as! NSString).length
}
internal func _CFSwiftStringGetCharacterAtIndex(_ str: AnyObject, index: CFIndex) -> UniChar {
return (str as! NSString).character(at: index)
}
internal func _CFSwiftStringGetCharacters(_ str: AnyObject, range: CFRange, buffer: UnsafeMutablePointer<UniChar>) {
(str as! NSString).getCharacters(buffer, range: NSRange(location: range.location, length: range.length))
}
internal func _CFSwiftStringGetBytes(_ str: AnyObject, encoding: CFStringEncoding, range: CFRange, buffer: UnsafeMutablePointer<UInt8>?, maxBufLen: CFIndex, usedBufLen: UnsafeMutablePointer<CFIndex>?) -> CFIndex {
let convertedLength: CFIndex
switch encoding {
// TODO: Don't treat many encodings like they are UTF8
case CFStringEncoding(kCFStringEncodingUTF8), CFStringEncoding(kCFStringEncodingISOLatin1), CFStringEncoding(kCFStringEncodingMacRoman), CFStringEncoding(kCFStringEncodingASCII), CFStringEncoding(kCFStringEncodingNonLossyASCII):
let encodingView = (str as! NSString).substring(with: NSRange(range)).utf8
if let buffer = buffer {
for (idx, character) in encodingView.enumerated() {
buffer.advanced(by: idx).initialize(to: character)
}
}
usedBufLen?.pointee = encodingView.count
convertedLength = encodingView.count
case CFStringEncoding(kCFStringEncodingUTF16):
let encodingView = (str as! NSString)._swiftObject.utf16
let start = encodingView.startIndex
if let buffer = buffer {
for idx in 0..<range.length {
// Since character is 2 bytes but the buffer is in term of 1 byte values, we have to split it up
let character = encodingView[encodingView.index(start, offsetBy: idx + range.location)]
#if _endian(big)
let byte0 = UInt8((character >> 8) & 0x00ff)
let byte1 = UInt8(character & 0x00ff)
#else
let byte0 = UInt8(character & 0x00ff)
let byte1 = UInt8((character >> 8) & 0x00ff)
#endif
buffer.advanced(by: idx * 2).initialize(to: byte0)
buffer.advanced(by: (idx * 2) + 1).initialize(to: byte1)
}
}
// Every character was 2 bytes
usedBufLen?.pointee = range.length * 2
convertedLength = range.length
default:
fatalError("Attempted to get bytes of a Swift string using an unsupported encoding")
}
return convertedLength
}
internal func _CFSwiftStringCreateWithSubstring(_ str: AnyObject, range: CFRange) -> Unmanaged<AnyObject> {
return Unmanaged<AnyObject>.passRetained((str as! NSString).substring(with: NSRange(location: range.location, length: range.length))._nsObject)
}
internal func _CFSwiftStringCreateCopy(_ str: AnyObject) -> Unmanaged<AnyObject> {
return Unmanaged<AnyObject>.passRetained((str as! NSString).copy() as! NSObject)
}
internal func _CFSwiftStringCreateMutableCopy(_ str: AnyObject) -> Unmanaged<AnyObject> {
return Unmanaged<AnyObject>.passRetained((str as! NSString).mutableCopy() as! NSObject)
}
internal func _CFSwiftStringFastCStringContents(_ str: AnyObject, _ nullTerminated: Bool) -> UnsafePointer<Int8>? {
return (str as! NSString)._fastCStringContents(nullTerminated)
}
internal func _CFSwiftStringFastContents(_ str: AnyObject) -> UnsafePointer<UniChar>? {
return (str as! NSString)._fastContents
}
internal func _CFSwiftStringGetCString(_ str: AnyObject, buffer: UnsafeMutablePointer<Int8>, maxLength: Int, encoding: CFStringEncoding) -> Bool {
return (str as! NSString).getCString(buffer, maxLength: maxLength, encoding: CFStringConvertEncodingToNSStringEncoding(encoding))
}
internal func _CFSwiftStringIsUnicode(_ str: AnyObject) -> Bool {
return (str as! NSString)._encodingCantBeStoredInEightBitCFString
}
internal func _CFSwiftStringInsert(_ str: AnyObject, index: CFIndex, inserted: AnyObject) {
(str as! NSMutableString).insert((inserted as! NSString)._swiftObject, at: index)
}
internal func _CFSwiftStringDelete(_ str: AnyObject, range: CFRange) {
(str as! NSMutableString).deleteCharacters(in: NSRange(location: range.location, length: range.length))
}
internal func _CFSwiftStringReplace(_ str: AnyObject, range: CFRange, replacement: AnyObject) {
(str as! NSMutableString).replaceCharacters(in: NSRange(location: range.location, length: range.length), with: (replacement as! NSString)._swiftObject)
}
internal func _CFSwiftStringReplaceAll(_ str: AnyObject, replacement: AnyObject) {
(str as! NSMutableString).setString((replacement as! NSString)._swiftObject)
}
internal func _CFSwiftStringAppend(_ str: AnyObject, appended: AnyObject) {
(str as! NSMutableString).append((appended as! NSString)._swiftObject)
}
internal func _CFSwiftStringAppendCharacters(_ str: AnyObject, chars: UnsafePointer<UniChar>, length: CFIndex) {
(str as! NSMutableString).appendCharacters(chars, length: length)
}
internal func _CFSwiftStringAppendCString(_ str: AnyObject, chars: UnsafePointer<Int8>, length: CFIndex) {
(str as! NSMutableString)._cfAppendCString(chars, length: length)
}
| apache-2.0 | fd53a90b226e07f3e9067ae7e8674e62 | 35.851406 | 232 | 0.689298 | 4.581128 | false | false | false | false |
duming91/Hear-You | Hear You/Extensions/NSURLRequest+cURL.swift | 1 | 3847 | //
// NSURLRequest+cURL.swift
// Hello
//
// Created by 董亚珣 on 16/3/25.
// Copyright © 2016年 snow. All rights reserved.
//
import Foundation
public extension NSURLRequest {
public var cURLCommandLine: String {
get {
return cURLCommandLineWithSession(nil)
}
}
public func cURLCommandLineWithSession(session: NSURLSession?, credential: NSURLCredential? = nil) -> String {
var components = ["\ncurl -i"]
if let HTTPMethod = HTTPMethod where HTTPMethod != "GET" {
components.append("-X \(HTTPMethod)")
}
if let URLString = URL?.absoluteString {
components.append("\"\(URLString)\"")
}
if let credentialStorage = session?.configuration.URLCredentialStorage {
if let host = URL?.host, scheme = URL?.scheme {
let port = URL?.port?.integerValue ?? 0
let protectionSpace = NSURLProtectionSpace(
host: host,
port: port,
protocol: scheme,
realm: host,
authenticationMethod: NSURLAuthenticationMethodHTTPBasic
)
if let credentials = credentialStorage.credentialsForProtectionSpace(protectionSpace)?.values {
for credential in credentials {
if let user = credential.user, password = credential.password {
components.append("-u \(user):\(password)")
}
}
} else {
if let user = credential?.user, password = credential?.password {
components.append("-u \(user):\(password)")
}
}
}
}
if let session = session, URL = URL {
if session.configuration.HTTPShouldSetCookies {
if let
cookieStorage = session.configuration.HTTPCookieStorage,
cookies = cookieStorage.cookiesForURL(URL) where !cookies.isEmpty {
let string = cookies.reduce("") { $0 + "\($1.name)=\($1.value ?? String());" }
components.append("-b \"\(string.substringToIndex(string.endIndex.predecessor()))\"")
}
}
}
if let headerFields = allHTTPHeaderFields {
for (field, value) in headerFields {
switch field {
case "Cookie":
continue
default:
let escapedValue = value.stringByReplacingOccurrencesOfString("\"", withString: "\\\"")
components.append("-H \"\(field): \(escapedValue)\"")
}
}
}
if let additionalHeaders = session?.configuration.HTTPAdditionalHeaders as? [String: String] {
for (field, value) in additionalHeaders {
switch field {
case "Cookie":
continue
default:
let escapedValue = value.stringByReplacingOccurrencesOfString("\"", withString: "\\\"")
components.append("-H \"\(field): \(escapedValue)\"")
}
}
}
if let HTTPBody = HTTPBody, HTTPBodyString = NSString(data: HTTPBody, encoding: NSUTF8StringEncoding) {
let escapedString = HTTPBodyString.stringByReplacingOccurrencesOfString("\"", withString: "\\\"")
components.append("-d \"\(escapedString)\"")
}
return components.joinWithSeparator(" ") + "\n"
}
} | gpl-3.0 | c00f0c2bcbe69a7ec94b829b7f421ab7 | 35.913462 | 114 | 0.493226 | 6.396667 | false | false | false | false |
james-gray/selektor | Selektor/GrandSelektor.swift | 1 | 17122 | //
// GrandSelektor.swift
// Selektor
//
// Created by James Gray on 2016-07-05.
// Copyright © 2016 James Gray. All rights reserved.
//
import Foundation
import Cocoa
/**
The meat and potatoes of the Selektor application. This class contains a method
to select the best next track given a currently playing track, and provides
multiple implementations of selection algorithms, with the algorithm to be used
specified in Settings.plist.
*/
class GrandSelektor: NSObject {
/// Convenience property reference to the application delegate
let appDelegate = NSApplication.sharedApplication().delegate as! AppDelegate
/**
Mapping of algorithm strings as can be specified in Settings.plist to the
selection functions.
*/
var algorithms: [String: (TrackEntity, [TrackEntity]) -> TrackEntity] = [:]
/// The algorithm to be used.
var algorithm: String = ""
/**
Set up the GrandSelektor instance, configuring the algorithms as necessary.
*/
override init() {
super.init()
self.algorithms = [
"dummy": self.selectTrackDummy,
"rankedBPM": self.selectTrackRankedBPM,
"medianBPM": self.selectTrackMedianBPM,
"rankedLoudness": self.selectTrackRankedLoudness,
"medianLoudness": self.selectTrackMedianLoudness,
"rankedGenre": self.selectTrackRankedGenre,
"medianGenre": self.selectTrackMedianGenre,
"rankedKey": self.selectTrackRankedKey,
"medianKey": self.selectTrackMedianKey,
]
self.algorithm = appDelegate.settings?["selektorAlgorithm"] as! String
}
/**
Given the current track, return a subset of tracks that are similar in BPM
to the current track's tempo, with a range of ± 3 BPM.
If no other tracks within the range of ± 3 BPM are available, increment
the considered BPM range by 3 repeatedly until more tracks are found.
- parameter currentTrack: The track to compare tracks against.
- parameter tracks: The set of tracks to filter from.
- returns: A subset of tracks with similar BPM.
*/
func findTracksWithSimilarBPM(toTrack currentTrack: TrackEntity, inSet tracks: [TrackEntity]) -> [TrackEntity] {
var bpmOffset = 0
let currentTempo = currentTrack.tempo as! Int
var tracksSubset = [TrackEntity]()
// Filter considered tracks to tracks with tempo within ± 3 BPM of the current
// track's tempo, increasing the range if no tracks are found
while tracksSubset.count == 0 {
bpmOffset += 3
tracksSubset = tracks.filter {
($0.tempo as! Int) <= currentTempo + bpmOffset
&& ($0.tempo as! Int) >= currentTempo - bpmOffset
}
}
return tracksSubset
}
/**
Given the current track, return a subset of tracks with the same genre as
the current track. If no other tracks with the same genre are available,
simply return all tracks.
- parameter currentTrack: The track to compare tracks against.
- parameter tracks: The set of tracks to filter from.
- returns: A subset of tracks with the same genre, or the original set if no
other tracks with the same genre are found.
*/
func findTracksWithSameGenre(asTrack currentTrack: TrackEntity, inSet tracks: [TrackEntity]) -> [TrackEntity] {
guard let genre = currentTrack.genre else {
// Don't bother comparing this track if it doesn't have a genre
return tracks
}
let tracksSubset = tracks.filter { $0.genre == genre }
return tracksSubset.count > 0 ? tracksSubset : tracks
}
/**
Selects a track within ± 3 BPM (if possible) with the shortest distance
to the current track based on the distance function `distanceFunc`.
- parameter currentTrack: The track that is currently playing.
- parameter tracks: An array of `TrackEntity`s to choose from.
- parameter distanceFunc: The function to use in distance calculation.
- returns: The recommended track.
*/
func rankedSelection(withTrack currentTrack: TrackEntity, fromSet tracks: [TrackEntity],
usingDistanceFunction distanceFunc: (TrackEntity, TrackEntity) -> Double) -> TrackEntity {
var minDistance = DBL_MAX
var distance = 0.0
var selectedTrack: TrackEntity? = nil
for otherTrack in tracks {
distance = distanceFunc(currentTrack, otherTrack)
if distance < minDistance {
minDistance = distance
selectedTrack = otherTrack
}
}
return selectedTrack!
}
/**
Selects a track within ± 3 BPM (if possible) whose distance from the current
track is closest to the median distance of all tracks to the current track.
Distance is calculated using the distance function `distanceFunc`.
- parameter currentTrack: The track that is currently playing.
- parameter tracks: An array of `TrackEntity`s to choose from.
- parameter distanceFunc: The function to use in distance calculation.
- returns: The recommended track.
*/
func medianSelection(withTrack currentTrack: TrackEntity, fromSet tracks: [TrackEntity],
usingDistanceFunction distanceFunc: (TrackEntity, TrackEntity) -> Double) -> TrackEntity {
// Compute the median distance
let distances = tracks.map { distanceFunc(currentTrack, $0) }
let medianDistance = distances.sort()[distances.count / 2]
// Compare the distances of each track from the current track to the median distance
let deviationsFromMedianDistance = distances.map { fabs(medianDistance - $0) }
var minDeviation = DBL_MAX
var selectedIndex = -1
// Find the index of the track with the closest timbre distance to the
// median.
for (index, deviation) in deviationsFromMedianDistance.enumerate() {
if deviation < minDeviation {
minDeviation = deviation
selectedIndex = index
}
}
return tracks[selectedIndex]
}
/**
Select the best next track to play based on the currently playing track.
- parameter currentTrack: The `TrackEntity` the user is currently playing.
- returns: A `TrackEntity` that the application suggests the user plays next.
*/
func selectTrack(currentTrack: TrackEntity) -> TrackEntity {
// Filter out un-analyzed tracks
var tracks = self.appDelegate.tracks.filter {
$0.objectID != currentTrack.objectID
&& $0.analyzed == AnalysisState.complete.rawValue
}
// Filter out tracks the user has already played
tracks = tracks.filter {
$0.played == false
}
// Mark the current track as played
currentTrack.played = true
if tracks.count == 0 {
// TODO: UI to show a useful error when there's only one track in the
// library
return currentTrack
}
// Ensure the algorithm specified in Settings.plist is actually implemented
if !self.algorithms.keys.contains(algorithm) {
fatalError("Invalid selektorAlgorithm specified in Settings.plist")
}
// Get the selection function which implements the specified algorithm and
// use it to determine the best next track
let selekt = self.algorithms[algorithm]!
return selekt(currentTrack, tracks)
}
/**
Dummy selection algorithm which simply picks another track at random.
- parameter currentTrack: The track that is currently playing.
- parameter tracks: An array of `TrackEntity`s to choose from.
- returns: A random track.
*/
func selectTrackDummy(currentTrack: TrackEntity, tracks: [TrackEntity]) -> TrackEntity {
let index = Int(arc4random_uniform(UInt32(tracks.count)))
return tracks[index]
}
/**
Selects a track within ± 3 BPM (if possible) with the most similar timbre
to the current track. Timbre similarity is calculated by computing the
Euclidean distance between the tracks' timbre vectors.
- parameter currentTrack: The track that is currently playing.
- parameter tracks: An array of `TrackEntity`s to choose from.
- returns: The recommended track as deduced by the algorithm.
*/
func selectTrackRankedBPM(currentTrack: TrackEntity, tracks: [TrackEntity]) -> TrackEntity {
let trackSubset = findTracksWithSimilarBPM(toTrack: currentTrack, inSet: tracks)
let distanceFunc = { (currentTrack: TrackEntity, otherTrack: TrackEntity) in
return currentTrack.compareTimbreWith(otherTrack: otherTrack)
}
return rankedSelection(withTrack: currentTrack, fromSet: trackSubset,
usingDistanceFunction: distanceFunc)
}
/**
Selects a track within ± 3 BPM (if possible) whose timbre distance is
closest to the median distance of all tracks to the current track.
- parameter currentTrack: The track that is currently playing.
- parameter tracks: An array of `TrackEntity`s to choose from.
- returns: The recommended track as deduced by the algorithm.
*/
func selectTrackMedianBPM(currentTrack: TrackEntity, tracks: [TrackEntity]) -> TrackEntity {
let trackSubset = findTracksWithSimilarBPM(toTrack: currentTrack, inSet: tracks)
let distanceFunc = { (currentTrack: TrackEntity, otherTrack: TrackEntity) in
return currentTrack.compareTimbreWith(otherTrack: otherTrack)
}
return medianSelection(withTrack: currentTrack, fromSet: trackSubset,
usingDistanceFunction: distanceFunc)
}
/**
Selects a track within ± 3 BPM (if possible) of the current track's tempo,
with the most similar timbre and loudness to the current track.
The distance values for timbre and loudness are added together for each
track, and the track with the shortest combined distance is chosen as the
suggested track.
- parameter currentTrack: The track that is currently playing.
- parameter tracks: An array of `TrackEntity`s to choose from.
- returns: The recommended track as deduced by the algorithm.
*/
func selectTrackRankedLoudness(currentTrack: TrackEntity, tracks: [TrackEntity]) -> TrackEntity {
let trackSubset = findTracksWithSimilarBPM(toTrack: currentTrack, inSet: tracks)
// Scale the loudness factor by 50 to weight the timbre and loudness distances
// roughly equally. In testing, the maximum timbre distance between tracks
// was about 50, so this scales the normalized RMS values to roughly the same
// range.
let distanceFunc = { (currentTrack: TrackEntity, otherTrack: TrackEntity) in
return currentTrack.compareTimbreWith(otherTrack: otherTrack)
+ (50.0 * currentTrack.compareLoudnessWith(otherTrack: otherTrack))
}
return rankedSelection(withTrack: currentTrack, fromSet: trackSubset,
usingDistanceFunction: distanceFunc)
}
/**
Selects a track within ± 3 BPM (if possible) whose combined timbre and
loudness distance is closest to the median combined distance of all tracks
to the current track.
- parameter currentTrack: The track that is currently playing.
- parameter tracks: An array of `TrackEntity`s to choose from.
- returns: The recommended track as deduced by the algorithm.
*/
func selectTrackMedianLoudness(currentTrack: TrackEntity, tracks: [TrackEntity]) -> TrackEntity {
let trackSubset = findTracksWithSimilarBPM(toTrack: currentTrack, inSet: tracks)
let distanceFunc = { (currentTrack: TrackEntity, otherTrack: TrackEntity) in
return currentTrack.compareTimbreWith(otherTrack: otherTrack)
+ (50.0 * currentTrack.compareLoudnessWith(otherTrack: otherTrack))
}
return medianSelection(withTrack: currentTrack, fromSet: trackSubset,
usingDistanceFunction: distanceFunc)
}
/**
Selects a track that is in the same genre as the current track (if possible),
within ± 3 BPM (if possible) of the current track's tempo, and with the
most similar timbre and loudness to the current track.
- parameter currentTrack: The track that is currently playing.
- parameter tracks: An array of `TrackEntity`s to choose from.
- returns: The recommended track as deduced by the algorithm.
*/
func selectTrackRankedGenre(currentTrack: TrackEntity, tracks: [TrackEntity]) -> TrackEntity {
var trackSubset = findTracksWithSameGenre(asTrack: currentTrack, inSet: tracks)
trackSubset = findTracksWithSimilarBPM(toTrack: currentTrack, inSet: trackSubset)
let distanceFunc = { (currentTrack: TrackEntity, otherTrack: TrackEntity) in
return currentTrack.compareTimbreWith(otherTrack: otherTrack)
+ (50.0 * currentTrack.compareLoudnessWith(otherTrack: otherTrack))
}
return rankedSelection(withTrack: currentTrack, fromSet: trackSubset,
usingDistanceFunction: distanceFunc)
}
/**
Selects a track that is the same genre as the current track (if possible),
within ± 3 BPM (if possible) of the current track's tempo, whose combined
timbre and loudness distance is closest to the median combined distance of
all tracks to the current track.
- parameter currentTrack: The track that is currently playing.
- parameter tracks: An array of `TrackEntity`s to choose from.
- returns: The recommended track as deduced by the algorithm.
*/
func selectTrackMedianGenre(currentTrack: TrackEntity, tracks: [TrackEntity]) -> TrackEntity {
var trackSubset = findTracksWithSameGenre(asTrack: currentTrack, inSet: tracks)
trackSubset = findTracksWithSimilarBPM(toTrack: currentTrack, inSet: trackSubset)
let distanceFunc = { (currentTrack: TrackEntity, otherTrack: TrackEntity) in
return currentTrack.compareTimbreWith(otherTrack: otherTrack)
+ (50.0 * currentTrack.compareLoudnessWith(otherTrack: otherTrack))
}
return medianSelection(withTrack: currentTrack, fromSet: trackSubset,
usingDistanceFunction: distanceFunc)
}
/**
Selects a track that is the same, or close, in key (based on the circle of
5ths), with the same genre as the current track (if possible), within ± 3
BPM (if possible) of the current track's tempo, and with the most similar
timbre and loudness to the current track.
- parameter currentTrack: The track that is currently playing.
- parameter tracks: An array of `TrackEntity`s to choose from.
- returns: The recommended track as deduced by the algorithm.
*/
func selectTrackRankedKey(currentTrack: TrackEntity, tracks: [TrackEntity]) -> TrackEntity {
var trackSubset = findTracksWithSameGenre(asTrack: currentTrack, inSet: tracks)
trackSubset = findTracksWithSimilarBPM(toTrack: currentTrack, inSet: trackSubset)
// Scale the key factor by 16 to weight the key more heavily than the loudness
// and timbre (which are weighted roughly equally.) Since the maximum distance
// between keys is 6, and the rough maximum distance between timbres and (scaled)
// loudness is 50, multiply by 16 to roughly double the maximum distance between
// keys to ensure it influences the selection the most out of the three factors.
let distanceFunc = { (currentTrack: TrackEntity, otherTrack: TrackEntity) in
return currentTrack.compareTimbreWith(otherTrack: otherTrack)
+ (50.0 * currentTrack.compareLoudnessWith(otherTrack: otherTrack))
+ (16.0 * currentTrack.compareKeyWith(otherTrack: otherTrack))
}
return rankedSelection(withTrack: currentTrack, fromSet: trackSubset,
usingDistanceFunction: distanceFunc)
}
/**
Selects a track that is the same, or close, in key (based on the circle of
5ths), with the same genre as the current track (if possible), within ± 3
BPM (if possible) of the current track's tempo, and with the most similar
timbre and loudness to the current track.
- parameter currentTrack: The track that is currently playing.
- parameter tracks: An array of `TrackEntity`s to choose from.
- returns: The recommended track as deduced by the algorithm.
*/
func selectTrackMedianKey(currentTrack: TrackEntity, tracks: [TrackEntity]) -> TrackEntity {
var trackSubset = findTracksWithSameGenre(asTrack: currentTrack, inSet: tracks)
trackSubset = findTracksWithSimilarBPM(toTrack: currentTrack, inSet: trackSubset)
// Scale the key factor by 16 to weight the key more heavily than the loudness
// and timbre (which are weighted roughly equally.) Since the maximum distance
// between keys is 6, and the rough maximum distance between timbres and (scaled)
// loudness is 50, multiply by 16 to increase the maximum distance between
// keys to ensure it influences the selection roughly twice as much as the timbre
// or loudness.
let distanceFunc = { (currentTrack: TrackEntity, otherTrack: TrackEntity) in
return currentTrack.compareTimbreWith(otherTrack: otherTrack)
+ (50.0 * currentTrack.compareLoudnessWith(otherTrack: otherTrack))
+ (16.0 * currentTrack.compareKeyWith(otherTrack: otherTrack))
}
return medianSelection(withTrack: currentTrack, fromSet: trackSubset,
usingDistanceFunction: distanceFunc)
}
} | gpl-3.0 | 74397d1b058417e68a78d0df97986453 | 39.930622 | 114 | 0.715455 | 4.508037 | false | false | false | false |
jjatie/Charts | Source/Charts/Renderers/DataRenderer/CandleStickChartRenderer.swift | 1 | 14764 | //
// CandleStickChartRenderer.swift
// Charts
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/Charts
//
import CoreGraphics
import Foundation
public class CandleStickChartRenderer: DataRenderer {
public let viewPortHandler: ViewPortHandler
public final var accessibleChartElements: [NSUIAccessibilityElement] = []
public let animator: Animator
let xBounds = XBounds()
open weak var dataProvider: CandleChartDataProvider?
public init(dataProvider: CandleChartDataProvider, animator: Animator, viewPortHandler: ViewPortHandler)
{
self.viewPortHandler = viewPortHandler
self.animator = animator
self.dataProvider = dataProvider
}
public func drawData(context: CGContext) {
guard let dataProvider = dataProvider, let candleData = dataProvider.candleData else { return }
// If we redraw the data, remove and repopulate accessible elements to update label values and frames
accessibleChartElements.removeAll()
// Make the chart header the first element in the accessible elements array
if let chart = dataProvider as? CandleStickChartView {
let element = createAccessibleHeader(usingChart: chart,
andData: candleData,
withDefaultDescription: "CandleStick Chart")
accessibleChartElements.append(element)
}
for case let set as CandleChartDataSet in candleData where set.isVisible {
drawDataSet(context: context, dataSet: set)
}
}
private var _shadowPoints = [CGPoint](repeating: CGPoint(), count: 4)
private var _rangePoints = [CGPoint](repeating: CGPoint(), count: 2)
private var _openPoints = [CGPoint](repeating: CGPoint(), count: 2)
private var _closePoints = [CGPoint](repeating: CGPoint(), count: 2)
private var _bodyRect = CGRect()
open func drawDataSet(context: CGContext, dataSet: CandleChartDataSet) {
guard
let dataProvider = dataProvider
else { return }
let trans = dataProvider.getTransformer(forAxis: dataSet.axisDependency)
let phaseY = animator.phaseY
let barSpace = dataSet.barSpace
let showCandleBar = dataSet.showCandleBar
xBounds.set(chart: dataProvider, dataSet: dataSet, animator: animator)
context.saveGState()
context.setLineWidth(dataSet.shadowWidth)
for j in xBounds {
// get the entry
guard let e = dataSet[j] as? CandleChartDataEntry else { continue }
let xPos = e.x
let open = e.open
let close = e.close
let high = e.high
let low = e.low
let doesContainMultipleDataSets = (dataProvider.candleData?.count ?? 1) > 1
var accessibilityMovementDescription = "neutral"
var accessibilityRect = CGRect(x: CGFloat(xPos) + 0.5 - barSpace,
y: CGFloat(low * phaseY),
width: (2 * barSpace) - 1.0,
height: CGFloat(abs(high - low) * phaseY))
trans.rectValueToPixel(&accessibilityRect)
if showCandleBar {
// calculate the shadow
_shadowPoints[0].x = CGFloat(xPos)
_shadowPoints[1].x = CGFloat(xPos)
_shadowPoints[2].x = CGFloat(xPos)
_shadowPoints[3].x = CGFloat(xPos)
if open > close {
_shadowPoints[0].y = CGFloat(high * phaseY)
_shadowPoints[1].y = CGFloat(open * phaseY)
_shadowPoints[2].y = CGFloat(low * phaseY)
_shadowPoints[3].y = CGFloat(close * phaseY)
} else if open < close {
_shadowPoints[0].y = CGFloat(high * phaseY)
_shadowPoints[1].y = CGFloat(close * phaseY)
_shadowPoints[2].y = CGFloat(low * phaseY)
_shadowPoints[3].y = CGFloat(open * phaseY)
} else {
_shadowPoints[0].y = CGFloat(high * phaseY)
_shadowPoints[1].y = CGFloat(open * phaseY)
_shadowPoints[2].y = CGFloat(low * phaseY)
_shadowPoints[3].y = _shadowPoints[1].y
}
trans.pointValuesToPixel(&_shadowPoints)
// draw the shadows
var shadowColor: NSUIColor!
if dataSet.isShadowColorSameAsCandle {
if open > close {
shadowColor = dataSet.decreasingColor ?? dataSet.color(at: j)
} else if open < close {
shadowColor = dataSet.increasingColor ?? dataSet.color(at: j)
} else {
shadowColor = dataSet.neutralColor ?? dataSet.color(at: j)
}
}
if shadowColor === nil {
shadowColor = dataSet.shadowColor ?? dataSet.color(at: j)
}
context.setStrokeColor(shadowColor.cgColor)
context.strokeLineSegments(between: _shadowPoints)
// calculate the body
_bodyRect.origin.x = CGFloat(xPos) - 0.5 + barSpace
_bodyRect.origin.y = CGFloat(close * phaseY)
_bodyRect.size.width = (CGFloat(xPos) + 0.5 - barSpace) - _bodyRect.origin.x
_bodyRect.size.height = CGFloat(open * phaseY) - _bodyRect.origin.y
trans.rectValueToPixel(&_bodyRect)
// draw body differently for increasing and decreasing entry
if open > close {
accessibilityMovementDescription = "decreasing"
let color = dataSet.decreasingColor ?? dataSet.color(at: j)
if dataSet.isDecreasingFilled {
context.setFillColor(color.cgColor)
context.fill(_bodyRect)
} else {
context.setStrokeColor(color.cgColor)
context.stroke(_bodyRect)
}
} else if open < close {
accessibilityMovementDescription = "increasing"
let color = dataSet.increasingColor ?? dataSet.color(at: j)
if dataSet.isIncreasingFilled {
context.setFillColor(color.cgColor)
context.fill(_bodyRect)
} else {
context.setStrokeColor(color.cgColor)
context.stroke(_bodyRect)
}
} else {
let color = dataSet.neutralColor ?? dataSet.color(at: j)
context.setStrokeColor(color.cgColor)
context.stroke(_bodyRect)
}
} else {
_rangePoints[0].x = CGFloat(xPos)
_rangePoints[0].y = CGFloat(high * phaseY)
_rangePoints[1].x = CGFloat(xPos)
_rangePoints[1].y = CGFloat(low * phaseY)
_openPoints[0].x = CGFloat(xPos) - 0.5 + barSpace
_openPoints[0].y = CGFloat(open * phaseY)
_openPoints[1].x = CGFloat(xPos)
_openPoints[1].y = CGFloat(open * phaseY)
_closePoints[0].x = CGFloat(xPos) + 0.5 - barSpace
_closePoints[0].y = CGFloat(close * phaseY)
_closePoints[1].x = CGFloat(xPos)
_closePoints[1].y = CGFloat(close * phaseY)
trans.pointValuesToPixel(&_rangePoints)
trans.pointValuesToPixel(&_openPoints)
trans.pointValuesToPixel(&_closePoints)
// draw the ranges
var barColor: NSUIColor!
if open > close {
accessibilityMovementDescription = "decreasing"
barColor = dataSet.decreasingColor ?? dataSet.color(at: j)
} else if open < close {
accessibilityMovementDescription = "increasing"
barColor = dataSet.increasingColor ?? dataSet.color(at: j)
} else {
barColor = dataSet.neutralColor ?? dataSet.color(at: j)
}
context.setStrokeColor(barColor.cgColor)
context.strokeLineSegments(between: _rangePoints)
context.strokeLineSegments(between: _openPoints)
context.strokeLineSegments(between: _closePoints)
}
let axElement = createAccessibleElement(withIndex: j,
container: dataProvider,
dataSet: dataSet) { element in
element.accessibilityLabel = "\(doesContainMultipleDataSets ? "\(dataSet.label ?? "Dataset")" : "") " + "\(xPos) - \(accessibilityMovementDescription). low: \(low), high: \(high), opening: \(open), closing: \(close)"
element.accessibilityFrame = accessibilityRect
}
accessibleChartElements.append(axElement)
}
// Post this notification to let VoiceOver account for the redrawn frames
accessibilityPostLayoutChangedNotification()
context.restoreGState()
}
public func drawValues(context: CGContext) {
guard
let dataProvider = dataProvider,
let candleData = dataProvider.candleData
else { return }
// if values are drawn
if isDrawingValuesAllowed(dataProvider: dataProvider) {
let phaseY = animator.phaseY
var pt = CGPoint()
for i in candleData.indices {
guard let
dataSet = candleData[i] as? BarLineScatterCandleBubbleChartDataSet,
shouldDrawValues(forDataSet: dataSet)
else { continue }
let valueFont = dataSet.valueFont
let formatter = dataSet.valueFormatter
let trans = dataProvider.getTransformer(forAxis: dataSet.axisDependency)
let valueToPixelMatrix = trans.valueToPixelMatrix
let iconsOffset = dataSet.iconsOffset
let angleRadians = dataSet.valueLabelAngle.DEG2RAD
xBounds.set(chart: dataProvider, dataSet: dataSet, animator: animator)
let lineHeight = valueFont.lineHeight
let yOffset: CGFloat = lineHeight + 5.0
for j in xBounds {
guard let e = dataSet[j] as? CandleChartDataEntry else { break }
pt.x = CGFloat(e.x)
pt.y = CGFloat(e.high * phaseY)
pt = pt.applying(valueToPixelMatrix)
if !viewPortHandler.isInBoundsRight(pt.x) {
break
}
if !viewPortHandler.isInBoundsLeft(pt.x) || !viewPortHandler.isInBoundsY(pt.y) {
continue
}
if dataSet.isDrawValuesEnabled {
context.drawText(formatter.stringForValue(e.high,
entry: e,
dataSetIndex: i,
viewPortHandler: viewPortHandler),
at: CGPoint(x: pt.x,
y: pt.y - yOffset),
align: .center,
angleRadians: angleRadians,
attributes: [.font: valueFont,
.foregroundColor: dataSet.valueTextColorAt(j)])
}
if let icon = e.icon, dataSet.isDrawIconsEnabled {
context.drawImage(icon,
atCenter: CGPoint(x: pt.x + iconsOffset.x,
y: pt.y + iconsOffset.y),
size: icon.size)
}
}
}
}
}
public func drawExtras(context _: CGContext) {}
public func drawHighlighted(context: CGContext, indices: [Highlight]) {
guard
let dataProvider = dataProvider,
let candleData = dataProvider.candleData
else { return }
context.saveGState()
for high in indices {
guard
let set = candleData[high.dataSetIndex] as? CandleChartDataSet,
set.isHighlightEnabled
else { continue }
guard let e = set.element(withX: high.x, closestToY: high.y) as? CandleChartDataEntry else { continue }
if !isInBoundsX(entry: e, dataSet: set) {
continue
}
let trans = dataProvider.getTransformer(forAxis: set.axisDependency)
context.setStrokeColor(set.highlightColor.cgColor)
context.setLineWidth(set.highlightLineWidth)
if set.highlightLineDashLengths != nil {
context.setLineDash(phase: set.highlightLineDashPhase, lengths: set.highlightLineDashLengths!)
} else {
context.setLineDash(phase: 0.0, lengths: [])
}
let lowValue = e.low * Double(animator.phaseY)
let highValue = e.high * Double(animator.phaseY)
let y = (lowValue + highValue) / 2.0
let pt = trans.pixelForValues(x: e.x, y: y)
high.setDraw(pt: pt)
// draw the lines
drawHighlightLines(context: context, point: pt, set: set)
}
context.restoreGState()
}
private func createAccessibleElement(withIndex _: Int,
container: CandleChartDataProvider,
dataSet _: CandleChartDataSet,
modifier: (NSUIAccessibilityElement) -> Void) -> NSUIAccessibilityElement
{
let element = NSUIAccessibilityElement(accessibilityContainer: container)
// The modifier allows changing of traits and frame depending on highlight, rotation, etc
modifier(element)
return element
}
}
| apache-2.0 | 3975987c17a9ab0bc7ae65cb6d8ad4a1 | 38.902703 | 232 | 0.527838 | 5.760437 | false | false | false | false |
mypalal84/GoGoGithub | GoGoGithub/GoGoGithub/GitHubAuthController.swift | 1 | 1863 | //
// GitHubAuthController.swift
// GoGoGithub
//
// Created by A Cahn on 4/3/17.
// Copyright © 2017 A Cahn. All rights reserved.
//
import UIKit
class GitHubAuthController: UIViewController {
@IBOutlet weak var loginButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
}
func updateUI() {
if let _ = UserDefaults.standard.getAccessToken() {
// disable your button, change color
self.loginButton.isEnabled = false
self.loginButton.backgroundColor = UIColor.gray
//enable button, change color back to original
} else {
self.loginButton.isEnabled = true
self.loginButton.backgroundColor = UIColor(red: 0,
green: 255/255,
blue: 128/255,
alpha: 1)
}
}
@IBAction func printTokenPressed(_ sender: Any) {
//print accessToken
let accessToken = UserDefaults.standard.getAccessToken()
print("Access Token: \(String(describing: accessToken))")
}
@IBAction func loginButtonPressed(_ sender: Any) {
//request OAuth
let parameters = ["scope" : "email,user,repo"]
GitHub.shared.oAuthRequestWith(parameters: parameters)
updateUI()
}
@IBAction func logoutButtonPressed(_ sender: Any) {
UserDefaults.standard.removeObject(forKey: "access_token")
updateUI()
}
//take view off parent view, and parent viewcontroller
func dismissAuthController() {
self.view.removeFromSuperview()
self.removeFromParentViewController()
}
}
| mit | bd84ded0efd971416eac1c179c062ece | 26.382353 | 70 | 0.542965 | 5.460411 | false | false | false | false |
mfitzpatrick79/BidHub-iOS | AuctionApp/ItemList/ItemListViewController.swift | 1 | 15890 | //
// ItemListViewController.swift
// AuctionApp
//
import UIKit
import SVProgressHUD
import CSNotificationView
import Haneke
import NSDate_RelativeTime
import Parse
extension String {
subscript (i: Int) -> String {
return String(Array(self.characters)[i])
}
}
class ItemListViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UISearchBarDelegate, UIScrollViewDelegate, ItemTableViewCellDelegate, BiddingViewControllerDelegate, CategoryViewControllerDelegate {
@IBOutlet var searchBar: UISearchBar!
@IBOutlet var segmentControl: UISegmentedControl!
@IBOutlet var tableView: UITableView!
var window: UIWindow?
var refreshControl: UIRefreshControl = UIRefreshControl()
var items:[Item] = [Item]()
var timer:Timer?
var filterType: FilterType = .all
var sizingCell: ItemTableViewCell?
var bottomContraint:NSLayoutConstraint!
var zoomOverlay: UIScrollView!
var zoomImageView: UIImageView = UIImageView()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
SVProgressHUD.setBackgroundColor(UIColor(red: 0/255, green: 0/255, blue: 0/255, alpha: 0))
SVProgressHUD.setForegroundColor(UIColor(red: 242/255, green: 109/255, blue: 59/255, alpha: 1.0))
SVProgressHUD.setRingThickness(5.0)
let colorView:UIView = UIView(frame: CGRect(x: 0, y: -1000, width: view.frame.size.width, height: 1000))
colorView.backgroundColor = UIColor(red: 0/255, green: 0/255, blue: 0/255, alpha: 0)
tableView.addSubview(colorView)
// Refresh Control
let refreshView = UIView(frame: CGRect(x: 0, y: 10, width: 0, height: 0))
tableView.insertSubview(refreshView, aboveSubview: colorView)
refreshControl.tintColor = UIColor(red: 242/255, green: 109/255, blue: 59/255, alpha: 1.0)
refreshControl.addTarget(self, action: #selector(ItemListViewController.reloadItems), for: .valueChanged)
refreshView.addSubview(refreshControl)
sizingCell = tableView.dequeueReusableCell(withIdentifier: "ItemTableViewCell") as? ItemTableViewCell
tableView.estimatedRowHeight = 635
tableView.rowHeight = UITableViewAutomaticDimension
self.tableView.alpha = 0.0
reloadData(false, initialLoad: true)
let user = PFUser.current()
print("Logged in as: \(String(describing: user!.email))", terminator: "")
}
override func viewDidAppear(_ animated: Bool) {
timer = Timer.scheduledTimer(timeInterval: 30.0, target: self, selector: #selector(ItemListViewController.reloadItems), userInfo: nil, repeats: true)
timer?.tolerance = 10.0
}
override func viewWillDisappear(_ animated: Bool) {
NotificationCenter.default.removeObserver(self)
timer?.invalidate()
}
/// Hack for selectors and default parameters
func reloadItems(){
reloadData()
}
func reloadData(_ silent: Bool = true, initialLoad: Bool = false) {
if initialLoad {
SVProgressHUD.show()
}
DataManager().sharedInstance.getItems{ (items, error) in
if error != nil {
// Error Case
if !silent {
if (error?.code == 209) {
PFUser.logOut()
let frame = UIScreen.main.bounds
self.window = UIWindow(frame: frame)
//Necessary pop of view controllers after executing the previous code.
let loginVC = UIStoryboard(name: "Main", bundle: Bundle.main).instantiateViewController(withIdentifier: "LoginViewController") as! LoginViewController
self.window?.rootViewController=loginVC
}
}
print("Error getting items", terminator: "")
}else{
self.items = items
self.filterTable(self.filterType)
}
self.refreshControl.endRefreshing()
if initialLoad {
SVProgressHUD.dismiss()
UIView.animate(withDuration: 1.0, animations: { () -> Void in
self.tableView.alpha = 1.0
})
}
}
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return items.count
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return UITableViewAutomaticDimension
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "ItemTableViewCell", for: indexPath) as! ItemTableViewCell
return configureCellForIndexPath(cell, indexPath: indexPath)
}
func configureCellForIndexPath(_ cell: ItemTableViewCell, indexPath: IndexPath) -> ItemTableViewCell {
let item = items[indexPath.row];
cell.itemImageView.hnk_setImageFromURL(URL(string: item.imageUrl)!, placeholder: UIImage(named: "blank")!)
cell.itemProgramNumberLabel.text = item.programNumberString
cell.itemTitleLabel.text = item.title
cell.itemArtistLabel.text = item.artist
cell.itemMediaLabel.text = item.media
cell.itemSizeLabel.text = item.size
cell.itemCalloutLabel.text = item.itemCallout
cell.itemDescriptionLabel.text = item.itemDesctiption
cell.itemFmvLabel.text = item.fairMarketValue
if item.quantity > 1 {
let bidsString = "$\(item.price)"
cell.itemDescriptionLabel.text =
"\(item.quantity) available! Highest \(item.quantity) bidders win. Current high bid is \(bidsString)" +
"\n\n" + cell.itemDescriptionLabel.text!
}
cell.delegate = self;
cell.item = item
var price: Int?
var lowPrice: Int?
switch (item.winnerType) {
case .single:
price = item.price
case .multiple:
price = item.price
lowPrice = item.price
}
let bidString = (item.numberOfBids == 1) ? "Bid":"Bids"
cell.numberOfBidsLabel.text = "\(item.numberOfBids) \(bidString)"
if let topBid = price {
if let lowBid = lowPrice{
if item.numberOfBids > 1{
cell.currentBidLabel.text = "$\(lowBid)-\(topBid)"
}else{
cell.currentBidLabel.text = "$\(topBid)"
}
}else{
cell.currentBidLabel.text = "$\(topBid)"
}
}else{
cell.currentBidLabel.text = "$\(item.price)"
}
if !item.currentWinners.isEmpty && item.hasBid{
if item.isWinning{
cell.setWinning()
}else{
cell.setOutbid()
}
}else{
cell.setDefault()
}
if(item.closeTime.timeIntervalSinceNow < 0.0){
cell.dateLabel.text = "Sorry, bidding has closed"
cell.bidNowButton.isHidden = true
}else{
if(item.openTime.timeIntervalSinceNow < 0.0){
// open
cell.dateLabel.text = "Bidding closes \((item.closeTime as NSDate).relativeTime().lowercased())."
cell.bidNowButton.isHidden = false
}else{
cell.dateLabel.text = "Bidding opens \((item.openTime as NSDate).relativeTime().lowercased())."
cell.bidNowButton.isHidden = true
}
}
return cell
}
/// Cell Delegate
func cellDidPressBid(_ item: Item) {
let bidVC = UIStoryboard(name: "Main", bundle: Bundle.main).instantiateViewController(withIdentifier: "BiddingViewController") as? BiddingViewController
if let biddingVC = bidVC {
biddingVC.delegate = self
biddingVC.item = item
addChildViewController(biddingVC)
view.addSubview(biddingVC.view)
biddingVC.didMove(toParentViewController: self)
}
}
/// Image Detail Zoom
func cellImageTapped(_ item: Item) {
zoomImageView.frame = view.bounds
zoomImageView.clipsToBounds = false
zoomImageView.contentMode = .scaleAspectFit
zoomImageView.hnk_setImageFromURL(URL(string: item.imageUrl)!, placeholder: UIImage(named: "blank")!)
zoomOverlay = UIScrollView(frame: view.bounds)
zoomOverlay.tag = 420
zoomOverlay.delegate = self
zoomOverlay.backgroundColor = UIColor.darkGray
zoomOverlay.alwaysBounceVertical = false
zoomOverlay.alwaysBounceHorizontal = false
zoomOverlay.showsVerticalScrollIndicator = true
zoomOverlay.flashScrollIndicators()
zoomOverlay.minimumZoomScale = 1.0
zoomOverlay.maximumZoomScale = 6.0
let backButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.done, target: self, action: #selector(ItemListViewController.pressedClose(_:)))
navigationItem.leftBarButtonItem = nil
navigationItem.rightBarButtonItem = backButton
navigationItem.rightBarButtonItem?.tintColor = UIColor.white
segmentControl.isHidden = true
zoomOverlay.addSubview(zoomImageView)
self.view.addSubview(zoomOverlay)
setupZoomGestureRecognizer()
}
func viewForZooming(in scrollView: UIScrollView) -> UIView? {
return zoomImageView
}
func scrollViewDidZoom(_ scrollView: UIScrollView) {
let imageViewSize = zoomImageView.frame.size
let scrollViewSize = zoomOverlay.bounds.size
let verticalPadding = imageViewSize.height < scrollViewSize.height ? (scrollViewSize.height - imageViewSize.height) / 2 : 0
let horizontalPadding = imageViewSize.width < scrollViewSize.width ? (scrollViewSize.width - imageViewSize.width) / 2 : 0
zoomOverlay.contentInset = UIEdgeInsets(top: verticalPadding, left: horizontalPadding, bottom: verticalPadding, right: horizontalPadding)
}
func setupZoomGestureRecognizer() {
let doubleTap = UITapGestureRecognizer(target: self, action: #selector(ItemListViewController.handleZoomImageDoubleTap(_:)))
doubleTap.numberOfTapsRequired = 2
zoomOverlay.addGestureRecognizer(doubleTap)
}
func handleZoomImageDoubleTap(_ recognizer: UITapGestureRecognizer) {
if (zoomOverlay.zoomScale > zoomOverlay.minimumZoomScale) {
zoomOverlay.setZoomScale(zoomOverlay.minimumZoomScale, animated: true)
} else {
zoomOverlay.setZoomScale(zoomOverlay.maximumZoomScale, animated: true)
}
}
func pressedClose(_ sender: UIButton!) {
self.segmentControl.isHidden = false
if let viewWithTag = self.view.viewWithTag(420) {
viewWithTag.removeFromSuperview()
}
let btnName = UIButton()
btnName.setImage(UIImage(named: "HSLogOutIcon"), for: UIControlState())
btnName.frame = CGRect(x: 0, y: 0, width: 30, height: 30)
btnName.addTarget(self, action: #selector(ItemListViewController.logoutPressed(_:)), for: .touchUpInside)
let leftBarButton = UIBarButtonItem(customView: btnName)
navigationItem.leftBarButtonItem = leftBarButton
navigationItem.rightBarButtonItem = nil
}
/// Actions
@IBAction func logoutPressed(_ sender: AnyObject) {
PFUser.logOut()
performSegue(withIdentifier: "logoutSegue", sender: nil)
}
@IBAction func segmentBarValueChanged(_ sender: AnyObject) {
searchBar.resignFirstResponder()
searchBar.text = ""
let segment = sender as! UISegmentedControl
switch(segment.selectedSegmentIndex) {
case 0:
filterTable(.all)
case 1:
filterTable(.noBids)
case 2:
filterTable(.myItems)
case 3:
didPressCategoryFilterTrigger()
default:
filterTable(.all)
}
}
func filterTable(_ filter: FilterType) {
filterType = filter
self.items = DataManager().sharedInstance.applyFilter(filter)
self.tableView.reloadData()
}
func bidOnItem(_ item: Item, maxBid: Int) {
SVProgressHUD.show()
DataManager().sharedInstance.bidOn(item, maxBid: maxBid) { (success, errorString) -> () in
if success {
print("Woohoo", terminator: "")
self.items = DataManager().sharedInstance.allItems
self.reloadData()
SVProgressHUD.dismiss()
}else{
self.showError(errorString)
self.reloadData()
SVProgressHUD.dismiss()
}
}
}
func showError(_ errorString: String) {
if let _: AnyClass = NSClassFromString("UIAlertController") {
// make and use a UIAlertController
let alertView = UIAlertController(title: "Error", message: errorString, preferredStyle: .alert)
let okAction = UIAlertAction(title: "Ok", style: .default, handler: { (action) -> Void in
print("Ok Pressed", terminator: "")
})
alertView.addAction(okAction)
self.present(alertView, animated: true, completion: nil)
}
else {
// make and use a UIAlertView
let alertView = UIAlertView(title: "Error", message: errorString, delegate: nil, cancelButtonTitle: nil, otherButtonTitles: "Ok")
alertView.show()
}
}
/// Category Filtering
func didPressCategoryFilterTrigger() {
let catVC = UIStoryboard(name: "Main", bundle: Bundle.main).instantiateViewController(withIdentifier: "CategoryViewController") as? CategoryViewController
if let categoryVC = catVC {
categoryVC.delegate = self
addChildViewController(categoryVC)
view.addSubview(categoryVC.view)
categoryVC.didMove(toParentViewController: self)
}
}
/// Search Bar
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
if searchText.isEmpty {
filterTable(.all)
}else{
filterTable(.search(searchTerm:searchText))
}
}
func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
self.segmentBarValueChanged(segmentControl)
searchBar.resignFirstResponder()
}
/// Bidding VC
func biddingViewControllerDidBid(_ viewController: BiddingViewController, onItem: Item, maxBid: Int){
viewController.view.removeFromSuperview()
bidOnItem(onItem, maxBid: maxBid)
}
func biddingViewControllerDidCancel(_ viewController: BiddingViewController){
viewController.view.removeFromSuperview()
}
/// Category VC
func categoryViewControllerDidFilter(_ viewController: CategoryViewController, onCategory: String){
viewController.view.removeFromSuperview()
filterTable(.category(filterValue: onCategory))
}
func categoryViewControllerDidCancel(_ viewController: CategoryViewController){
viewController.view.removeFromSuperview()
self.segmentControl.selectedSegmentIndex = 0
segmentBarValueChanged(self.segmentControl)
}
}
| apache-2.0 | a20d7b28753c1d9d758d4b8ef043011f | 37.567961 | 225 | 0.619006 | 5.323283 | false | false | false | false |
roecrew/AudioKit | AudioKit/Common/Playgrounds/Synthesis.playground/Pages/Amplitude Envelope.xcplaygroundpage/Contents.swift | 1 | 1768 | //: ## Amplitude Envelope
//: Enveloping an Oscillator with an ADSR envelope
import XCPlayground
import AudioKit
var fmWithADSR = AKOscillatorBank()
AudioKit.output = AKBooster(fmWithADSR, gain: 5)
AudioKit.start()
//: User Interface Set up
class PlaygroundView: AKPlaygroundView, AKKeyboardDelegate {
var holdDuration = 1.0
override func setup() {
addTitle("ADSR Envelope")
let adsrView = AKADSRView() {
att, dec, sus, rel in
fmWithADSR.attackDuration = att
fmWithADSR.decayDuration = dec
fmWithADSR.sustainLevel = sus
fmWithADSR.releaseDuration = rel
Swift.print("fmWithADSR.attackDuration = \(att)")
Swift.print("fmWithADSR.decayDuration = \(dec)")
Swift.print("fmWithADSR.sustainLevel = \(sus)")
Swift.print("fmWithADSR.releaseDuration = \(rel)\n")
}
adsrView.attackDuration = fmWithADSR.attackDuration
adsrView.decayDuration = fmWithADSR.decayDuration
adsrView.releaseDuration = fmWithADSR.releaseDuration
adsrView.sustainLevel = fmWithADSR.sustainLevel
addSubview(adsrView)
let plot = AKRollingOutputPlot.createView(width: 440, height: 330)
addSubview(plot)
let keyboard = AKKeyboardView(width: 440, height: 100)
keyboard.polyphonicMode = false
keyboard.delegate = self
addSubview(keyboard)
}
func noteOn(note: MIDINoteNumber) {
fmWithADSR.play(noteNumber: note, velocity: 80)
}
func noteOff(note: MIDINoteNumber) {
fmWithADSR.stop(noteNumber: note)
}
}
XCPlaygroundPage.currentPage.needsIndefiniteExecution = true
XCPlaygroundPage.currentPage.liveView = PlaygroundView()
| mit | 3928a396b4644cf6c2b38bf24a75e590 | 29.482759 | 74 | 0.667986 | 4.714667 | false | false | false | false |
disklessGames/cartel | Cartel/CartelTests/BankrollTests.swift | 1 | 1189 | import XCTest
@testable import Cartel
class BankrollTests: XCTestCase {
let sut = Bankroll()
func testShuffle() {
let preShuffleDeck = sut.bankrollCards
sut.shuffle()
let shuffledDards = sut.bankrollCards
var diff = false
for i in 1...10 {
if !diff {
diff = preShuffleDeck[i].type != shuffledDards[i].type
}
}
XCTAssertTrue(diff)
}
func testFlip() {
sut.flip()
XCTAssertTrue(sut.flipped)
}
func testDraw2CardsAtATime() {
let cardsDrawn = sut.drawCards(2)
XCTAssertEqual(cardsDrawn.count, 2)
}
func testNoCardDrawn_bankrollEmpty() {
sut.bankrollCards = [Card]()
XCTAssertNil(sut.drawCard())
}
func testBankRollSetupCreates73Cards() {
XCTAssertEqual(sut.cardsLeft(), 73)
}
func testPocketCardsAre15() {
XCTAssertEqual(sut.pocketCardsCount(), 15)
}
func testRoadCardsAreThereExceptStartingStraights() {
XCTAssertEqual(sut.roadCardsCount(), 14)
}
func testBuildingCardsAre44() {
XCTAssertEqual(sut.buildingCardsCount(), 44)
}
}
| mit | 457e28f98bc0264b8e8c0d051a4983ca | 18.177419 | 70 | 0.599664 | 4.216312 | false | true | false | false |
svenbacia/iTunesSearchAPI | Tests/iTunesSearchAPITests/iTunesSearchAPITests.swift | 1 | 3681 | //
// iTunesSearchAPITest.swift
// iTunesSearchAPI
//
// Created by Sven Bacia on 24.07.16.
// Copyright © 2016 Sven Bacia. All rights reserved.
//
import XCTest
@testable import iTunesSearchAPI
// swiftlint:disable:next type_name
class iTunesSearchAPITests: XCTestCase {
func testInit_DefaultValues() {
let tunes = iTunes()
XCTAssertFalse(tunes.isDebug)
}
func testInit_DebugTrue() {
let tunes = iTunes(debug: true)
XCTAssertTrue(tunes.isDebug)
}
func testBasicSearch() {
let session = FakeURLSession.empty
let client = iTunes(session: session, debug: true)
let task = client.search(for: "Suits") { _ in }
task?.resume()
XCTAssertEqual(session.completedURLs.first!.absoluteString, "https://itunes.apple.com/search?term=Suits&media=all")
}
func testSearchWithOptions() {
let session = FakeURLSession.empty
let client = iTunes(session: session, debug: true)
let task = client.search(for: "Suits", options: Options(country: .germany), completion: { _ in })
task?.resume()
XCTAssertEqual(session.completedURLs.first!.absoluteString, "https://itunes.apple.com/search?country=de&term=Suits&media=all")
}
func testBasicLookupByID() {
let session = FakeURLSession.empty
let client = iTunes(session: session, debug: true)
let task = client.lookup(by: .id("909253")) { _ in }
task?.resume()
XCTAssertEqual(session.completedURLs.first!.absoluteString, "https://itunes.apple.com/lookup?id=909253")
}
func testBasicLookupByIdWithOptions() {
let session = FakeURLSession.empty
let client = iTunes(session: session, debug: true)
let task = client.lookup(by: .id("909253"), options: Options(country: .germany)) { _ in }
task?.resume()
XCTAssertEqual(session.completedURLs.first!.absoluteString, "https://itunes.apple.com/lookup?id=909253&country=de")
}
func testSearch_withServerIssue() {
let session = FakeURLSession.serverIssue
let client = iTunes(session: session, debug: true)
let task = client.search(for: "Suits") { _ in }
task?.resume()
XCTAssertEqual(session.completedURLs.first!.absoluteString, "https://itunes.apple.com/search?term=Suits&media=all")
}
func testSearch_withUnknownResponse() {
let session = FakeURLSession.invalidResponse
let client = iTunes(session: session, debug: true)
let task = client.search(for: "Suits") { _ in }
task?.resume()
XCTAssertEqual(session.completedURLs.first!.absoluteString, "https://itunes.apple.com/search?term=Suits&media=all")
}
func testSearch_withInvalidJSON() {
let session = FakeURLSession.invalidJSON
let client = iTunes(session: session, debug: true)
let task = client.search(for: "Suits") { _ in }
task?.resume()
XCTAssertEqual(session.completedURLs.first!.absoluteString, "https://itunes.apple.com/search?term=Suits&media=all")
}
func testSearch_withMissingData() {
let session = FakeURLSession { (url) -> (iTunes.Result<(Data?, URLResponse?), iTunes.Error>) in
let response = HTTPURLResponse(url: url, statusCode: 200, httpVersion: nil, headerFields: nil)
return (iTunes.Result.success((nil, response)))
}
let client = iTunes(session: session, debug: true)
let task = client.search(for: "Suits") { _ in }
task?.resume()
XCTAssertEqual(session.completedURLs.first!.absoluteString, "https://itunes.apple.com/search?term=Suits&media=all")
}
}
| mit | 05a10b710988153aea6416cf1bbae7fc | 33.392523 | 134 | 0.655163 | 4.120941 | false | true | false | false |
CoderZZF/DYZB | DYZB/DYZB/Classes/Home/Controller/FunnyViewController.swift | 1 | 1089 | //
// FunnyViewController.swift
// DYZB
//
// Created by zhangzhifu on 2017/3/19.
// Copyright © 2017年 seemygo. All rights reserved.
//
import UIKit
private let kTopMargin : CGFloat = 8
class FunnyViewController: BaseAnchorViewController {
// MARK: 懒加载ViewModel对象
fileprivate lazy var funnyVM : FunnyViewModel = FunnyViewModel()
}
extension FunnyViewController {
override func setupUI() {
super.setupUI()
let layout = collectionView.collectionViewLayout as! UICollectionViewFlowLayout
layout.headerReferenceSize = CGSize.zero
collectionView.contentInset = UIEdgeInsets(top: kTopMargin, left: 0, bottom: 0, right: 0)
}
}
extension FunnyViewController {
override func loadData() {
// 1. 给父类中的ViewModel赋值
baseVM = funnyVM
// 2. 请求数据
funnyVM.loadFunnyData {
// 2.1 刷新表格
self.collectionView.reloadData()
// 2.2. 数据请求完成
self.loadDataFinished()
}
}
}
| apache-2.0 | 0ba9521d1e91b84ca54d311caaea5132 | 22.5 | 97 | 0.629594 | 4.764977 | false | false | false | false |
apple/swift-driver | Sources/SwiftDriver/Utilities/Diagnostics.swift | 1 | 6260 | //===--------------- Diagnostics.swift - Swift Driver Diagnostics ---------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2019 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import SwiftOptions
import struct TSCBasic.Diagnostic
extension Diagnostic.Message {
static var error_static_emit_executable_disallowed: Diagnostic.Message {
.error("-static may not be used with -emit-executable")
}
static func error_update_code_not_supported(in mode: CompilerMode) -> Diagnostic.Message {
.error("using '-update-code' in \(mode) mode is not supported")
}
static func error_option_missing_required_argument(option: Option, requiredArg: String) -> Diagnostic.Message {
.error("option '\(option.spelling)' is missing a required argument (\(requiredArg))")
}
static func error_opt_invalid_mapping(option: Option, value: String) -> Diagnostic.Message {
.error("values for '\(option.spelling)' must be in the format 'original=remapped', but '\(value)' was provided")
}
static func error_unsupported_argument(argument: String, option: Option) -> Diagnostic.Message {
.error("unsupported argument '\(argument)' to option '\(option.spelling)'")
}
static func error_option_requires_sanitizer(option: Option) -> Diagnostic.Message {
.error("option '\(option.spelling)' requires a sanitizer to be enabled. Use -sanitize= to enable a sanitizer")
}
static func error_invalid_arg_value(arg: Option, value: String) -> Diagnostic.Message {
.error("invalid value '\(value)' in '\(arg.spelling)'")
}
static func error_invalid_arg_value_with_allowed(arg: Option, value: String, options: [String]) -> Diagnostic.Message {
.error("invalid value '\(value)' in '\(arg.spelling)', valid options are: \(options.joined(separator: ", "))")
}
static func warning_inferring_simulator_target(originalTriple: Triple, inferredTriple: Triple) -> Diagnostic.Message {
.warning("inferring simulator environment for target '\(originalTriple.triple)'; use '-target \(inferredTriple.triple)' instead")
}
static func error_argument_not_allowed_with(arg: String, other: String) -> Diagnostic.Message {
.error("argument '\(arg)' is not allowed with '\(other)'")
}
static func error_unsupported_opt_for_target(arg: String, target: Triple) -> Diagnostic.Message {
.error("unsupported option '\(arg)' for target '\(target.triple)'")
}
static func error_sanitizer_unavailable_on_target(sanitizer: String, target: Triple) -> Diagnostic.Message {
.error("\(sanitizer) sanitizer is unavailable on target '\(target.triple)'")
}
static var error_mode_cannot_emit_module: Diagnostic.Message {
.error("this mode does not support emitting modules")
}
static func error_cannot_read_swiftdeps(file: VirtualPath, reason: String) -> Diagnostic.Message {
.error("cannot read swiftdeps: \(reason), file: \(file)")
}
static func error_bad_module_name(
moduleName: String,
explicitModuleName: Bool
) -> Diagnostic.Message {
let suffix: String
if explicitModuleName {
suffix = ""
} else {
suffix = "; use -module-name flag to specify an alternate name"
}
return .error("module name \"\(moduleName)\" is not a valid identifier\(suffix)")
}
static func error_stdlib_module_name(
moduleName: String,
explicitModuleName: Bool
) -> Diagnostic.Message {
let suffix: String
if explicitModuleName {
suffix = ""
} else {
suffix = "; use -module-name flag to specify an alternate name"
}
return .error("module name \"\(moduleName)\" is reserved for the standard library\(suffix)")
}
static func error_bad_module_alias(_ arg: String,
moduleName: String,
formatted: Bool = true,
isDuplicate: Bool = false) -> Diagnostic.Message {
if !formatted {
return .error("invalid format \"\(arg)\"; use the format '-module-alias alias_name=underlying_name'")
}
if arg == moduleName {
return .error("module alias \"\(arg)\" should be different from the module name \"\(moduleName)\"")
}
if isDuplicate {
return .error("the name \"\(arg)\" is already used for a module alias or an underlying name")
}
return .error("bad module alias \"\(arg)\"")
}
static var error_hermetic_seal_cannot_have_library_evolution: Diagnostic.Message {
.error("Cannot use -experimental-hermetic-seal-at-link with -enable-library-evolution")
}
static var error_hermetic_seal_requires_lto: Diagnostic.Message {
.error("-experimental-hermetic-seal-at-link requires -lto=llvm-full or -lto=llvm-thin")
}
static func warning_no_such_sdk(_ path: String) -> Diagnostic.Message {
.warning("no such SDK: \(path)")
}
static func warning_no_sdksettings_json(_ path: String) -> Diagnostic.Message {
.warning("Could not read SDKSettings.json for SDK at: \(path)")
}
static func warning_fail_parse_sdk_ver(_ version: String, _ path: String) -> Diagnostic.Message {
.warning("Could not parse SDK version '\(version)' at: \(path)")
}
static func error_sdk_too_old(_ path: String) -> Diagnostic.Message {
.error("Swift does not support the SDK \(path)")
}
static func error_unknown_target(_ target: String) -> Diagnostic.Message {
.error("unknown target '\(target)'")
}
static func warning_option_overrides_another(overridingOption: Option, overridenOption: Option) -> Diagnostic.Message {
.warning("ignoring '\(overridenOption.spelling)' because '\(overridingOption.spelling)' was also specified")
}
static func error_expected_one_frontend_job() -> Diagnostic.Message {
.error("unable to handle compilation, expected exactly one frontend job")
}
static func error_expected_frontend_command() -> Diagnostic.Message {
.error("expected a swift frontend command")
}
}
| apache-2.0 | f66703967cc1b05d4528ba14af235376 | 38.872611 | 133 | 0.670927 | 4.278879 | false | false | false | false |
fthomasmorel/insapp-iOS | Insapp/AssociationSearchCell.swift | 1 | 1372 | //
// AssociationSearchCell.swift
// Insapp
//
// Created by Guillaume Courtet on 29/11/2016.
// Copyright © 2016 Florent THOMAS-MOREL. All rights reserved.
//
import UIKit
class AssociationSearchCell: UICollectionViewCell {
@IBOutlet weak var associationImageView: UIImageView!
@IBOutlet weak var associationNameLabel: UILabel!
var more = 0
override func layoutSubviews() {
if(more == 1) {
super.layoutSubviews()
self.associationImageView.frame = CGRect(x: 8, y: 0, width: self.frame.width-16, height: self.frame.width-16)
self.associationImageView.layer.cornerRadius = self.associationImageView.frame.width/2
self.associationImageView.layer.masksToBounds = true
self.associationImageView.backgroundColor = kWhiteColor
self.associationImageView.layer.borderColor = kLightGreyColor.cgColor
self.associationImageView.layer.borderWidth = 1
self.associationNameLabel.frame = CGRect(x: 0, y: self.frame.height-15, width: self.frame.width, height: 15)
}
}
func load(association : Association){
let photo_url = kCDNHostname + association.profilePhotoURL!
self.associationImageView.downloadedFrom(link: photo_url)
self.associationNameLabel.text = "@\(association.name!.lowercased())"
}
}
| mit | 5f9e095b57a517f1423dba76dc1b32fd | 37.083333 | 121 | 0.68636 | 4.465798 | false | false | false | false |
googlearchive/science-journal-ios | ScienceJournal/UI/ExperimentCardHeaderView.swift | 1 | 7707 | /*
* Copyright 2019 Google LLC. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import UIKit
import third_party_objective_c_material_components_ios_components_Buttons_Buttons
import third_party_objective_c_material_components_ios_components_Palettes_Palettes
import third_party_objective_c_material_components_ios_components_Typography_Typography
/// The timestamp, caption and menu options view for all cells in an experiment or Trial Detail
/// view.
class ExperimentCardHeaderView: UIView {
// MARK: - Constants
let innerHorizontalSpacing: CGFloat = 8.0
static let iconDimension: CGFloat = 24.0
private let innerButtonSpacing: CGFloat = 14.0
// MARK: - Properties
/// The timestamp label.
let headerTimestampLabel = UILabel()
/// The invisible button wrapping the timestamp and timestamp dot, only tappable if
/// `isRelativeTimestamp` is true.
let timestampButton = UIButton()
/// The comment button for the header.
let commentButton = MDCFlatButton()
/// The menu button for the header.
let menuButton = MenuButton()
/// Override the accessibility label to set the inner wrapper instead.
override var accessibilityLabel: String? {
didSet {
accessibilityWrappingView.accessibilityLabel = accessibilityLabel
}
}
// A dot icon placed on the leading side of the timestamp in relative timestamp situations like
// Trial detail.
private let timestampDot = UIImageView(image: UIImage(named: "ic_lens_18pt"))
// The outer containing stack view for this header.
private let outerStack = UIStackView()
// The accessibility wrapping view that reads the timestamp and allows for selection in any open
// region of the view.
private let accessibilityWrappingView = UIView()
/// Show or hide the caption creation icon. Caption icons are hidden when there is a caption set
/// on the owner or when the owner doesn't support captions (e.g. text notes).
var showCaptionButton: Bool = true {
didSet {
commentButton.isHidden = !showCaptionButton
}
}
/// Show or hide the menu icon.
var showMenuButton: Bool = true {
didSet {
menuButton.isHidden = !showMenuButton
}
}
/// If the timestamp for this view is relative, show the leading dot.
var isTimestampRelative: Bool = false {
didSet {
timestampDot.isHidden = !isTimestampRelative
// We use an invisible button on top of the timestamp to allow a user to tap the timestamp
// to move the chart to that time. But when we are not in relative timestamp mode, we need to
// remove that button entirely because it should not be an accessible element in VoiceOver.
if isTimestampRelative {
outerStack.addSubview(timestampButton)
timestampButton.topAnchor.constraint(equalTo: topAnchor).isActive = true
timestampButton.leadingAnchor.constraint(equalTo: leadingAnchor).isActive = true
timestampButton.trailingAnchor.constraint(
equalTo: headerTimestampLabel.trailingAnchor, constant: -20).isActive = true
timestampButton.bottomAnchor.constraint(equalTo: bottomAnchor).isActive = true
} else {
timestampButton.removeFromSuperview()
}
}
}
static let height: CGFloat = {
// Calculate the header stack view's height, which is either the label's height or the icon
// (whichever is bigger) + padding.
let headerHeight = String.runReviewActivityLabel.labelHeight(
withConstrainedWidth: 0,
font: MDCTypography.fontLoader().regularFont(ofSize: ExperimentCardView.timestampFontSize))
return max(headerHeight, ExperimentCardHeaderView.iconDimension) +
(ExperimentCardView.headerFooterVerticalPadding * 2)
}()
// MARK: - Public
override required init(frame: CGRect) {
super.init(frame: frame)
configureView()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
configureView()
}
override var intrinsicContentSize: CGSize {
return CGSize(width: UIView.noIntrinsicMetric, height: ExperimentCardHeaderView.height)
}
// MARK: - Private
private func configureView() {
autoresizingMask = [.flexibleWidth, .flexibleHeight]
// Relative timestamp dot, for use in Trial detail timelines.
timestampDot.tintColor = .appBarReviewBackgroundColor
timestampDot.setContentHuggingPriority(.defaultHigh, for: .horizontal)
timestampDot.isHidden = true
timestampDot.translatesAutoresizingMaskIntoConstraints = false
outerStack.addArrangedSubview(timestampDot)
// Timestamp label.
headerTimestampLabel.textColor = MDCPalette.grey.tint500
headerTimestampLabel.font = MDCTypography.fontLoader().regularFont(
ofSize: ExperimentCardView.timestampFontSize)
headerTimestampLabel.translatesAutoresizingMaskIntoConstraints = false
headerTimestampLabel.isAccessibilityElement = false
outerStack.addArrangedSubview(headerTimestampLabel)
// The comment button.
commentButton.setImage(UIImage(named: "ic_comment"), for: .normal)
commentButton.tintColor = MDCPalette.grey.tint500
commentButton.inkColor = .clear
commentButton.autoresizesSubviews = false
commentButton.contentEdgeInsets = .zero
commentButton.imageEdgeInsets = .zero
commentButton.translatesAutoresizingMaskIntoConstraints = false
commentButton.setContentHuggingPriority(.required, for: .horizontal)
commentButton.accessibilityLabel = String.noteCaptionHint
// The menu button.
menuButton.tintColor = commentButton.tintColor
menuButton.translatesAutoresizingMaskIntoConstraints = false
// Button wrapper to give extra padding between the two buttons.
let buttonWrapper = UIStackView(arrangedSubviews: [commentButton, menuButton])
buttonWrapper.axis = .horizontal
buttonWrapper.alignment = .center
buttonWrapper.spacing = innerButtonSpacing
buttonWrapper.translatesAutoresizingMaskIntoConstraints = false
outerStack.addArrangedSubview(buttonWrapper)
// The wrapping stackView for the header.
addSubview(outerStack)
outerStack.axis = .horizontal
outerStack.alignment = .center
outerStack.spacing = innerHorizontalSpacing
outerStack.translatesAutoresizingMaskIntoConstraints = false
outerStack.layoutMargins = UIEdgeInsets(top: ExperimentCardView.headerFooterVerticalPadding,
left: ExperimentCardView.innerHorizontalPadding,
bottom: ExperimentCardView.headerFooterVerticalPadding,
right: ExperimentCardView.innerHorizontalPadding)
outerStack.isLayoutMarginsRelativeArrangement = true
outerStack.pinToEdgesOfView(self)
// The invisible timestamp button.
timestampButton.translatesAutoresizingMaskIntoConstraints = false
timestampButton.accessibilityLabel = String.selectTimestampContentDescription
// Accessibility wrapping view, which sits behind all other elements to allow a user to "grab"
// anywhere in this view to read the timestamp.
configureAccessibilityWrappingView(accessibilityWrappingView, traits: .staticText)
}
}
| apache-2.0 | 3ab7ec8aedaf5157ca9036d8563ebf70 | 39.140625 | 99 | 0.742053 | 5.103974 | false | false | false | false |
iAugux/Weboot | Weboot/PanDirectionGestureRecognizer+Addtions.swift | 1 | 1410 | //
// PanDirectionGestureRecognizer+Addtions.swift
// TinderSwipeCellSwift
//
// Created by Augus on 8/23/15.
// Copyright © 2015 iAugus. All rights reserved.
// http://stackoverflow.com/a/30607392/4656574
import UIKit
import UIKit.UIGestureRecognizerSubclass
enum PanDirection {
case Vertical
case Horizontal
}
class PanDirectionGestureRecognizer: UIPanGestureRecognizer {
let direction : PanDirection
init(direction: PanDirection, target: AnyObject, action: Selector) {
self.direction = direction
super.init(target: target, action: action)
}
override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent) {
super.touchesMoved(touches, withEvent: event)
if state == .Began {
let velocity = velocityInView(self.view!)
switch direction {
// disable local gesture when locationInView < 44 to ensure UIScreenEdgePanGestureRecognizer is only avalible
// The comfortable minimum size of tappable UI elements is 44 x 44 points.
case .Horizontal where fabs(velocity.y) > fabs(velocity.x) || locationInView(self.view).x <= 44:
state = .Cancelled
case .Vertical where fabs(velocity.x) > fabs(velocity.y):
state = .Cancelled
default:
break
}
}
}
} | mit | 6c9d91ca9daebf4a02a8abb81126d5a5 | 31.045455 | 125 | 0.638041 | 4.858621 | false | false | false | false |
kgleong/OMAKOView | Example/OMAKOView/PopUpViewController.swift | 1 | 5208 | import UIKit
import OMAKOView
class PopUpViewController: UIViewController {
@IBOutlet weak var textPopUpTypeSegmentedControl: UISegmentedControl!
@IBOutlet weak var spinnerTypeSegmentedControl: UISegmentedControl!
var activeSegmentedControl: UISegmentedControl?
var inactiveSegmentedControl: UISegmentedControl?
var popUpView: OMAKOPopUpView?
var defaultTitleString = NSMutableAttributedString(string: "Title Displayed Here")
var defaultLoadingString = NSMutableAttributedString(string: "Loading")
override open func viewDidLoad() {
super.viewDidLoad()
activeSegmentedControl = textPopUpTypeSegmentedControl
inactiveSegmentedControl = spinnerTypeSegmentedControl
spinnerTypeSegmentedControl.selectedSegmentIndex = UISegmentedControlNoSegment
}
override open func viewWillAppear(_ animated: Bool) {
popUpView?.hide(completion: nil)
}
// MARK: - Pop Up View
fileprivate func displayTitleOnlyPopUp() {
createPopUpView()
guard let popUpView = popUpView else {
return
}
popUpView.titleText = defaultTitleString
popUpView.display(parentView: view, withDuration: nil, completion: nil)
}
fileprivate func displayBody() {
createPopUpView()
guard let popUpView = popUpView else {
return
}
popUpView.bodyText = NSMutableAttributedString(
string: "Text for the pop up body displayed here."
)
// Passes in an on completion handler that logs a message.
popUpView.display(parentView: view, withDuration: nil) { print("Popup with body displayed") }
}
fileprivate func displayTitleBodyPopUpWithFade() {
createPopUpView()
guard let popUpView = popUpView else {
return
}
popUpView.titleText = defaultTitleString
let duration: TimeInterval = 5.0
popUpView.bodyText = NSMutableAttributedString(
string: "This pop up will automatically disappear in \(String(duration)) seconds)"
)
popUpView.display(parentView: view, withDuration: duration, completion: nil)
}
fileprivate func displaySquareSpinner() {
createPopUpView()
guard let popUpView = popUpView else {
return
}
popUpView.bodyText = NSMutableAttributedString(string: "Loading")
popUpView.displaySpinner(parentView: view, spinnerType: .square)
}
fileprivate func displaySquareSpinnerWithTitle() {
createPopUpView()
guard let popUpView = popUpView else {
return
}
popUpView.titleText = defaultLoadingString
popUpView.bodyText = NSMutableAttributedString(string: "Your request will be completed shortly.")
popUpView.displaySpinner(parentView: view, spinnerType: .square)
}
fileprivate func displayStarSpinner() {
createPopUpView()
guard let popUpView = popUpView else {
return
}
popUpView.titleText = defaultLoadingString
popUpView.spinnerSizeInPoints = 40
popUpView.displaySpinner(parentView: view, spinnerType: .star)
}
fileprivate func createPopUpView() {
popUpView?.hide(completion: nil)
popUpView = OMAKOPopUpView()
popUpView!.layer.borderColor = UIColor(red: 0.4, green: 0.4, blue: 0.4, alpha: 1.0).cgColor
popUpView!.layer.borderWidth = 2
}
// MARK: - Interface Builder Actions
@IBAction func onSegmentedValueChange(_ sender: UISegmentedControl) {
setActive(segmentedControl: sender)
}
@IBAction func onDisplayPopUp(_ sender: UIButton) {
guard let activeSegmentedControl = activeSegmentedControl else {
return
}
/// Text only pop ups
if activeSegmentedControl == textPopUpTypeSegmentedControl {
switch activeSegmentedControl.selectedSegmentIndex {
case 0:
displayTitleOnlyPopUp()
case 1:
displayBody()
case 2:
displayTitleBodyPopUpWithFade()
default: break
}
}
/// Spinner pop ups.
else if activeSegmentedControl == spinnerTypeSegmentedControl {
switch activeSegmentedControl.selectedSegmentIndex {
case 0:
displaySquareSpinner()
case 1:
displaySquareSpinnerWithTitle()
case 2:
displayStarSpinner()
default: break
}
}
}
@IBAction func onHideTap(_ sender: UIButton) {
guard let popUpView = popUpView else {
return
}
popUpView.hide(completion: nil)
}
fileprivate func setActive(segmentedControl: UISegmentedControl) {
if activeSegmentedControl != segmentedControl {
inactiveSegmentedControl = activeSegmentedControl
inactiveSegmentedControl?.selectedSegmentIndex = UISegmentedControlNoSegment
activeSegmentedControl = segmentedControl
}
}
}
| mit | 9c19b33754d6e841f335f4fa43926590 | 30 | 105 | 0.639401 | 5.618123 | false | false | false | false |
paulz/ImageCoordinateSpace | Example/Visual.playground/Pages/Scale To Fill.xcplaygroundpage/Contents.swift | 1 | 879 | //: [Previous](@previous)
import UIKit
import ImageCoordinateSpace
//: Scale
let image = #imageLiteral(resourceName: "rose.jpg")
let imageView = UIImageView(image: image)
let square = CGSize(width: 100, height: 100)
imageView.bounds = CGRect(origin: CGPoint.zero, size: square)
imageView.backgroundColor = UIColor.green
imageView.contentMode = .scaleToFill
let imageSpace = imageView.contentSpace()
let topLeft = imageSpace.convert(CGPoint.zero, to: imageView)
//: top left corners should be the same
assert(topLeft == CGPoint.zero)
image.size
let bottomRight = CGPoint(x: image.size.width, y: image.size.height)
let lowerRight = imageSpace.convert(bottomRight, to: imageView)
//: bottom right corners should be the same
assert(lowerRight.x == square.width, "should the view width")
assert(lowerRight.y == square.height, "should the view height")
imageView
//: [Next](@next)
| mit | db3334f5d6a794fdae74c485f5b4a834 | 32.807692 | 68 | 0.76223 | 3.788793 | false | false | false | false |
aestesis/Aether | Sources/Aether/Foundation/View.swift | 1 | 39060 | //
// View.swift
// Aether
//
// Created by renan jegouzo on 27/02/2016.
// Copyright © 2016 aestesis. 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
//////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////
open class View : NodeUI {
//////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////
public enum DrawMode {
//case device
case superview
case surface
}
public struct Grid {
public struct Disposition {
public var begin:Bool
public var between:Bool
public var end:Bool
public var count:Int {
return (begin ? 1 : 0) + (end ? 1 : 0)
}
public init(begin:Bool=true,between:Bool=true,end:Bool=true) {
self.begin = begin
self.between = between
self.end = end
}
}
public var marginFloat:Size=Size.zero
public var marginAbs:Size=Size.zero
public var size:SizeI=SizeI(1,1)
public var horizontal:Disposition=Disposition()
public var vertical:Disposition=Disposition()
public var spaces:PointI {
return PointI(x:horizontal.count+(horizontal.between ? size.width-1 : 0),y:vertical.count+(vertical.between ? size.height-1 : 0))
}
}
public struct Layout {
public static var marginMultiplier:Double = 1.0
public var placement:Rect=Rect(x:0,y:0,w:1,h:1)
public var align:Align=Align.none
public var marginLeft:Double=0
public var marginRight:Double=0
public var marginTop:Double=0
public var marginBottom:Double=0
public var aspect:Double=0
public var margin: Double {
get { return marginLeft }
set(m) {
marginLeft=m
marginRight=m
marginTop=m
marginBottom=m
}
}
public var origin:Point {
get { return placement.origin }
set(p) {
placement.origin = p
if placement.width == 0 {
placement.width = 1
}
if placement.height == 0 {
placement.height = 1
}
}
}
public var size : Size {
get { return placement.size }
set(s) {
placement.size=s
}
}
public init(placement:Rect?=nil,origin:Point?=nil,size:Size?=nil,align:Align?=nil,margin:Double?=nil,marginLeft:Double?=nil,marginRight:Double?=nil,marginTop:Double?=nil,marginBottom:Double?=nil,aspect:Double=0)
{
if let p=placement {
self.placement=p
}
if let o=origin {
self.placement.origin=o
}
if let s=size {
self.placement.size=s
}
if let a=align {
self.align=a
}
if let m=margin {
self.margin=m*Layout.marginMultiplier
}
if let m=marginLeft {
self.marginLeft=m*Layout.marginMultiplier
}
if let m=marginRight {
self.marginRight=m*Layout.marginMultiplier
}
if let m=marginTop {
self.marginTop=m*Layout.marginMultiplier
}
if let m=marginBottom {
self.marginBottom=m*Layout.marginMultiplier
}
self.aspect=aspect
}
public static var none:Layout {
return Layout(align:Align.none)
}
}
public struct Transform {
public var position:Vec3
var _scale:Vec3
public var rotation:Vec3
public var scale : Size {
get { return Size(_scale.x,_scale.y) }
set(s) {
_scale.x = s.width
_scale.y = s.height
}
}
public var perspective:Double
public var offset:Vec3
public var matrix:Mat4 {
return Mat4.scale(_scale)*Mat4.rotX(rotation.x)*Mat4.rotY(rotation.y)*Mat4.rotZ(rotation.z)*Mat4.translation(position+offset)
}
public func matrixCentered(_ p:Point) -> Mat4 {
let v=Vec3(p)
return Mat4.translation(-v)*Mat4.scale(_scale)*Mat4.rotX(rotation.x)*Mat4.rotY(rotation.y)*Mat4.rotZ(rotation.z)*Mat4.translation(position+v+offset)
}
public func matrixCenteredRender(_ p:Point) -> Mat4 {
let v=Vec3(p)
if perspective>0 {
let mp = Mat4.localPerspective(perspective)
return Mat4.translation(-v)*Mat4.scale(_scale)*Mat4.rotX(rotation.x)*Mat4.rotY(rotation.y)*Mat4.rotZ(rotation.z)*mp*Mat4.translation(position+v+offset)
}
return Mat4.translation(-v)*Mat4.scale(_scale)*Mat4.rotX(rotation.x)*Mat4.rotY(rotation.y)*Mat4.rotZ(rotation.z)*Mat4.translation(position+v+offset)
}
static var identity:Transform {
return Transform(position:Vec3.zero, _scale:Vec3(x:1,y:1,z:1), rotation:Vec3.zero, perspective:0, offset:Vec3.zero)
}
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////
var _layouts=[String:Layout]()
var _size:Size=Size.zero
var _needsLayout:Bool=false
var swipeStart=TouchLocation()
var swipeCurrent=Swipe.none
var swipeOK = false
var nframe:Int=0
var surface:Bitmap? = nil
var _effect:Effect? = nil
var touchCaptured:View?=nil
//////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////
public let onEnterRendering=Event<Void>()
public let onDraw=Event<Graphics>()
public let onOverlay=Event<Graphics>()
public let onResize=Event<Size>()
public let onSubviewAttached=Event<View>()
public let onSubviewDetached=Event<View>()
public let onSubviewsChanged=Event<Void>()
public let onFocus=Event<Bool>()
//////////////////////////////////////////////////////////////////////////////////////////////////////////
public private(set) var id:String
public var background:Color?
public var color:Color=Color.white {
didSet {
if oldValue != color {
self.needsRedraw = true
}
}
}
public var enabled:Bool=true
public var grid:Grid=Grid()
public var swipe:Swipe=Swipe.none
public var edgeSwipe = false
public var transform:Transform=Transform.identity
public var visible:Bool=true
public var opaque:Bool=false
public var clipping = true
public private(set) var subviews:[View]=[View]()
public var needsRedraw = true
public var drawMode:DrawMode = .superview
public var depthOrdering = false
//////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////
public var bounds:Rect {
return Rect(o:Point.zero,s:size)
}
public var center : Point {
get { return frame.origin+localCenter }
set(p) { frame.origin = p-localCenter }
}
public var computedColor:Color {
var a = self.color.a
var v:View? = self.superview
while v != nil {
a *= v!.color.a
v = v!.superview
}
return Color(a:a,rgb:color)
}
func dispatchLayout() {
if needsLayout {
needsLayout=false
arrange()
for v in subviews {
v.dispatchLayout()
}
}
}
var memoDrawMode = DrawMode.superview
public var afterEffect : Effect? {
get { return _effect }
set(e) {
if _effect != e, let oe = _effect {
oe.detach()
} else if e != nil {
self.memoDrawMode = self.drawMode
self.drawMode = .surface
}
_effect = e
if e == nil {
self.drawMode = self.memoDrawMode
}
}
}
open func arrange() {
let m=grid.marginAbs+grid.marginFloat*size/Size(grid.size)
let c=(size-Size(grid.spaces)*m)/Size(grid.size)
let mb = Size(grid.horizontal.begin ? m.w : 0,grid.vertical.begin ? m.h : 0)
for v in subviews {
if let l=v.layout {
if l.align != Align.none {
let lp=l.placement
var f = Rect (x:mb.w + lp.x * (m.w + c.w) + l.marginLeft, y:mb.h + lp.y * (m.h + c.h) + l.marginTop, w:lp.w * c.w + (lp.w - 1) * m.w - (l.marginLeft + l.marginRight), h:lp.h * c.h + (lp.h - 1) * m.h - (l.marginTop + l.marginBottom));
if l.align.hasFlag(.fill) && l.aspect > 0 {
if l.aspect > f.size.ratio {
let o=f.height
f.height = f.width / l.aspect
f.y = f.y + ( o - f.height) * 0.5
}
}
if !l.align.hasFlag(.fillHeight) {
if l.align.hasFlag(.center) {
f.y = f.y + (f.height - v.size.height) * 0.5
} else if l.align.hasFlag(.bottom) {
f.y = f.bottom - v.size.height
}
}
if !l.align.hasFlag(.fillWidth) {
if l.align.hasFlag(.middle) {
f.x = f.x + (f.width - v.size.width) * 0.5
} else if l.align.hasFlag(.right) {
f.x = f.right - v.size.width
}
}
v.frame = viewport!.pixPerfect(f)
}
}
}
}
open func draw(to g:Graphics) {
onDraw.dispatch(g)
}
open func overlay(to g:Graphics) {
onOverlay.dispatch(g)
}
public func focus(_ focused:Bool) {
if let viewport = viewport {
viewport.setFocus(self,focus:focused)
}
}
public var focused : Bool {
if let viewport = viewport {
return viewport.focusedView == self
}
return false
}
public var frame:Rect {
get { return Rect(o:Point(transform.position.x,transform.position.y),s:size) }
set(r) {
self.transform.position.x=r.x
self.transform.position.y=r.y
self.size=r.size
}
}
open func getSubview(ref:View,increment:Int) -> View? {
for i in 0..<subviews.count {
if subviews[i] == ref {
let n = i + increment
if n>=0 && n<subviews.count {
return subviews[n]
}
return nil
}
}
return nil
}
public func child<T:View>(recursive:Bool=false) -> T? {
for v0 in subviews {
if let v=v0 as? T {
return v
}
if recursive, let s = v0.child(recursive:true) as T? {
return s
}
}
return nil
}
public func children<T:View>(recursive:Bool=false) -> [T] {
var s=[T]()
for v0 in subviews {
if let v=v0 as? T {
s.append(v)
}
if recursive {
s += v0.children(recursive:true) as [T]
}
}
return s
}
public func find(key:String) -> [View] {
var views=[View]()
if(self.classes.contains(key: key)) {
views.append(self);
}
for v in subviews {
views.append(contentsOf: v.find(key:key))
}
return views;
}
public func find(keys:[String]) -> [View] {
var views=[View]()
if(self.classes.contains(keys: keys)) {
views.append(self);
}
for v in subviews {
views.append(contentsOf: v.find(classes: classes))
}
return views;
}
public func find(classes:Classes) -> [View] {
return self.find(keys:classes.keys)
}
open func key(_ k: Key) {
superview?.key(k)
}
public var layout:Layout? {
get {
if let s=superview {
return s._layouts[self.id]
}
return nil
}
set(l) {
if let s=superview {
if l == nil {
s._layouts.removeValue(forKey: self.id)
} else {
s._layouts[self.id]=l
s.needsLayout = true
}
}
}
}
open var localCenter : Point {
return self.bounds.center // rotation center, can be overridden
}
public func localTo(_ subview:View,_ p:Point) -> Point { // superview coord to subview coord
let m = self.matrix(subview).inverted // why inverted ??
let v = m.transform(Vec4(x:p.x,y:p.y,z:0,w:1))
return Point(v.x,v.y)
}
public func localFrom(_ subview:View,_ p:Point) -> Point { // superview coord from subview coord
let m = self.matrix(subview) // should be inverted..
let v = m.transform(Vec4(x:p.x,y:p.y,z:0,w:1))
return Point(v.x,v.y)
}
public func matrix(_ subview:View) -> Mat4 {
var v:View?=subview
var m = Mat4.identity
while v != nil && v != self { // inverted path
m = m * v!.matrix // inverted mul
v = v!.superview
}
return m // inverted + inverted = normal ?
}
public var matrix : Mat4 {
return transform.matrixCentered(localCenter)
}
public var matrixRender : Mat4 {
return transform.matrixCenteredRender(localCenter)
}
#if os(OSX)
var viewOver=Set<View>()
open func mouse(_ mo:MouseOver) {
switch mo.state {
case .exited:
for v in viewOver {
v.mouse(MouseOver(state:.exited))
}
viewOver.removeAll()
//Debug.info("exited \(self.className)")
break
case .wheel:
if let touch = _touch {
switch swipe {
case .both:
if touch.magnetSwipe(mo.delta) {
return
}
break
case .horizontal:
if abs(mo.delta.x) > abs(mo.delta.y) && touch.magnetSwipe(mo.delta) {
return
}
break
case .vertical:
if abs(mo.delta.x) < abs(mo.delta.y) && touch.magnetSwipe(mo.delta) {
return
}
break
default:
break
}
}
fallthrough
case .entered,.moved:
let rvo=viewOver
for v in rvo {
let p=localTo(v, mo.position)
if !v.bounds.contains(p) {
v.mouse(MouseOver(state:.exited))
viewOver.remove(v)
}
}
var i=subviews.count-1
for _ in subviews {
let v=subviews[i]
if !viewOver.contains(v) {
let p=localTo(v,mo.position)
if v.visible && v.color.a>0.01 && v.bounds.contains(p) {
viewOver.insert(v)
v.mouse(MouseOver(state:.entered,position:p,buttons:mo.buttons))
}
}
i -= 1
}
if mo.state == .wheel || mo.state == .moved {
for v in viewOver {
v.mouse(MouseOver(state:mo.state,position:localTo(v,mo.position),delta:mo.delta,buttons:mo.buttons))
}
}
break
default:
break
}
}
#else
open func mouse(_ mo:MouseOver) {
Debug.notImplemented()
}
#endif
public func order(before v:View) {
if let superview = superview, v != self {
superview.subviews.remove(at:superview.subviews.index(of:self)!)
superview.subviews.insert(self,at:superview.subviews.index(of:v)!)
}
}
public func order(after v:View) {
if let superview = superview, v != self {
superview.subviews.remove(at:superview.subviews.index(of:self)!)
superview.subviews.insert(self,at:superview.subviews.index(of:v)!+1)
}
}
public var needsLayout : Bool {
get { return _needsLayout }
set(b) {
if b {
if let s=superview {
s.needsLayout=true
} else if let viewport = viewport {
viewport.needsLayout=true
}
}
_needsLayout=b
}
}
public var orientation : Orientation {
if let s=superview {
return s.orientation
}
return viewport!.orientation
}
public var position : Point {
get { return frame.origin }
set(p) { frame.origin = p }
}
public var rendered:Bool {
return ((viewport!.nframes-nframe) <= 1)
}
open var size: Size {
get { return _size }
set(s) {
if s != _size {
if s.width<=0 || s.height<=0 {
Debug.warning("warning, view \(self.className), size set to empty area \(s)")
}
_size=s;
needsLayout=true
onResize.dispatch(s)
}
}
}
public func snapshot(_ fn:@escaping (Bitmap)->()) {
if let viewport = viewport {
viewport.snapshot(view:self, { b in
if let b=b {
fn(b)
}
})
}
}
public func snapshotDepth(_ fn:@escaping (Bitmap)->()) { // returning bitmap["depth"] contains [Float32]
if let viewport = viewport {
viewport.snapshotDepth(view:self) { b in
if let b=b {
fn(b)
}
}
}
}
public func subview(_ p:Point,recursive:Bool=false) -> View? {
var i=subviews.count-1
for _ in 0..<subviews.count {
let v=subviews[i]
let pl=localTo(v,p)
if v.bounds.contains(pl) {
if recursive && v.subviews.count>0 {
if let vs=v.subview(pl,recursive:true) {
return vs
}
}
return v
}
i -= 1
}
return nil
}
public var superview:View? {
if let v = parent as? View {
return v
}
return nil
}
public func touches(_ touches:[TouchLocation]) -> Bool {
let dispatch:([TouchLocation])->(View?) = { touches in
var i=self.subviews.count - 1
for _ in 0..<self.subviews.count {
let v=self.subviews[i]
if v.visible && v.enabled && v.color.a > 0.9 {
let p=self.localTo(v, touches[0].position)
if v.bounds.contains(p) {
if v.touches(TouchLocation.transform(touches:touches,matrix:v.matrix)) {
return v
}
}
}
i -= 1
}
return nil
}
if !visible || !enabled {
return false
}
if let touch=_touch {
if swipe == .horizontal || swipe == .vertical {
if touches.count == 1 {
let t = touches[0]
switch t.state {
case .pressed:
swipeStart = t
swipeCurrent = Swipe.none
//Debug.warning("\(self.className): swipe pressed")
touchCaptured = dispatch(touches)
swipeOK = false
if edgeSwipe {
var p = t.position / self.size
p.x = p.x.truncatingRemainder(dividingBy: 1)
p.y = p.y.truncatingRemainder(dividingBy: 1)
//Debug.warning("edgeSwipe start: \(p)")
switch swipe {
case .horizontal:
if p.x<0.07 || p.x>0.93 {
swipeOK = true
}
case .vertical:
if p.y<0.07 || p.y>0.93 {
swipeOK = true
}
case .both:
if p.x<0.07 || p.x>0.93 {
swipeOK = true
}
if p.y<0.07 || p.y>0.93 {
swipeOK = true
}
default:
break
}
} else {
swipeOK = true
}
//Debug.warning("edgeSwipe: \(swipeOK)")
return true
case .moved:
//Debug.warning("\(self.className): swipe moved")
if swipeCurrent == Swipe.none && swipeOK {
let d = (t.position-swipeStart.position).length
if d > touch.distanceAcceptMove {
swipeCurrent = (abs(t.position.x-swipeStart.position.x) > abs(t.position.y-swipeStart.position.y)) ? Swipe.horizontal : Swipe.vertical
if swipeCurrent.match(swipe:swipe) {
let _ = touch.touches([swipeStart])
if let v=touchCaptured {
let _ = v.touches([TouchLocation(state:.cancelled,position:t.position,pressure:0)])
touchCaptured = nil
}
}
}
}
if swipeCurrent.match(swipe:swipe) {
return touch.touches(touches)
}
if let v = touchCaptured {
//Debug.info("touchCaptured, moved: \(v.className)")
return v.touches(TouchLocation.transform(touches:touches,matrix:v.matrix))
}
case .released,.cancelled:
//Debug.warning("\(self.className): swipe released")
if swipeCurrent.match(swipe: swipe) {
return touch.touches(touches)
} else if let v=touchCaptured {
let _ = v.touches(TouchLocation.transform(touches:touches,matrix:v.matrix))
touchCaptured = nil
//Debug.info("touchCaptured, \(t.state): \(v.className)")
} else if touch.onClick.count>0 { // fast click
if touch.touches([swipeStart]) {
let _ = touch.touches(touches)
}
}
swipeCurrent = Swipe.none
swipeOK = false
break
}
return true
} else {
let _ = dispatch(touches) // multitouch TODO: must be done better
}
} else { // no swipe hook
let t = touches[0]
switch t.state {
case .pressed:
touchCaptured = dispatch(touches)
if touchCaptured == nil {
return touch.touches(touches)
}
return touchCaptured != nil
case .moved:
if let v=touchCaptured {
//Debug.info("touchCaptured, \(t.state): \(v.className)")
return v.touches(TouchLocation.transform(touches:touches,matrix:v.matrix))
} else {
return touch.touches(touches)
}
case .released,.cancelled:
if let v=touchCaptured {
//Debug.info("touchCaptured, \(t.state): \(v.className)")
let r = v.touches(TouchLocation.transform(touches:touches,matrix:v.matrix))
touchCaptured = nil
return r
} else {
return touch.touches(touches)
}
}
}
} else { // no TouchManager
let t = touches[0]
switch t.state {
case .pressed:
touchCaptured = dispatch(touches)
return touchCaptured != nil
case .moved:
if let v=touchCaptured {
//Debug.info("touchCaptured, \(t.state): \(v.className)")
return v.touches(TouchLocation.transform(touches:touches,matrix:v.matrix))
}
case .released,.cancelled:
if let v=touchCaptured {
let r = v.touches(TouchLocation.transform(touches:touches,matrix:v.matrix))
//Debug.info("touchCaptured, \(t.state): \(v.className)")
touchCaptured = nil
return r
}
}
}
return false
}
private var _touch:TouchManager?
public var touch:TouchManager {
if let t=_touch {
return t
} else {
let t=TouchManager(view:self)
_touch=t
return t
}
}
open func add(view:View) {
self.subviews.append(view)
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////
public init(viewport:Viewport) {
self.id = ß.alphaID
super.init(parent: viewport)
if !viewport.uiThread {
Debug.error("error, View added outside UI thread",#file,#line)
}
viewport.rootView=self
self._size=viewport.size
self.needsLayout=true
self.viewport!.pulse.once {
self.onResize.dispatch(self.bounds.size)
}
}
public init(superview:View,layout:Layout=Layout.none,id:String=ß.alphaID) {
self.id = id
super.init(parent: superview)
if let viewport=viewport, !viewport.uiThread {
Debug.error("error, View added outside UI thread",#file,#line)
}
self._size=superview.size
superview.add(view:self)
superview._layouts[self.id]=layout
self.needsLayout=true
self.viewport!.pulse.once {
self.onResize.dispatch(self.bounds.size)
}
superview.onSubviewAttached.dispatch(self)
superview.onSubviewsChanged.dispatch(())
}
open override func detach() {
if let viewport=viewport, !viewport.uiThread {
Debug.error("error, View detached outside UI thread")
}
self.sui {
self._touch?.detach()
self._touch = nil
self.onSubviewAttached.removeAll()
self.onSubviewsChanged.removeAll()
self.onEnterRendering.removeAll()
self.onDraw.removeAll()
self.onOverlay.removeAll()
self.onResize.removeAll()
self.onFocus.removeAll()
for v in self.subviews {
v.detach()
}
self.onSubviewDetached.removeAll()
if let superview=self.superview {
if superview.touchCaptured == self {
superview.touchCaptured = nil
}
superview.subviews=superview.subviews.filter({ (v) -> Bool in
return v != self
})
} else if let viewport = self.viewport {
viewport.rootView=nil
}
self.afterEffect = nil
if let b = self.surface {
b.detach()
self.surface = nil
}
let superview = self.superview
super.detach()
if let superview = superview {
superview.onSubviewDetached.dispatch(self)
superview.onSubviewsChanged.dispatch(())
}
}
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////
public enum Align : Int {
case none = 0
case left = 1
case middle = 2
case right = 4
case justified = 8
case top = 128
case center = 256
case bottom = 512
case topLeft = 129
case topMiddle = 130
case topRight = 132
case centerLeft = 257
case centerMiddle = 258
case centerRight = 260
case bottomLeft = 513
case bottomMiddle = 514
case bottomRight = 516
case fillWidth = 5
case fillHeight = 640
case fill = 645
case maskHorizontal = 15
case maskVertical = 896
public static var horizontalCenter:Align {
return .middle
}
public static var verticalCenter:Align {
return .center
}
public static var fullCenter:Align {
return .centerMiddle
}
public var horizontalPart:Align {
return Align(rawValue:self.rawValue&Align.maskHorizontal.rawValue)!
}
public var verticalPart:Align {
return Align(rawValue:self.rawValue&Align.maskVertical.rawValue)!
}
public func hasFlag(_ flag:Align) -> Bool {
return (self.rawValue & flag.rawValue) == flag.rawValue
}
public var point:Point {
var p = Point.zero
switch(Align(rawValue: self.rawValue & Align.maskHorizontal.rawValue)!) {
case .right:
p.x = 1
case .middle,.fillWidth:
p.x = 0.5
//case .left:
default:
p.x = 0.0
}
switch(Align(rawValue: self.rawValue & Align.maskVertical.rawValue)!) {
case .bottom:
p.y = 1
case .center,.fillHeight:
p.y = 0.5
//case .top:
default:
p.y = 0
}
return p
}
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////
public enum Orientation : Int
{
case undefined=0
case portraitBottom=1
case portraitUpsideDown=2
case landscapeRight=4
case landscapeLeft=8
// bas du telephone a droite sur android (TODO; make it the same on iOS)
case portrait=3
case landscape=12
case all=15
public var isLandscape : Bool {
return self==Orientation.landscapeLeft||self==Orientation.landscapeRight||self==Orientation.landscape
}
public var isPortrait : Bool {
return self==Orientation.portrait||self==Orientation.portraitBottom||self==Orientation.portraitUpsideDown
}
public var isSingle : Bool {
return self==Orientation.portraitBottom||self==Orientation.portraitUpsideDown||self==Orientation.landscapeLeft||self==Orientation.landscapeRight
}
public func rotation(from:Orientation) -> Rotation {
if self==Orientation.undefined||from==Orientation.undefined||self==Orientation.all||from==Orientation.all {
return Rotation.none
} else if self==Orientation.landscape&&from.isLandscape || self==Orientation.portrait&&from.isPortrait || from==Orientation.landscape&&self.isLandscape || from==Orientation.portrait && self.isPortrait {
return Rotation.none
}
return Rotation(rawValue: (self.rotation.rawValue-from.rotation.rawValue)&3)!
}
public func rotation(to:Orientation) -> Rotation {
if self==Orientation.undefined||to==Orientation.undefined||self==Orientation.all||to==Orientation.all {
return Rotation.none
} else if self==Orientation.landscape&&to.isLandscape || self==Orientation.portrait&&to.isPortrait || to==Orientation.landscape&&self.isLandscape || to==Orientation.portrait && self.isPortrait {
return Rotation.none
}
return Rotation(rawValue: (to.rotation.rawValue-self.rotation.rawValue)&3)!
}
public var rotation : Rotation {
switch self {
case Orientation.landscape:
return Rotation.clockwise
case Orientation.landscapeLeft:
return Rotation.clockwise
case Orientation.landscapeRight:
return Rotation.anticlockwise
case Orientation.portraitUpsideDown:
return Rotation.upSideDown
default:
return Rotation.none
}
}
public func rotate(_ rotation:Rotation) -> Orientation {
return Rotation(rawValue: (self.rotation.rawValue+rotation.rawValue)&3)!.orientation
}
#if os(iOS)
public init(device:UIDeviceOrientation) {
switch device {
case UIDeviceOrientation.portrait:
self = .portraitBottom
case UIDeviceOrientation.portraitUpsideDown:
self = .portraitUpsideDown
case UIDeviceOrientation.landscapeLeft:
self = .landscapeLeft
case UIDeviceOrientation.landscapeRight:
self = .landscapeRight
default:
self = .undefined
}
}
public init(interface:UIInterfaceOrientation) {
switch interface {
case UIInterfaceOrientation.portrait:
self = .portraitBottom
case UIInterfaceOrientation.portraitUpsideDown:
self = .portraitUpsideDown
case UIInterfaceOrientation.landscapeLeft:
self = .landscapeRight
case UIInterfaceOrientation.landscapeRight:
self = .landscapeLeft
default:
self = .undefined
}
}
#endif
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////
public enum Rotation : Int
{
case none=0
case clockwise=1
case upSideDown=2
case anticlockwise=3
public var angle : Double
{
switch self {
case Rotation.anticlockwise:
return -ß.π2
case Rotation.clockwise:
return ß.π2
case Rotation.upSideDown:
return ß.π
default:
return 0.0;
}
}
public var isQuarter : Bool {
return self==Rotation.clockwise||self==Rotation.anticlockwise
}
public func rotate(_ size:Size) -> Size {
if isQuarter {
return size.rotate
}
return size
}
public func rotate(_ rect:Rect) -> Rect {
if isQuarter {
return rect.rotate
}
return rect
}
public var invers : Rotation {
return Rotation(rawValue: (4-self.rawValue)&3)!
}
public var orientation : Orientation
{
switch self {
case Rotation.none:
return Orientation.portraitBottom
case Rotation.clockwise:
return Orientation.landscapeLeft
case Rotation.upSideDown:
return Orientation.portraitUpsideDown
case Rotation.anticlockwise:
return Orientation.landscapeRight
}
}
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////
public enum Direction : Int {
case vertical=1
case horizontal=2
public var point : Point {
switch self {
case .vertical:
return Point(0,1)
case .horizontal:
return Point(1,0)
}
}
public var size : Size {
switch self {
case .vertical:
return Size(0,1)
case .horizontal:
return Size(1,0)
}
}
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////
| apache-2.0 | 4b096cfddf04171aa5e785c5540638d7 | 36.262405 | 253 | 0.45881 | 4.930682 | false | false | false | false |
ins-wing/Apptoms | Apptoms/Classes/Lithium/Extensions_Lithium.swift | 1 | 922 | //
// Extensions_Lithium.swift
// Lithium
//
// Created by WinG@Apptoms on 3/7/2017.
// Copyright (c) 2017 Apptoms. All rights reserved.
//
import Foundation
public extension URLSession {
public func asyncData(url: URL, complete: @escaping (Data?, URLResponse?, Error?) -> ()) {
DispatchQueue.global(qos: .utility).async {
let request = URLRequest(url: url)
let task = self.dataTask(with: request) { data, response, error in
complete(data, response, error)
}
task.resume()
}
}
public func asyncJson(url: URL, complete: @escaping (Any?, URLResponse?, Error?) -> ()) {
DispatchQueue.global(qos: .utility).async {
let request = URLRequest(url: url)
let task = self.dataTask(with: request) { data, response, error in
let json = try? JSONSerialization.jsonObject(with: data!, options: .allowFragments)
complete(json ?? nil, response, error)
}
task.resume()
}
}
}
| mit | e34f722227f0e76b02ad3c0221322135 | 26.117647 | 91 | 0.665944 | 3.32852 | false | false | false | false |
charles-oder/rest-fetcher-swift | RestFetcher/RFLoggedRequest.swift | 1 | 3160 | //
// RFLoggedRequest.swift
// Pods-RestFetcherExample
//
// Created by Charles Oder DTN on 1/27/18.
//
import Foundation
public protocol RFLoggedRequest {
var logger: RFLogger { get }
var keysToScrub: [String] { get }
}
extension RFRequest: RFLoggedRequest {
func logResponse(responseTime: Double, code: Int, headers: [String: String], data: Data?) {
guard let unwrappedData = data else {
return
}
let body = String(data: unwrappedData, encoding: .utf8)
logger.debug(buildSuccessMessage(responseTime: responseTime, code: code, headers: headers, data: data, body: body))
}
func logError(_ error: NSError) {
logger.error(buildErrorMessage(error: error))
}
func logRequest(resource: String, method: RFMethod, headers: [String: String], bodyString: String?) {
logger.debug(buildRequestLogMessage())
}
func buildRequestLogMessage() -> String {
var logMessage = "Sending Request: \(requestId)\n\(restMethod.rawValue) Request: \(requestUrlString)\n Request Headers:\n"
for (key, val) in requestHeaders {
logMessage += "\t\(key): \(val)\n"
}
do {
let requestBodyLogMessageScrubbed = try RFDataScrubber(keysToScrub: keysToScrub).scrub(json: requestBodyString) ?? ""
logMessage += "Request Body: \(requestBodyLogMessageScrubbed)\n"
return logMessage
} catch {
logMessage += "Request Body: Error scrubbing requestBody\(error)\n"
return logMessage
}
}
//swiftlint:disable line_length
func buildSuccessMessage(responseTime: Double, code: Int, headers: [String: String], data: Data?, body: String?) -> String {
let responseTimeString = String(format: "%.6f", responseTime)
var logMessage = "Response Recieved: \(requestId)\n\(restMethod.rawValue): \(requestUrlString)\nResponse took \(responseTimeString) seconds\nResponse: \(code)\nHeaders:\n"
for (key, val) in headers {
logMessage += "\(key): \(val)"
}
do {
let responseBodyMessageScrubbed = try RFDataScrubber(keysToScrub: keysToScrub).scrub(json: body) ?? ""
logMessage += "\nResponse Body: \(responseBodyMessageScrubbed)"
return logMessage
} catch {
logMessage += "Response Body: Error scrubbing response\(error)\n"
return logMessage
}
}
func buildErrorMessage(error: NSError) -> String {
let responseTimeString = error.userInfo["time"] as? String ?? "<unknown>"
var logMessage = "Response Recieved: \(requestId)\n\(restMethod.rawValue): \(requestUrlString)\nResponse took \(responseTimeString) seconds\nResponse: \(error.code)\n"
let headers = error.userInfo["headers"] as? [String: String]
logMessage += "\nResponse Headers:"
for (key, value) in headers ?? [:] {
logMessage += "\n\(key): \(value)"
}
logMessage += "\nResponse Body: \(error.userInfo["message"] ?? "")"
return logMessage
}
//swiftlint:enable line_length
}
| mit | 1fc8c5d466edbc58292fedd186915b62 | 39 | 179 | 0.625316 | 4.42577 | false | false | false | false |
duliodenis/jukebox | jukebox/jukebox/PlaylistMasterViewController.swift | 1 | 1849 | //
// ViewController.swift
// jukebox
//
// Created by Dulio Denis on 3/20/15.
// Copyright (c) 2015 Dulio Denis. All rights reserved.
//
import UIKit
class PlaylistMasterViewController: UIViewController {
var playlistsArray: [UIImageView] = []
@IBOutlet weak var playlistImageView0: UIImageView!
@IBOutlet weak var playlistImageView1: UIImageView!
@IBOutlet weak var playlistImageView2: UIImageView!
@IBOutlet weak var playlistImageView3: UIImageView!
@IBOutlet weak var playlistImageView4: UIImageView!
@IBOutlet weak var playlistImageView5: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
playlistsArray += [playlistImageView0, playlistImageView1, playlistImageView2]
// , playlistImageView2, playlistImageView3, playlistImageView4, playlistImageView5]
for index in 0..<playlistsArray.count {
let playlist = Playlist(index: index)
let playlistImageView = playlistsArray[index]
playlistImageView.image = playlist.icon
playlistImageView.backgroundColor = playlist.backgroundColor
}
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "showPlaylistDetailSegue" {
let playlistImageView = sender!.view as UIImageView
if let index = find(playlistsArray, playlistImageView) {
let playListDetailController = segue.destinationViewController as PlaylistDetailViewController
playListDetailController.playlist = Playlist(index: index)
}
}
}
@IBAction func showPlaylistDetail(sender: AnyObject) {
performSegueWithIdentifier("showPlaylistDetailSegue", sender: sender)
}
}
| mit | 8a12ca7e0fdcc5058e28f24a040ff032 | 33.240741 | 110 | 0.673878 | 5.390671 | false | false | false | false |
luizlopezm/ios-Luis-Trucking | Pods/Eureka/Source/Rows/CheckRow.swift | 1 | 1749 | //
// CheckRow.swift
// Eureka
//
// Created by Martin Barreto on 2/23/16.
// Copyright © 2016 Xmartlabs. All rights reserved.
//
import Foundation
// MARK: CheckCell
public final class CheckCell : Cell<Bool>, CellType {
required public init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
height = { BaseRow.estimatedRowHeight }
}
public override func update() {
super.update()
accessoryType = row.value == true ? .Checkmark : .None
editingAccessoryType = accessoryType
selectionStyle = .Default
var red: CGFloat = 0, green: CGFloat = 0, blue: CGFloat = 0, alpha: CGFloat = 0
tintColor.getRed(&red, green: &green, blue: &blue, alpha: &alpha)
if row.isDisabled {
tintColor = UIColor(red: red, green: green, blue: blue, alpha: 0.3)
selectionStyle = .None
}
else {
tintColor = UIColor(red: red, green: green, blue: blue, alpha: 1)
}
}
public override func setup() {
super.setup()
accessoryType = .Checkmark
editingAccessoryType = accessoryType
}
public override func didSelect() {
row.value = row.value ?? false ? false : true
row.deselect()
row.updateCell()
}
}
// MARK: CheckRow
public class _CheckRow: Row<Bool, CheckCell> {
required public init(tag: String?) {
super.init(tag: tag)
displayValueFor = nil
}
}
///// Boolean row that has a checkmark as accessoryType
public final class CheckRow: _CheckRow, RowType {
required public init(tag: String?) {
super.init(tag: tag)
}
}
| mit | 29e241a283e2af13d1f9f3337aa2f802 | 25.484848 | 87 | 0.603547 | 4.337469 | false | false | false | false |
jamalping/XPUtil | XPUtil/Foundation/JSON.swift | 1 | 1991 | //
// JSON.swift
// XPUtilExample
//
// Created by Apple on 2018/12/30.
// Copyright © 2018年 xyj. All rights reserved.
//
import Foundation
// MARK: - JSON字符串相关
public struct JSON {
/// 转JSON字符串
///
/// - Parameters:
/// - object: JSON对象(字典)
/// - options: <#options description#>
/// - Returns: JSON字符串
public static func toJSONString(_ object: Any, options: JSONSerialization.WritingOptions) -> String? {
guard let data = try? JSONSerialization.data(withJSONObject: object, options: options) else {
return nil
}
let jsonString = String.init(data: data, encoding: .utf8)
return jsonString
}
/// 转data
///
/// - Parameters:
/// - JSONObject: JSON对象(字典)
/// - options: <#options description#>
/// - Returns: Data
public static func toJSONData(_ JSONObject: Any, options: JSONSerialization.WritingOptions) -> Data? {
if JSONSerialization.isValidJSONObject(JSONObject) {
let JSONData: Data?
do {
JSONData = try JSONSerialization.data(withJSONObject: JSONObject, options: options)
} catch let error {
print(error)
JSONData = nil
}
return JSONData
}
return nil
}
/// 转JSON对象
///
/// - Parameters:
/// - jsonString: JSON字符串
/// - options: <#options description#>
/// - Returns: JOSN对象
public static func toJSON(_ jsonString: String, options: JSONSerialization.ReadingOptions) -> [String: Any] {
guard let data = jsonString.data(using: .utf8) else {
return [:]
}
guard let json: [String: Any] = try? JSONSerialization.jsonObject(with: data, options: options) as? [String : Any] else {
return [:]
}
return json
}
}
| mit | 801ccd1c5568201ad6c3418cf74b5da7 | 27.323529 | 130 | 0.55296 | 4.563981 | false | false | false | false |
apple/swift | test/IDE/complete_decl_attribute.swift | 1 | 32953 | // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=AVAILABILITY1 | %FileCheck %s -check-prefix=AVAILABILITY1
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=AVAILABILITY2 | %FileCheck %s -check-prefix=AVAILABILITY2
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=KEYWORD2 | %FileCheck %s -check-prefix=KEYWORD2
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=KEYWORD3 | %FileCheck %s -check-prefix=KEYWORD3
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=KEYWORD3_2 | %FileCheck %s -check-prefix=KEYWORD3
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=KEYWORD4 | %FileCheck %s -check-prefix=KEYWORD4
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=KEYWORD5 | %FileCheck %s -check-prefix=KEYWORD5
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=ON_GLOBALVAR | %FileCheck %s -check-prefix=ON_GLOBALVAR
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=ON_INIT | %FileCheck %s -check-prefix=ON_INIT
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=ON_PROPERTY | %FileCheck %s -check-prefix=ON_PROPERTY
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=ON_METHOD | %FileCheck %s -check-prefix=ON_METHOD
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=ON_PARAM_1 | %FileCheck %s -check-prefix=ON_PARAM
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=ON_PARAM_2 | %FileCheck %s -check-prefix=ON_PARAM
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=ON_MEMBER_INDEPENDENT_1 | %FileCheck %s -check-prefix=ON_MEMBER_LAST
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=ON_MEMBER_INDEPENDENT_2 | %FileCheck %s -check-prefix=ON_MEMBER_LAST
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=ON_MEMBER_LAST | %FileCheck %s -check-prefix=ON_MEMBER_LAST
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=IN_CLOSURE | %FileCheck %s -check-prefix=IN_CLOSURE
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=KEYWORD_INDEPENDENT_1 | %FileCheck %s -check-prefix=KEYWORD_LAST
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=KEYWORD_INDEPENDENT_2 | %FileCheck %s -check-prefix=KEYWORD_LAST
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=KEYWORD_LAST | %FileCheck %s -check-prefix=KEYWORD_LAST
struct MyStruct {}
@propertyWrapper
struct MyPropertyWrapper {
var wrappedValue: String
}
@resultBuilder
struct MyResultBuilder {
static func buildBlock(_ components: Int) -> Int {
return components.first!
}
}
@globalActor
actor MyGlobalActor {
static let shared = MyGlobalActor()
}
@available(#^AVAILABILITY1^#)
// NOTE: Please do not include the ", N items" after "Begin completions". The
// item count creates needless merge conflicts given that we use the "-NEXT"
// feature of FileCheck and because an "End completions" line exists for each
// test.
// AVAILABILITY1: Begin completions
// AVAILABILITY1-NEXT: Keyword/None: *[#Platform#]; name=*{{$}}
// AVAILABILITY1-NEXT: Keyword/None: iOS[#Platform#]; name=iOS{{$}}
// AVAILABILITY1-NEXT: Keyword/None: tvOS[#Platform#]; name=tvOS{{$}}
// AVAILABILITY1-NEXT: Keyword/None: watchOS[#Platform#]; name=watchOS{{$}}
// AVAILABILITY1-NEXT: Keyword/None: macOS[#Platform#]; name=macOS{{$}}
// AVAILABILITY1-NEXT: Keyword/None: iOSApplicationExtension[#Platform#]; name=iOSApplicationExtension{{$}}
// AVAILABILITY1-NEXT: Keyword/None: tvOSApplicationExtension[#Platform#]; name=tvOSApplicationExtension{{$}}
// AVAILABILITY1-NEXT: Keyword/None: watchOSApplicationExtension[#Platform#]; name=watchOSApplicationExtension{{$}}
// AVAILABILITY1-NEXT: Keyword/None: macOSApplicationExtension[#Platform#]; name=macOSApplicationExtension{{$}}
// AVAILABILITY1-NEXT: Keyword/None: macCatalyst[#Platform#]; name=macCatalyst
// AVAILABILITY1-NEXT: Keyword/None: macCatalystApplicationExtension[#Platform#]; name=macCatalystApplicationExtension
// AVAILABILITY1-NEXT: Keyword/None: OpenBSD[#Platform#]; name=OpenBSD{{$}}
// AVAILABILITY1-NEXT: Keyword/None: Windows[#Platform#]; name=Windows{{$}}
// AVAILABILITY1-NEXT: End completions
@available(*, #^AVAILABILITY2^#)
// AVAILABILITY2: Begin completions
// AVAILABILITY2-NEXT: Keyword/None: unavailable; name=unavailable{{$}}
// AVAILABILITY2-NEXT: Keyword/None: message: [#Specify message#]; name=message{{$}}
// AVAILABILITY2-NEXT: Keyword/None: renamed: [#Specify replacing name#]; name=renamed{{$}}
// AVAILABILITY2-NEXT: Keyword/None: introduced: [#Specify version number#]; name=introduced{{$}}
// AVAILABILITY2-NEXT: Keyword/None: deprecated: [#Specify version number#]; name=deprecated{{$}}
// AVAILABILITY2-NEXT: End completions
@#^KEYWORD2^# func method(){}
// KEYWORD2: Begin completions
// KEYWORD2-NEXT: Keyword/None: available[#Func Attribute#]; name=available{{$}}
// KEYWORD2-NEXT: Keyword/None: objc[#Func Attribute#]; name=objc{{$}}
// KEYWORD2-NEXT: Keyword/None: IBAction[#Func Attribute#]; name=IBAction{{$}}
// KEYWORD2-NEXT: Keyword/None: NSManaged[#Func Attribute#]; name=NSManaged{{$}}
// KEYWORD2-NEXT: Keyword/None: inline[#Func Attribute#]; name=inline{{$}}
// KEYWORD2-NEXT: Keyword/None: nonobjc[#Func Attribute#]; name=nonobjc{{$}}
// KEYWORD2-NEXT: Keyword/None: inlinable[#Func Attribute#]; name=inlinable{{$}}
// KEYWORD2-NEXT: Keyword/None: warn_unqualified_access[#Func Attribute#]; name=warn_unqualified_access{{$}}
// KEYWORD2-NEXT: Keyword/None: usableFromInline[#Func Attribute#]; name=usableFromInline
// KEYWORD2-NEXT: Keyword/None: discardableResult[#Func Attribute#]; name=discardableResult
// KEYWORD2-NEXT: Keyword/None: differentiable[#Func Attribute#]; name=differentiable
// KEYWORD2-NEXT: Keyword/None: IBSegueAction[#Func Attribute#]; name=IBSegueAction{{$}}
// KEYWORD2-NEXT: Keyword/None: derivative[#Func Attribute#]; name=derivative
// KEYWORD2-NEXT: Keyword/None: transpose[#Func Attribute#]; name=transpose
// KEYWORD2-NEXT: Keyword/None: noDerivative[#Func Attribute#]; name=noDerivative
// KEYWORD2-NEXT: Keyword/None: Sendable[#Func Attribute#]; name=Sendable
// KEYWORD2-NEXT: Keyword/None: preconcurrency[#Func Attribute#]; name=preconcurrency
// KEYWORD2-NOT: Keyword
// KEYWORD2-DAG: Decl[Struct]/CurrModule: MyStruct[#MyStruct#]; name=MyStruct
// KEYWORD2-DAG: Decl[Struct]/CurrModule: MyPropertyWrapper[#MyPropertyWrapper#]; name=MyPropertyWrapper
// KEYWORD2-DAG: Decl[Struct]/CurrModule/TypeRelation[Convertible]: MyResultBuilder[#MyResultBuilder#]; name=MyResultBuilder
// KEYWORD2-DAG: Decl[Actor]/CurrModule/TypeRelation[Convertible]: MyGlobalActor[#MyGlobalActor#]; name=MyGlobalActor
// KEYWORD2: End completions
@#^KEYWORD3^# class C {}
// KEYWORD3: Begin completions
// KEYWORD3-NEXT: Keyword/None: available[#Class Attribute#]; name=available{{$}}
// KEYWORD3-NEXT: Keyword/None: objc[#Class Attribute#]; name=objc{{$}}
// KEYWORD3-NEXT: Keyword/None: dynamicCallable[#Class Attribute#]; name=dynamicCallable{{$}}
// KEYWORD3-NEXT: Keyword/None: main[#Class Attribute#]; name=main
// KEYWORD3-NEXT: Keyword/None: dynamicMemberLookup[#Class Attribute#]; name=dynamicMemberLookup{{$}}
// KEYWORD3-NEXT: Keyword/None: IBDesignable[#Class Attribute#]; name=IBDesignable{{$}}
// KEYWORD3-NEXT: Keyword/None: UIApplicationMain[#Class Attribute#]; name=UIApplicationMain{{$}}
// KEYWORD3-NEXT: Keyword/None: requires_stored_property_inits[#Class Attribute#]; name=requires_stored_property_inits{{$}}
// KEYWORD3-NEXT: Keyword/None: objcMembers[#Class Attribute#]; name=objcMembers{{$}}
// KEYWORD3-NEXT: Keyword/None: NSApplicationMain[#Class Attribute#]; name=NSApplicationMain{{$}}
// KEYWORD3-NEXT: Keyword/None: usableFromInline[#Class Attribute#]; name=usableFromInline
// KEYWORD3-NEXT: Keyword/None: propertyWrapper[#Class Attribute#]; name=propertyWrapper
// KEYWORD3-NEXT: Keyword/None: resultBuilder[#Class Attribute#]; name=resultBuilder
// KEYWORD3-NEXT: Keyword/None: globalActor[#Class Attribute#]; name=globalActor
// KEYWORD3-NEXT: Keyword/None: preconcurrency[#Class Attribute#]; name=preconcurrency
// KEYWORD3-NEXT: Keyword/None: typeWrapper[#Class Attribute#]; name=typeWrapper
// KEYWORD3-NEXT: Keyword/None: runtimeMetadata[#Class Attribute#]; name=runtimeMetadata
// KEYWORD3-NEXT: End completions
@#^KEYWORD3_2^#IB class C2 {}
// Same as KEYWORD3.
@#^KEYWORD4^# enum E {}
// KEYWORD4: Begin completions
// KEYWORD4-NEXT: Keyword/None: available[#Enum Attribute#]; name=available{{$}}
// KEYWORD4-NEXT: Keyword/None: objc[#Enum Attribute#]; name=objc{{$}}
// KEYWORD4-NEXT: Keyword/None: dynamicCallable[#Enum Attribute#]; name=dynamicCallable
// KEYWORD4-NEXT: Keyword/None: main[#Enum Attribute#]; name=main
// KEYWORD4-NEXT: Keyword/None: dynamicMemberLookup[#Enum Attribute#]; name=dynamicMemberLookup
// KEYWORD4-NEXT: Keyword/None: usableFromInline[#Enum Attribute#]; name=usableFromInline
// KEYWORD4-NEXT: Keyword/None: frozen[#Enum Attribute#]; name=frozen
// KEYWORD4-NEXT: Keyword/None: propertyWrapper[#Enum Attribute#]; name=propertyWrapper
// KEYWORD4-NEXT: Keyword/None: resultBuilder[#Enum Attribute#]; name=resultBuilder
// KEYWORD4-NEXT: Keyword/None: globalActor[#Enum Attribute#]; name=globalActor
// KEYWORD4-NEXT: Keyword/None: preconcurrency[#Enum Attribute#]; name=preconcurrency
// KEYWORD4-NEXT: Keyword/None: typeWrapper[#Enum Attribute#]; name=typeWrapper
// KEYWORD4-NEXT: End completions
@#^KEYWORD5^# struct S{}
// KEYWORD5: Begin completions
// KEYWORD5-NEXT: Keyword/None: available[#Struct Attribute#]; name=available{{$}}
// KEYWORD5-NEXT: Keyword/None: dynamicCallable[#Struct Attribute#]; name=dynamicCallable
// KEYWORD5-NEXT: Keyword/None: main[#Struct Attribute#]; name=main
// KEYWORD5-NEXT: Keyword/None: dynamicMemberLookup[#Struct Attribute#]; name=dynamicMemberLookup
// KEYWORD5-NEXT: Keyword/None: usableFromInline[#Struct Attribute#]; name=usableFromInline
// KEYWORD5-NEXT: Keyword/None: frozen[#Struct Attribute#]; name=frozen
// KEYWORD5-NEXT: Keyword/None: propertyWrapper[#Struct Attribute#]; name=propertyWrapper
// KEYWORD5-NEXT: Keyword/None: resultBuilder[#Struct Attribute#]; name=resultBuilder
// KEYWORD5-NEXT: Keyword/None: globalActor[#Struct Attribute#]; name=globalActor
// KEYWORD5-NEXT: Keyword/None: preconcurrency[#Struct Attribute#]; name=preconcurrency
// KEYWORD5-NEXT: Keyword/None: typeWrapper[#Struct Attribute#]; name=typeWrapper
// KEYWORD5-NEXT: Keyword/None: runtimeMetadata[#Struct Attribute#]; name=runtimeMetadata
// KEYWORD5-NEXT: End completions
@#^ON_GLOBALVAR^# var globalVar
// ON_GLOBALVAR: Begin completions
// ON_GLOBALVAR-DAG: Keyword/None: available[#Var Attribute#]; name=available
// ON_GLOBALVAR-DAG: Keyword/None: objc[#Var Attribute#]; name=objc
// ON_GLOBALVAR-DAG: Keyword/None: NSCopying[#Var Attribute#]; name=NSCopying
// ON_GLOBALVAR-DAG: Keyword/None: IBInspectable[#Var Attribute#]; name=IBInspectable
// ON_GLOBALVAR-DAG: Keyword/None: IBOutlet[#Var Attribute#]; name=IBOutlet
// ON_GLOBALVAR-DAG: Keyword/None: NSManaged[#Var Attribute#]; name=NSManaged
// ON_GLOBALVAR-DAG: Keyword/None: inline[#Var Attribute#]; name=inline
// ON_GLOBALVAR-DAG: Keyword/None: nonobjc[#Var Attribute#]; name=nonobjc
// ON_GLOBALVAR-DAG: Keyword/None: inlinable[#Var Attribute#]; name=inlinable
// ON_GLOBALVAR-DAG: Keyword/None: usableFromInline[#Var Attribute#]; name=usableFromInline
// ON_GLOBALVAR-DAG: Keyword/None: GKInspectable[#Var Attribute#]; name=GKInspectable
// ON_GLOBALVAR-DAG: Keyword/None: differentiable[#Var Attribute#]; name=differentiable
// ON_GLOBALVAR-DAG: Keyword/None: noDerivative[#Var Attribute#]; name=noDerivative
// ON_GLOBALVAR-DAG: Keyword/None: exclusivity[#Var Attribute#]; name=exclusivity
// ON_GLOBALVAR-DAG: Keyword/None: preconcurrency[#Var Attribute#]; name=preconcurrency
// ON_GLOBALVAR-DAG: Keyword/None: typeWrapperIgnored[#Var Attribute#]; name=typeWrapperIgnored
// ON_GLOBALVAR-NOT: Keyword
// ON_GLOBALVAR-DAG: Decl[Struct]/CurrModule: MyStruct[#MyStruct#]; name=MyStruct
// ON_GLOBALVAR-DAG: Decl[Struct]/CurrModule/TypeRelation[Convertible]: MyPropertyWrapper[#MyPropertyWrapper#]; name=MyPropertyWrapper
// ON_GLOBALVAR-DAG: Decl[Struct]/CurrModule/TypeRelation[Convertible]: MyResultBuilder[#MyResultBuilder#]; name=MyResultBuilder
// ON_GLOBALVAR-DAG: Decl[Actor]/CurrModule/TypeRelation[Convertible]: MyGlobalActor[#MyGlobalActor#]; name=MyGlobalActor
// ON_GLOBALVAR: End completions
struct _S {
@#^ON_INIT^# init()
// ON_INIT: Begin completions
// ON_INIT-DAG: Keyword/None: available[#Constructor Attribute#]; name=available
// ON_INIT-DAG: Keyword/None: objc[#Constructor Attribute#]; name=objc
// ON_INIT-DAG: Keyword/None: inline[#Constructor Attribute#]; name=inline
// ON_INIT-DAG: Keyword/None: nonobjc[#Constructor Attribute#]; name=nonobjc
// ON_INIT-DAG: Keyword/None: inlinable[#Constructor Attribute#]; name=inlinable
// ON_INIT-DAG: Keyword/None: usableFromInline[#Constructor Attribute#]; name=usableFromInline
// ON_INIT-DAG: Keyword/None: discardableResult[#Constructor Attribute#]; name=discardableResult
// ON_INIT-DAG: Keyword/None: preconcurrency[#Constructor Attribute#]; name=preconcurrency
// ON_INIT: End completions
@#^ON_PROPERTY^# var foo
// ON_PROPERTY: Begin completions
// ON_PROPERTY-DAG: Keyword/None: available[#Var Attribute#]; name=available
// ON_PROPERTY-DAG: Keyword/None: objc[#Var Attribute#]; name=objc
// ON_PROPERTY-DAG: Keyword/None: NSCopying[#Var Attribute#]; name=NSCopying
// ON_PROPERTY-DAG: Keyword/None: IBInspectable[#Var Attribute#]; name=IBInspectable
// ON_PROPERTY-DAG: Keyword/None: IBOutlet[#Var Attribute#]; name=IBOutlet
// ON_PROPERTY-DAG: Keyword/None: NSManaged[#Var Attribute#]; name=NSManaged
// ON_PROPERTY-DAG: Keyword/None: inline[#Var Attribute#]; name=inline
// ON_PROPERTY-DAG: Keyword/None: nonobjc[#Var Attribute#]; name=nonobjc
// ON_PROPERTY-DAG: Keyword/None: inlinable[#Var Attribute#]; name=inlinable
// ON_PROPERTY-DAG: Keyword/None: usableFromInline[#Var Attribute#]; name=usableFromInline
// ON_PROPERTY-DAG: Keyword/None: GKInspectable[#Var Attribute#]; name=GKInspectable
// ON_PROPERTY-DAG: Keyword/None: differentiable[#Var Attribute#]; name=differentiable
// ON_PROPERTY-DAG: Keyword/None: noDerivative[#Var Attribute#]; name=noDerivative
// ON_PROPERTY-DAG: Keyword/None: exclusivity[#Var Attribute#]; name=exclusivity
// ON_PROPERTY-DAG: Keyword/None: preconcurrency[#Var Attribute#]; name=preconcurrency
// ON_PROPERTY-DAG: Keyword/None: typeWrapperIgnored[#Var Attribute#]; name=typeWrapperIgnored
// ON_PROPERTY-NOT: Keyword
// ON_PROPERTY-DAG: Decl[Struct]/CurrModule: MyStruct[#MyStruct#]; name=MyStruct
// ON_PROPERTY-DAG: Decl[Struct]/CurrModule/TypeRelation[Convertible]: MyPropertyWrapper[#MyPropertyWrapper#]; name=MyPropertyWrapper
// ON_PROPERTY-DAG: Decl[Struct]/CurrModule/TypeRelation[Convertible]: MyResultBuilder[#MyResultBuilder#]; name=MyResultBuilder
// ON_PROPERTY-DAG: Decl[Actor]/CurrModule/TypeRelation[Convertible]: MyGlobalActor[#MyGlobalActor#]; name=MyGlobalActor
// ON_PROPERTY-NOT: Decl[PrecedenceGroup]
// ON_PROPERTY: End completions
@#^ON_METHOD^# private
func foo()
// ON_METHOD: Begin completions
// ON_METHOD-DAG: Keyword/None: available[#Func Attribute#]; name=available
// ON_METHOD-DAG: Keyword/None: objc[#Func Attribute#]; name=objc
// ON_METHOD-DAG: Keyword/None: IBAction[#Func Attribute#]; name=IBAction
// ON_METHOD-DAG: Keyword/None: NSManaged[#Func Attribute#]; name=NSManaged
// ON_METHOD-DAG: Keyword/None: inline[#Func Attribute#]; name=inline
// ON_METHOD-DAG: Keyword/None: nonobjc[#Func Attribute#]; name=nonobjc
// ON_METHOD-DAG: Keyword/None: inlinable[#Func Attribute#]; name=inlinable
// ON_METHOD-DAG: Keyword/None: warn_unqualified_access[#Func Attribute#]; name=warn_unqualified_access
// ON_METHOD-DAG: Keyword/None: usableFromInline[#Func Attribute#]; name=usableFromInline
// ON_METHOD-DAG: Keyword/None: discardableResult[#Func Attribute#]; name=discardableResult
// ON_METHOD-DAG: Keyword/None: IBSegueAction[#Func Attribute#]; name=IBSegueAction
// ON_METHOD-DAG: Keyword/None: differentiable[#Func Attribute#]; name=differentiable
// ON_METHOD-DAG: Keyword/None: derivative[#Func Attribute#]; name=derivative
// ON_METHOD-DAG: Keyword/None: transpose[#Func Attribute#]; name=transpose
// ON_METHOD-DAG: Keyword/None: Sendable[#Func Attribute#]; name=Sendable
// ON_METHOD-DAG: Keyword/None: noDerivative[#Func Attribute#]; name=noDerivative
// ON_METHOD-DAG: Keyword/None: preconcurrency[#Func Attribute#]; name=preconcurrency
// ON_METHOD-NOT: Keyword
// ON_METHOD-DAG: Decl[Struct]/CurrModule: MyStruct[#MyStruct#]; name=MyStruct
// ON_METHOD-DAG: Decl[Struct]/CurrModule: MyPropertyWrapper[#MyPropertyWrapper#]; name=MyPropertyWrapper
// ON_METHOD-DAG: Decl[Struct]/CurrModule/TypeRelation[Convertible]: MyResultBuilder[#MyResultBuilder#]; name=MyResultBuilder
// ON_METHOD-DAG: Decl[Actor]/CurrModule/TypeRelation[Convertible]: MyGlobalActor[#MyGlobalActor#]; name=MyGlobalActor
// ON_METHOD: End completions
func bar(@#^ON_PARAM_1^#)
// ON_PARAM: Begin completions
// ON_PARAM-NOT: Keyword
// ON_PARAM-DAG: Decl[Struct]/CurrModule: MyStruct[#MyStruct#]; name=MyStruct
// ON_PARAM-DAG: Decl[Struct]/CurrModule/TypeRelation[Convertible]: MyPropertyWrapper[#MyPropertyWrapper#]; name=MyPropertyWrapper
// ON_PARAM-DAG: Decl[Struct]/CurrModule/TypeRelation[Convertible]: MyResultBuilder[#MyResultBuilder#]; name=MyResultBuilder
// ON_PARAM-DAG: Decl[Actor]/CurrModule: MyGlobalActor[#MyGlobalActor#]; name=MyGlobalActor
// ON_PARAM-NOT: Keyword
// ON_PARAM: End completions
func bar(
@#^ON_PARAM_2^#
arg: Int
)
// Same as ON_PARAM.
@#^ON_MEMBER_INDEPENDENT_1^#
func dummy1() {}
// Same as ON_MEMBER_LAST.
@#^ON_MEMBER_INDEPENDENT_2^#
func dummy2() {}
// Same as ON_MEMBER_LAST.
@#^ON_MEMBER_LAST^#
// ON_MEMBER_LAST: Begin completions
// ON_MEMBER_LAST-DAG: Keyword/None: available[#Declaration Attribute#]; name=available
// ON_MEMBER_LAST-DAG: Keyword/None: objc[#Declaration Attribute#]; name=objc
// ON_MEMBER_LAST-DAG: Keyword/None: dynamicCallable[#Declaration Attribute#]; name=dynamicCallable
// ON_MEMBER_LAST-DAG: Keyword/None: main[#Declaration Attribute#]; name=main
// ON_MEMBER_LAST-DAG: Keyword/None: dynamicMemberLookup[#Declaration Attribute#]; name=dynamicMemberLookup
// ON_MEMBER_LAST-DAG: Keyword/None: NSCopying[#Declaration Attribute#]; name=NSCopying
// ON_MEMBER_LAST-DAG: Keyword/None: IBAction[#Declaration Attribute#]; name=IBAction
// ON_MEMBER_LAST-DAG: Keyword/None: IBDesignable[#Declaration Attribute#]; name=IBDesignable
// ON_MEMBER_LAST-DAG: Keyword/None: IBInspectable[#Declaration Attribute#]; name=IBInspectable
// ON_MEMBER_LAST-DAG: Keyword/None: IBOutlet[#Declaration Attribute#]; name=IBOutlet
// ON_MEMBER_LAST-DAG: Keyword/None: NSManaged[#Declaration Attribute#]; name=NSManaged
// ON_MEMBER_LAST-DAG: Keyword/None: UIApplicationMain[#Declaration Attribute#]; name=UIApplicationMain
// ON_MEMBER_LAST-DAG: Keyword/None: inline[#Declaration Attribute#]; name=inline
// ON_MEMBER_LAST-DAG: Keyword/None: requires_stored_property_inits[#Declaration Attribute#]; name=requires_stored_property_inits
// ON_MEMBER_LAST-DAG: Keyword/None: nonobjc[#Declaration Attribute#]; name=nonobjc
// ON_MEMBER_LAST-DAG: Keyword/None: inlinable[#Declaration Attribute#]; name=inlinable
// ON_MEMBER_LAST-DAG: Keyword/None: objcMembers[#Declaration Attribute#]; name=objcMembers
// ON_MEMBER_LAST-DAG: Keyword/None: NSApplicationMain[#Declaration Attribute#]; name=NSApplicationMain
// ON_MEMBER_LAST-DAG: Keyword/None: rethrows[#Declaration Attribute#]; name=rethrows
// ON_MEMBER_LAST-DAG: Keyword/None: warn_unqualified_access[#Declaration Attribute#]; name=warn_unqualified_access
// ON_MEMBER_LAST-DAG: Keyword/None: usableFromInline[#Declaration Attribute#]; name=usableFromInline
// ON_MEMBER_LAST-DAG: Keyword/None: discardableResult[#Declaration Attribute#]; name=discardableResult
// ON_MEMBER_LAST-DAG: Keyword/None: GKInspectable[#Declaration Attribute#]; name=GKInspectable
// ON_MEMBER_LAST-DAG: Keyword/None: IBSegueAction[#Declaration Attribute#]; name=IBSegueAction
// ON_MEMBER_LAST-DAG: Keyword/None: propertyWrapper[#Declaration Attribute#]; name=propertyWrapper
// ON_MEMBER_LAST-DAG: Keyword/None: resultBuilder[#Declaration Attribute#]; name=resultBuilder
// ON_MEMBER_LAST-DAG: Keyword/None: differentiable[#Declaration Attribute#]; name=differentiable
// ON_MEMBER_LAST-DAG: Keyword/None: derivative[#Declaration Attribute#]; name=derivative
// ON_MEMBER_LAST-DAG: Keyword/None: transpose[#Declaration Attribute#]; name=transpose
// ON_MEMBER_LAST-DAG: Keyword/None: noDerivative[#Declaration Attribute#]; name=noDerivative
// ON_MEMBER_LAST-DAG: Keyword/None: Sendable[#Declaration Attribute#]; name=Sendable
// ON_MEMBER_LAST-DAG: Keyword/None: exclusivity[#Declaration Attribute#]; name=exclusivity
// ON_MEMBER_LAST-DAG: Keyword/None: preconcurrency[#Declaration Attribute#]; name=preconcurrency
// ON_MEMBER_LAST-DAG: Keyword/None: typeWrapper[#Declaration Attribute#]; name=typeWrapper
// ON_MEMBER_LAST-DAG: Keyword/None: typeWrapperIgnored[#Declaration Attribute#]; name=typeWrapperIgnored
// ON_MEMBER_LAST-DAG: Keyword/None: runtimeMetadata[#Declaration Attribute#]; name=runtimeMetadata
// ON_MEMBER_LAST-NOT: Keyword
// ON_MEMBER_LAST-DAG: Decl[Struct]/CurrModule: MyStruct[#MyStruct#]; name=MyStruct
// ON_MEMBER_LAST-DAG: Decl[Struct]/CurrModule/TypeRelation[Convertible]: MyPropertyWrapper[#MyPropertyWrapper#]; name=MyPropertyWrapper
// ON_MEMBER_LAST-DAG: Decl[Struct]/CurrModule/TypeRelation[Convertible]: MyResultBuilder[#MyResultBuilder#]; name=MyResultBuilder
// ON_MEMBER_LAST-DAG: Decl[Actor]/CurrModule/TypeRelation[Convertible]: MyGlobalActor[#MyGlobalActor#]; name=MyGlobalActor
// ON_MEMBER_LAST-NOT: Decl[PrecedenceGroup]
// ON_MEMBER_LAST: End completions
}
func takeClosure(_: () -> Void) {
takeClosure { @#^IN_CLOSURE^# in
print("x")
}
}
// FIXME: We should mark MyPropertyWrapper and MyResultBuilder as Unrelated
// IN_CLOSURE: Begin completions
// IN_CLOSURE-DAG: Decl[Struct]/CurrModule: MyStruct[#MyStruct#]; name=MyStruct
// IN_CLOSURE-DAG: Decl[Struct]/CurrModule/TypeRelation[Convertible]: MyPropertyWrapper[#MyPropertyWrapper#]; name=MyPropertyWrapper
// IN_CLOSURE-DAG: Decl[Struct]/CurrModule/TypeRelation[Convertible]: MyResultBuilder[#MyResultBuilder#]; name=MyResultBuilder
// IN_CLOSURE-DAG: Decl[Actor]/CurrModule/TypeRelation[Convertible]: MyGlobalActor[#MyGlobalActor#]; name=MyGlobalActor
// IN_CLOSURE: End completions
@#^KEYWORD_INDEPENDENT_1^#
func dummy1() {}
// Same as KEYWORD_LAST.
@#^KEYWORD_INDEPENDENT_2^#
func dummy2() {}
// Same as KEYWORD_LAST.
@#^KEYWORD_LAST^#
// KEYWORD_LAST: Begin completions
// KEYWORD_LAST-DAG: Keyword/None: available[#Declaration Attribute#]; name=available{{$}}
// KEYWORD_LAST-DAG: Keyword/None: objc[#Declaration Attribute#]; name=objc{{$}}
// KEYWORD_LAST-DAG: Keyword/None: dynamicCallable[#Declaration Attribute#]; name=dynamicCallable
// KEYWORD_LAST-DAG: Keyword/None: main[#Declaration Attribute#]; name=main
// KEYWORD_LAST-DAG: Keyword/None: dynamicMemberLookup[#Declaration Attribute#]; name=dynamicMemberLookup
// KEYWORD_LAST-DAG: Keyword/None: NSCopying[#Declaration Attribute#]; name=NSCopying{{$}}
// KEYWORD_LAST-DAG: Keyword/None: IBAction[#Declaration Attribute#]; name=IBAction{{$}}
// KEYWORD_LAST-DAG: Keyword/None: IBDesignable[#Declaration Attribute#]; name=IBDesignable{{$}}
// KEYWORD_LAST-DAG: Keyword/None: IBInspectable[#Declaration Attribute#]; name=IBInspectable{{$}}
// KEYWORD_LAST-DAG: Keyword/None: IBOutlet[#Declaration Attribute#]; name=IBOutlet{{$}}
// KEYWORD_LAST-DAG: Keyword/None: NSManaged[#Declaration Attribute#]; name=NSManaged{{$}}
// KEYWORD_LAST-DAG: Keyword/None: UIApplicationMain[#Declaration Attribute#]; name=UIApplicationMain{{$}}
// KEYWORD_LAST-DAG: Keyword/None: inline[#Declaration Attribute#]; name=inline{{$}}
// KEYWORD_LAST-DAG: Keyword/None: requires_stored_property_inits[#Declaration Attribute#]; name=requires_stored_property_inits{{$}}
// KEYWORD_LAST-DAG: Keyword/None: nonobjc[#Declaration Attribute#]; name=nonobjc{{$}}
// KEYWORD_LAST-DAG: Keyword/None: inlinable[#Declaration Attribute#]; name=inlinable{{$}}
// KEYWORD_LAST-DAG: Keyword/None: objcMembers[#Declaration Attribute#]; name=objcMembers{{$}}
// KEYWORD_LAST-DAG: Keyword/None: NSApplicationMain[#Declaration Attribute#]; name=NSApplicationMain{{$}}
// KEYWORD_LAST-DAG: Keyword/None: rethrows[#Declaration Attribute#]; name=rethrows{{$}}
// KEYWORD_LAST-DAG: Keyword/None: warn_unqualified_access[#Declaration Attribute#]; name=warn_unqualified_access
// KEYWORD_LAST-DAG: Keyword/None: usableFromInline[#Declaration Attribute#]; name=usableFromInline{{$}}
// KEYWORD_LAST-DAG: Keyword/None: discardableResult[#Declaration Attribute#]; name=discardableResult
// KEYWORD_LAST-DAG: Keyword/None: GKInspectable[#Declaration Attribute#]; name=GKInspectable{{$}}
// KEYWORD_LAST-DAG: Keyword/None: frozen[#Declaration Attribute#]; name=frozen
// KEYWORD_LAST-DAG: Keyword/None: propertyWrapper[#Declaration Attribute#]; name=propertyWrapper
// KEYWORD_LAST-DAG: Keyword/None: resultBuilder[#Declaration Attribute#]; name=resultBuilder
// KEYWORD_LAST-DAG: Keyword/None: differentiable[#Declaration Attribute#]; name=differentiable
// KEYWORD_LAST-DAG: Keyword/None: IBSegueAction[#Declaration Attribute#]; name=IBSegueAction{{$}}
// KEYWORD_LAST-DAG: Keyword/None: derivative[#Declaration Attribute#]; name=derivative
// KEYWORD_LAST-DAG: Keyword/None: transpose[#Declaration Attribute#]; name=transpose
// KEYWORD_LAST-DAG: Keyword/None: noDerivative[#Declaration Attribute#]; name=noDerivative
// KEYWORD_LAST-DAG: Keyword/None: Sendable[#Declaration Attribute#]; name=Sendable
// KEYWORD_LAST-DAG: Keyword/None: exclusivity[#Declaration Attribute#]; name=exclusivity
// KEYWORD_LAST-DAG: Keyword/None: preconcurrency[#Declaration Attribute#]; name=preconcurrency
// KEYWORD_LAST-DAG: Keyword/None: typeWrapper[#Declaration Attribute#]; name=typeWrapper
// KEYWORD_LAST-DAG: Keyword/None: typeWrapperIgnored[#Declaration Attribute#]; name=typeWrapperIgnored
// KEYWORD_LAST-DAG: Keyword/None: runtimeMetadata[#Declaration Attribute#]; name=runtimeMetadata
// KEYWORD_LAST-NOT: Keyword
// KEYWORD_LAST-DAG: Decl[Struct]/CurrModule: MyStruct[#MyStruct#]; name=MyStruct
// KEYWORD_LAST-DAG: Decl[Struct]/CurrModule/TypeRelation[Convertible]: MyPropertyWrapper[#MyPropertyWrapper#]; name=MyPropertyWrapper
// KEYWORD_LAST-DAG: Decl[Struct]/CurrModule/TypeRelation[Convertible]: MyResultBuilder[#MyResultBuilder#]; name=MyResultBuilder
// KEYWORD_LAST-DAG: Decl[Actor]/CurrModule/TypeRelation[Convertible]: MyGlobalActor[#MyGlobalActor#]; name=MyGlobalActor
// KEYWORD_LAST: End completions
| apache-2.0 | 1047840904b4c4a28ab840ce6bc9350c | 82.425316 | 159 | 0.635056 | 4.617853 | false | true | false | false |
jcheng77/missfit-ios | missfit/missfit/Vendor/Refresher/BeatAnimator.swift | 1 | 3609 | //
// BeatAnimator.swift
//
// Copyright (c) 2014 Josip Cavar
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
import Foundation
import QuartzCore
class BeatAnimator: PullToRefreshViewAnimator {
private var layerLoader: CAShapeLayer = CAShapeLayer()
private var layerSeparator: CAShapeLayer = CAShapeLayer()
init() {
layerLoader.lineWidth = 4
layerLoader.strokeColor = UIColor(red: 247.0 / 255.0, green: 126.0 / 255.0, blue: 164.0 / 255.0, alpha: 1.0).CGColor
layerLoader.strokeEnd = 0
layerSeparator.lineWidth = 1
layerSeparator.strokeColor = UIColor(red: 0.7, green: 0.7, blue: 0.7, alpha: 1).CGColor
}
func startAnimation() {
var pathAnimationEnd = CABasicAnimation(keyPath: "strokeEnd")
pathAnimationEnd.duration = 0.5
pathAnimationEnd.repeatCount = 100
pathAnimationEnd.autoreverses = true
pathAnimationEnd.fromValue = 1
pathAnimationEnd.toValue = 0.8
self.layerLoader.addAnimation(pathAnimationEnd, forKey: "strokeEndAnimation")
var pathAnimationStart = CABasicAnimation(keyPath: "strokeStart")
pathAnimationStart.duration = 0.5
pathAnimationStart.repeatCount = 100
pathAnimationStart.autoreverses = true
pathAnimationStart.fromValue = 0
pathAnimationStart.toValue = 0.2
self.layerLoader.addAnimation(pathAnimationStart, forKey: "strokeStartAnimation")
}
func stopAnimation() {
self.layerLoader.removeAllAnimations()
}
func layoutLayers(superview: UIView) {
if layerLoader.superlayer == nil {
superview.layer.addSublayer(layerLoader)
}
if layerSeparator.superlayer == nil {
superview.layer.addSublayer(layerSeparator)
}
var bezierPathLoader = UIBezierPath()
bezierPathLoader.moveToPoint(CGPointMake(0, superview.frame.height - 3))
bezierPathLoader.addLineToPoint(CGPoint(x: superview.frame.width, y: superview.frame.height - 3))
var bezierPathSeparator = UIBezierPath()
bezierPathSeparator.moveToPoint(CGPointMake(0, superview.frame.height - 1))
bezierPathSeparator.addLineToPoint(CGPoint(x: superview.frame.width, y: superview.frame.height - 1))
layerLoader.path = bezierPathLoader.CGPath
layerSeparator.path = bezierPathSeparator.CGPath
}
func changeProgress(progress: CGFloat) {
self.layerLoader.strokeEnd = progress
}
} | mit | 0dd4df6386ff88ac6cb0279cb8860a0f | 38.67033 | 124 | 0.693267 | 5.019471 | false | false | false | false |
RedRoster/rr-ios | RedRoster/Schedules/List/ScheduleTableViewController.swift | 1 | 10929 | //
// ScheduleTableViewController.swift
// RedRoster
//
// Created by Daniel Li on 8/6/16.
// Copyright © 2016 dantheli. All rights reserved.
//
import UIKit
import RealmSwift
class ScheduleTableViewController: UIViewController {
var schedule: Schedule!
var courses: [Course] = []
var sectionDict: [Course : [Element]] = [:]
var token: NotificationToken?
var redView: UIView!
var scheduleView: ScheduleInfoView!
var tableView: UITableView!
var emptyLabel: UILabel!
let ScheduleViewHeight: CGFloat = 50.0
var frame: CGRect
var fromProfile: Bool
init(schedule: Schedule, fromProfile: Bool = false, frame: CGRect) {
self.schedule = schedule
self.fromProfile = fromProfile
self.frame = frame
super.init(nibName: nil, bundle: nil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
title = schedule.name
view.backgroundColor = UIColor.rosterBackgroundColor()
view.frame = frame
setupTableView()
setupScheduleView()
configureTableView()
checkEmpty()
if !fromProfile {
setupNotification()
}
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(true)
scheduleView.alpha = 1.0
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(true)
UIView.animate(withDuration: 0.35, animations: {
self.scheduleView.alpha = 0.0
})
}
func configureTableView() {
sectionDict.removeAll(keepingCapacity: true)
var elements = Array(schedule.elements.filter { $0.section != nil })
courses = Array(schedule.courses)
for course in courses {
while let index = elements.index(where: { $0.courseId == course.courseId }) {
let element = elements.remove(at: index)
if sectionDict[course] != nil {
sectionDict[course]?.append(element)
} else {
sectionDict[course] = [element]
}
sectionDict[course]?.sort { $0.section?.classNumber ?? 0 < $1.section?.classNumber ?? 0 }
}
}
// courses.sort { sectionDict[$0]?.first?.creationDate.timeIntervalSince1970 < sectionDict[$1]?.first?.creationDate.timeIntervalSince1970 }
courses.sort { sectionDict[$0]?.first?.creationDate.timeIntervalSince1970 ?? 0 < sectionDict[$1]?.first?.creationDate.timeIntervalSince1970 ?? 0 }
tableView.reloadData()
}
func setupNotification() {
token = schedule.elements.addNotificationBlock { [weak self] changes in
self?.configureTableView()
self?.scheduleView.updateInfo()
self?.checkEmpty()
}
}
func setupTableView() {
tableView = UITableView(frame: CGRect(x: 0.0, y: 0.0, width: view.frame.width, height: view.frame.height - (navigationController?.navigationBar.frame.maxY ?? 0) - (tabBarController?.tabBar.frame.height ?? 0.0)), style: .grouped)
tableView.dataSource = self
tableView.delegate = self
tableView.backgroundColor = UIColor.clear
tableView.separatorColor = UIColor.rosterCellSeparatorColor()
tableView.showsVerticalScrollIndicator = false
tableView.register(UINib(nibName: "SectionCell", bundle: nil), forCellReuseIdentifier: "SectionCell")
tableView.register(UINib(nibName: "DeleteCell", bundle: nil), forCellReuseIdentifier: "DeleteCell")
let footer = UIView(frame: CGRect(x: 0.0, y: 0.0, width: view.frame.width, height: 66.0))
footer.backgroundColor = UIColor.clear
tableView.tableFooterView = footer
view.addSubview(tableView)
emptyLabel = UILabel(frame: view.frame)
emptyLabel.autoresizingMask = [.flexibleWidth, .flexibleHeight]
emptyLabel.text = "No Courses"
emptyLabel.font = UIFont.systemFont(ofSize: 24.0)
emptyLabel.textColor = UIColor.lightGray
emptyLabel.lineBreakMode = .byWordWrapping
emptyLabel.numberOfLines = 2
emptyLabel.textAlignment = .center
emptyLabel.isHidden = true
view.addSubview(emptyLabel)
}
func setupScheduleView() {
redView = UIView(frame: CGRect(x: 0.0, y: 0.0, width: view.frame.width, height: ScheduleViewHeight))
redView.backgroundColor = UIColor.rosterRed()
view.insertSubview(redView, belowSubview: tableView)
scheduleView = ScheduleInfoView(frame: CGRect(x: 0.0, y: 0.0, width: view.frame.width, height: ScheduleViewHeight), schedule: schedule)
scheduleView.updateInfo()
tableView.tableHeaderView = scheduleView
}
func checkEmpty() {
if schedule.courses.isEmpty {
emptyLabel.fadeShow()
tableView.isScrollEnabled = false
} else {
emptyLabel.fadeHide()
tableView.isScrollEnabled = true
}
}
}
extension ScheduleTableViewController: UITableViewDataSource, UITableViewDelegate {
func numberOfSections(in tableView: UITableView) -> Int {
return courses.count
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return (sectionDict[courses[section]]?.count ?? 0) + (fromProfile ? 0 : 1)
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let elements = sectionDict[courses[indexPath.section]]!
if indexPath.row == elements.count {
let cell = tableView.dequeueReusableCell(withIdentifier: "DeleteCell", for: indexPath) as! DeleteCell
cell.backgroundColor = UIColor.rosterCellBackgroundColor()
cell.selectionStyle = .default
let view = UIView()
view.backgroundColor = UIColor.rosterCellSelectionColor()
cell.selectedBackgroundView = view
return cell
}
let cell = tableView.dequeueReusableCell(withIdentifier: "SectionCell", for: indexPath) as! SectionCell
let element = elements[indexPath.row]
cell.configure(element.section!, selected: false, conflicted: element.collision)
let view = UIView()
view.backgroundColor = UIColor.rosterCellBackgroundColor()
cell.selectedBackgroundView = view
return cell
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
if indexPath.row == sectionDict[courses[indexPath.section]]!.count { return 44.0 }
return 66.0
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
let courseId = courses[indexPath.section]
if indexPath.row == sectionDict[courseId]!.count {
deleteCellTapped(courseId)
} else {
presentCourseViewController(courseId)
}
}
// MARK: - Header
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 66.0
}
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let course = courses[section]
let header = UIView(frame: CGRect(x: 0.0, y: 0.0, width: tableView.frame.width, height: 66.0))
header.tag = section
header.backgroundColor = UIColor.rosterBackgroundColor()
let shortHandLabel = UILabel(frame: CGRect(x: 0.0, y: 12.0, width: header.frame.width, height: header.frame.height / 3))
shortHandLabel.text = course.shortHand
shortHandLabel.font = UIFont.boldSystemFont(ofSize: 17.0)
shortHandLabel.textColor = UIColor.rosterHeaderTitleColor()
shortHandLabel.textAlignment = .center
header.addSubview(shortHandLabel)
let titleLabel = UILabel(frame: CGRect(x: 8.0, y: shortHandLabel.frame.maxY, width: header.frame.width - 16.0, height: header.frame.height - shortHandLabel.frame.maxY - 12.0))
titleLabel.text = course.title
titleLabel.textColor = UIColor.darkGray
titleLabel.font = UIFont.systemFont(ofSize: 14.0)
titleLabel.adjustsFontSizeToFitWidth = true
titleLabel.textAlignment = .center
header.addSubview(titleLabel)
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(headerTapped(_:)))
tapGesture.cancelsTouchesInView = false
header.addGestureRecognizer(tapGesture)
return header
}
func scrollViewDidScroll(_ scrollView: UIScrollView) {
scheduleView.alpha = (-1/20) * scrollView.contentOffset.y + 1
redView.frame.size.height = max(-scrollView.contentOffset.y + ScheduleViewHeight, 0.0)
}
}
// MARK: - Selectors
extension ScheduleTableViewController {
func deleteCellTapped(_ course: Course) {
let alertController = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
if !fromProfile {
let removeAction = UIAlertAction(title: "Remove \(course.shortHand)", style: .destructive) { Void in
let ids = self.schedule.elements.filter { $0.courseId == course.courseId }.map { $0.id }
NetworkManager.deleteElements(self.schedule, elementsWithIds: Array(ids)) { error in
if let error = error {
self.alert(errorMessage: error.localizedDescription, completion: nil)
return
}
}
}
alertController.addAction(removeAction)
}
alertController.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
present(alertController, animated: true, completion: nil)
}
func headerTapped(_ gesture: UITapGestureRecognizer) {
guard let section = gesture.view?.tag else { return }
presentCourseViewController(courses[section])
}
func presentCourseViewController(_ course: Course) {
let courseViewController = CourseViewController()
courseViewController.course = course
courseViewController.schedule = fromProfile ? nil : schedule
courseViewController.origin = fromProfile ? .fromProfile : .normal
let navigationController = UINavigationController(rootViewController: courseViewController)
self.present(navigationController, animated: true, completion: nil)
}
}
| apache-2.0 | 23715addcc5ff40c3c2438ad285f577a | 38.028571 | 236 | 0.634883 | 5.012844 | false | false | false | false |
debugsquad/nubecero | nubecero/View/HomeUploadSync/VHomeUploadSyncCell.swift | 1 | 3105 | import UIKit
class VHomeUploadSyncCell:UICollectionViewCell
{
private weak var imageView:UIImageView!
private weak var imageStatus:UIImageView!
private weak var shade:UIView!
private let kShadeAlpha:CGFloat = 0.6
override init(frame:CGRect)
{
super.init(frame:frame)
clipsToBounds = true
backgroundColor = UIColor.clear
isUserInteractionEnabled = false
let imageView:UIImageView = UIImageView()
imageView.isUserInteractionEnabled = false
imageView.translatesAutoresizingMaskIntoConstraints = false
imageView.clipsToBounds = true
imageView.contentMode = UIViewContentMode.scaleAspectFill
self.imageView = imageView
let imageStatus:UIImageView = UIImageView()
imageStatus.isUserInteractionEnabled = false
imageStatus.translatesAutoresizingMaskIntoConstraints = false
imageStatus.clipsToBounds = true
imageStatus.contentMode = UIViewContentMode.center
self.imageStatus = imageStatus
let shade:UIView = UIView()
shade.isUserInteractionEnabled = false
shade.clipsToBounds = true
shade.translatesAutoresizingMaskIntoConstraints = false
shade.alpha = kShadeAlpha
self.shade = shade
addSubview(imageView)
addSubview(shade)
addSubview(imageStatus)
let views:[String:UIView] = [
"imageView":imageView,
"imageStatus":imageStatus,
"shade":shade]
let metrics:[String:CGFloat] = [:]
addConstraints(NSLayoutConstraint.constraints(
withVisualFormat:
"H:|-0-[imageStatus]-0-|",
options:[],
metrics:metrics,
views:views))
addConstraints(NSLayoutConstraint.constraints(
withVisualFormat:
"H:|-0-[imageView]-0-|",
options:[],
metrics:metrics,
views:views))
addConstraints(NSLayoutConstraint.constraints(
withVisualFormat:
"V:|-0-[imageView]-0-|",
options:[],
metrics:metrics,
views:views))
addConstraints(NSLayoutConstraint.constraints(
withVisualFormat:"H:|-0-[shade]-0-|",
options:[],
metrics:metrics,
views:views))
addConstraints(NSLayoutConstraint.constraints(
withVisualFormat:"V:|-0-[shade]-0-|",
options:[],
metrics:metrics,
views:views))
addConstraints(NSLayoutConstraint.constraints(
withVisualFormat:"V:|-0-[imageStatus]-0-|",
options:[],
metrics:metrics,
views:views))
}
required init?(coder:NSCoder)
{
fatalError()
}
//MARK: public
func config(model:MHomeUploadItem)
{
shade.backgroundColor = model.status.color
imageView.image = model.image
imageStatus.image = UIImage(
named:model.status.assetSync)
}
}
| mit | b086b0840bf47cb65764d65fb51e1ddc | 30.683673 | 69 | 0.597101 | 5.803738 | false | false | false | false |
hassanabidpk/umapit_ios | uMAPit/controllers/SinglePlaceViewController.swift | 1 | 5758 | //
// SinglePlaceViewController.swift
// uMAPit
//
// Created by Hassan Abid on 18/02/2017.
// Copyright © 2017 uMAPit. All rights reserved.
//
import UIKit
import ImageSlideshow
class SinglePlaceViewController: UIViewController {
var singlePlace: Place?
@IBOutlet weak var userLabel: UILabel!
@IBOutlet weak var placeNameLabel: UILabel!
@IBOutlet weak var createdAtLabel: UILabel!
@IBOutlet weak var profileImage: UIImageView!
@IBOutlet weak var placeImageSlideShow: ImageSlideshow!
@IBOutlet weak var likeButton: UIButton!
@IBOutlet weak var likeLabel: UILabel!
@IBOutlet weak var flagButton: UIButton!
@IBOutlet weak var flagLabel: UILabel!
@IBOutlet weak var commentButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
configureActionItems()
setUI()
}
override func viewWillAppear(_ animated: Bool) {
self.tabBarController?.tabBar.isHidden = false
}
// MARK: - UI
func setUI() {
if let place = singlePlace {
if let fname = place.user?.first_name, let lname = place.user?.last_name {
userLabel.text = ("\(fname) \(lname) MAPPED")
}
placeNameLabel.text = place.name
createdAtLabel.text = getFormattedDateForUI(place.created_at)
likeLabel.text = "\(place.like_count)"
flagLabel.text = "\(place.flag_count)"
placeImageSlideShow.backgroundColor = UIColor.white
placeImageSlideShow.slideshowInterval = 5.0
placeImageSlideShow.pageControlPosition = PageControlPosition.underScrollView
placeImageSlideShow.pageControl.currentPageIndicatorTintColor = UIColor.lightGray;
placeImageSlideShow.pageControl.pageIndicatorTintColor = UIColor.black;
placeImageSlideShow.contentScaleMode = UIViewContentMode.scaleAspectFill
let kingfisherSource = [KingfisherSource(urlString: "\(IMAGE_BASE_URL)\(place.image_1)")!,
KingfisherSource(urlString: "\(IMAGE_BASE_URL)\(place.image_2)")!,
KingfisherSource(urlString: "\(IMAGE_BASE_URL)\(place.image_3)")!,
KingfisherSource(urlString: "\(IMAGE_BASE_URL)\(place.image_4)")!]
// try out other sources such as `afNetworkingSource`, `alamofireSource` or `sdWebImageSource` or `kingfisherSource`
placeImageSlideShow.setImageInputs(kingfisherSource)
let recognizer = UITapGestureRecognizer(target: self, action: #selector(SinglePlaceViewController.didTap))
placeImageSlideShow.addGestureRecognizer(recognizer)
}
}
func configureActionItems() {
let mapItem = UIBarButtonItem(image: UIImage(named: "ic_map_white_36pt"), style: .plain, target: self, action: #selector(SinglePlaceViewController.showMapView(_:)))
self.navigationItem.rightBarButtonItem = mapItem
}
func getFormattedDateForUI(_ date: Date?) -> String {
if let release_date = date {
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd"
return formatter.string(from: release_date)
}
return ""
}
func didTap() {
placeImageSlideShow.presentFullScreenController(from: self)
}
// MARK: - IBAction
@IBAction func didClickComment(_ sender: UIButton) {
navigationItem.title = nil
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let commentViewController = storyboard.instantiateViewController(withIdentifier: "commentslistvc") as! CommentListViewController
commentViewController.commentPlace = singlePlace
commentViewController.navigationItem.leftItemsSupplementBackButton = true
commentViewController.title = "uMAPit"
self.navigationController?.navigationBar.tintColor = Constants.tintColor
self.navigationController?.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName: Constants.tintColor]
self.navigationController?.pushViewController(commentViewController, animated: true)
}
// MARK: - Action Methods
func showMapView(_ sender: AnyObject) {
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let mapViewController = storyboard.instantiateViewController(withIdentifier: "singlemapvc") as! SingleMapViewController
mapViewController.singlePlace = self.singlePlace!
mapViewController.navigationItem.leftItemsSupplementBackButton = true
mapViewController.title = "uMAPit"
self.navigationController?.navigationBar.tintColor = Constants.tintColor
self.navigationController?.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName: Constants.tintColor]
self.navigationController?.pushViewController(mapViewController, animated: true)
}
/*
// 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.
}
*/
}
| mit | cca280350fe0ef5ea6375d29144ff8ec | 32.864706 | 172 | 0.632969 | 5.567698 | false | false | false | false |
bradhilton/SortedSet | Sources/SortedSet+Diff.swift | 1 | 1767 | //
// SortedSet+Diff.swift
// SortedSet
//
// Created by Bradley Hilton on 8/5/16.
// Copyright © 2016 Brad Hilton. All rights reserved.
//
public struct Diff : Equatable {
public var deletes = Set<Int>()
public var inserts = Set<Int>()
public var moves = Set<Move>()
public struct Move : Hashable {
public let from: Int
public let to: Int
}
}
public func ==(lhs: Diff.Move, rhs: Diff.Move) -> Bool {
return lhs.from == rhs.from && lhs.to == rhs.to
}
public func ==(lhs: Diff, rhs: Diff) -> Bool {
return lhs.deletes == rhs.deletes && lhs.inserts == rhs.inserts && lhs.moves == rhs.moves
}
extension SortedSet {
static func indices<T>(_ set: SortedSet<T>) -> [Int : Int] {
var indices = [Int : Int](minimumCapacity: set.count)
for (index, element) in set.enumerated() {
indices[element.hashValue] = index
}
return indices
}
// O(2N + M)
public static func diff(_ source: SortedSet, _ target: SortedSet) -> Diff {
var diff = Diff()
var targetSet = Set(target)
let targetIndices = indices(target)
for (index, element) in source.enumerated().reversed() {
if let newElement = targetSet.remove(element) {
if element < newElement || element > newElement {
diff.moves.insert(Diff.Move(from: index, to: targetIndices[element.hashValue]!))
}
} else {
diff.deletes.insert(index)
}
}
for element in targetSet {
guard let index = targetIndices[element.hashValue] else {
continue
}
diff.inserts.insert(index)
}
return diff
}
}
| mit | 8253b31b02378eb42c406c0638646b0d | 28.433333 | 100 | 0.560023 | 4.031963 | false | false | false | false |
prasanth223344/celapp | Cgrams/CustomViews/CGButton.swift | 1 | 1935 | //
// CGButton.swift
// Cgrams
//
// Created by JH Lee on 04/03/2017.
// Copyright © 2017 Widdit. All rights reserved.
//
import UIKit
@IBDesignable class CGButton: UIButton {
@IBInspectable var CornerRadius: CGFloat = 0
@IBInspectable var BorderWidth: CGFloat = 0
@IBInspectable var BorderColor: UIColor = UIColor.clear
@IBInspectable var TitleLines: Int = 1
@IBInspectable var VerticalAlign: Bool = false
override func draw(_ rect: CGRect) {
// Drawing code
titleLabel?.numberOfLines = TitleLines
titleLabel?.lineBreakMode = .byWordWrapping
titleLabel?.textAlignment = .center
layer.masksToBounds = true
layer.borderWidth = BorderWidth
layer.borderColor = BorderColor.cgColor
layer.cornerRadius = CornerRadius
setLayout()
}
override func setImage(_ image: UIImage?, for state: UIControlState) {
super.setImage(image, for: state)
setLayout()
}
override func setTitle(_ title: String?, for state: UIControlState) {
super.setTitle(title, for: state)
setLayout()
}
func setLayout() {
if(VerticalAlign) {
let imageSize = imageView?.frame.size
titleEdgeInsets = UIEdgeInsetsMake(0.0,
-imageSize!.width,
-(imageSize!.height + 6.0),
0.0);
// raise the image and push it right so it appears centered
// above the text
let titleSize = titleLabel?.frame.size;
imageEdgeInsets = UIEdgeInsetsMake(-(titleSize!.height + 6.0),
0.0,
0.0,
-titleSize!.width);
}
}
}
| mit | e44efaa46115baf67fde31ff9753a3af | 31.779661 | 74 | 0.527921 | 5.463277 | false | false | false | false |
ianyh/Amethyst | Amethyst/Preferences/ShortcutsPreferencesViewController.swift | 1 | 1496 | //
// ShortcutsPreferencesViewController.swift
// Amethyst
//
// Created by Ian Ynda-Hummel on 5/15/16.
// Copyright © 2016 Ian Ynda-Hummel. All rights reserved.
//
import Cocoa
import Foundation
import MASShortcut
import Silica
class ShortcutsPreferencesViewController: NSViewController, NSTableViewDataSource, NSTableViewDelegate {
private var hotKeyNameToDefaultsKey: [[String]] = []
@IBOutlet var tableView: NSTableView?
override func awakeFromNib() {
tableView?.dataSource = self
tableView?.delegate = self
}
override func viewWillAppear() {
super.viewWillAppear()
hotKeyNameToDefaultsKey = HotKeyManager<SIApplication>.hotKeyNameToDefaultsKey()
tableView?.reloadData()
}
func numberOfRows(in tableView: NSTableView) -> Int {
return hotKeyNameToDefaultsKey.count
}
func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? {
let frame = NSRect(x: 0, y: 0, width: tableView.frame.size.width, height: 30)
let shortcutItemView = ShortcutsPreferencesListItemView(frame: frame)
let name = hotKeyNameToDefaultsKey[row][0]
let key = hotKeyNameToDefaultsKey[row][1]
shortcutItemView.nameLabel?.stringValue = name
shortcutItemView.shortcutView?.associatedUserDefaultsKey = key
return shortcutItemView
}
func selectionShouldChange(in tableView: NSTableView) -> Bool {
return false
}
}
| mit | f8b372d80206690989a6e6a250f9e15d | 29.510204 | 104 | 0.707023 | 4.807074 | false | false | false | false |
hooman/swift | stdlib/public/Concurrency/AsyncDropWhileSequence.swift | 3 | 4650 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2021 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import Swift
@available(SwiftStdlib 5.5, *)
extension AsyncSequence {
/// Omits elements from the base asynchronous sequence until a given closure
/// returns false, after which it passes through all remaining elements.
///
/// Use `drop(while:)` to omit elements from an asynchronous sequence until
/// the element received meets a condition you specify.
///
/// In this example, an asynchronous sequence called `Counter` produces `Int`
/// values from `1` to `10`. The `drop(while:)` method causes the modified
/// sequence to ignore received values until it encounters one that is
/// divisible by `3`:
///
/// let stream = Counter(howHigh: 10)
/// .drop { $0 % 3 != 0 }
/// for await number in stream {
/// print("\(number) ", terminator: " ")
/// }
/// // prints "3 4 5 6 7 8 9 10"
///
/// After the predicate returns `false`, the sequence never executes it again,
/// and from then on the sequence passes through elements from its underlying
/// sequence as-is.
///
/// - Parameter predicate: A closure that takes an element as a parameter and
/// returns a Boolean value indicating whether to drop the element from the
/// modified sequence.
/// - Returns: An asynchronous sequence that skips over values from the
/// base sequence until the provided closure returns `false`.
@inlinable
public __consuming func drop(
while predicate: @escaping (Element) async -> Bool
) -> AsyncDropWhileSequence<Self> {
AsyncDropWhileSequence(self, predicate: predicate)
}
}
/// An asynchronous sequence which omits elements from the base sequence until a
/// given closure returns false, after which it passes through all remaining
/// elements.
@available(SwiftStdlib 5.5, *)
@frozen
public struct AsyncDropWhileSequence<Base: AsyncSequence> {
@usableFromInline
let base: Base
@usableFromInline
let predicate: (Base.Element) async -> Bool
@inlinable
init(
_ base: Base,
predicate: @escaping (Base.Element) async -> Bool
) {
self.base = base
self.predicate = predicate
}
}
@available(SwiftStdlib 5.5, *)
extension AsyncDropWhileSequence: AsyncSequence {
/// The type of element produced by this asynchronous sequence.
///
/// The drop-while sequence produces whatever type of element its base
/// sequence produces.
public typealias Element = Base.Element
/// The type of iterator that produces elements of the sequence.
public typealias AsyncIterator = Iterator
/// The iterator that produces elements of the drop-while sequence.
@frozen
public struct Iterator: AsyncIteratorProtocol {
@usableFromInline
var baseIterator: Base.AsyncIterator
@usableFromInline
var predicate: ((Base.Element) async -> Bool)?
@inlinable
init(
_ baseIterator: Base.AsyncIterator,
predicate: @escaping (Base.Element) async -> Bool
) {
self.baseIterator = baseIterator
self.predicate = predicate
}
/// Produces the next element in the drop-while sequence.
///
/// This iterator calls `next()` on its base iterator and evaluates the
/// result with the `predicate` closure. As long as the predicate returns
/// `true`, this method returns `nil`. After the predicate returns `false`,
/// for a value received from the base iterator, this method returns that
/// value. After that, the iterator returns values received from its
/// base iterator as-is, and never executes the predicate closure again.
@inlinable
public mutating func next() async rethrows -> Base.Element? {
while let predicate = self.predicate {
guard let element = try await baseIterator.next() else {
return nil
}
if await predicate(element) == false {
self.predicate = nil
return element
}
}
return try await baseIterator.next()
}
}
/// Creates an instance of the drop-while sequence iterator.
@inlinable
public __consuming func makeAsyncIterator() -> Iterator {
return Iterator(base.makeAsyncIterator(), predicate: predicate)
}
}
| apache-2.0 | 2b6d640a4484719f1c553872c089aa77 | 34.496183 | 80 | 0.66129 | 4.793814 | false | false | false | false |
dvaughn1712/perfect-routing | PerfectLib/NetNamedPipe.swift | 1 | 12483 | //
// NetNamedPipe.swift
// PerfectLib
//
// Created by Kyle Jessup on 7/5/15.
// Copyright (C) 2015 PerfectlySoft, Inc.
//
//===----------------------------------------------------------------------===//
//
// This source file is part of the Perfect.org open source project
//
// Copyright (c) 2015 - 2016 PerfectlySoft Inc. and the Perfect project authors
// Licensed under Apache License v2.0
//
// See http://perfect.org/licensing.html for license information
//
//===----------------------------------------------------------------------===//
//
#if os(Linux)
import SwiftGlibc
let AF_UNIX: Int32 = 1
let SOL_SOCKET: Int32 = 1
let SCM_RIGHTS: Int32 = 0x01
#else
import Darwin
#endif
/// This sub-class of NetTCP handles networking over an AF_UNIX named pipe connection.
public class NetNamedPipe : NetTCP {
/// Initialize the object using an existing file descriptor.
public convenience init(fd: Int32) {
self.init()
self.fd.fd = fd
self.fd.family = AF_UNIX
self.fd.switchToNBIO()
}
/// Override socket initialization to handle the UNIX socket type.
public override func initSocket() {
#if os(Linux)
fd.fd = socket(AF_UNIX, Int32(SOCK_STREAM.rawValue), 0)
#else
fd.fd = socket(AF_UNIX, SOCK_STREAM, 0)
#endif
fd.family = AF_UNIX
fd.switchToNBIO()
}
public override func sockName() -> (String, UInt16) {
var addr = UnsafeMutablePointer<sockaddr_un>.alloc(1)
let len = UnsafeMutablePointer<socklen_t>.alloc(1)
defer {
addr.dealloc(1)
len.dealloc(1)
}
len.memory = socklen_t(sizeof(sockaddr_in))
getsockname(fd.fd, UnsafeMutablePointer<sockaddr>(addr), len)
var nameBuf = [CChar]()
let mirror = Mirror(reflecting: addr.memory.sun_path)
let childGen = mirror.children.generate()
for _ in 0..<1024 {
let (_, elem) = childGen.next()!
if (elem as! Int8) == 0 {
break
}
nameBuf.append(elem as! Int8)
}
nameBuf.append(0)
let s = String.fromCString(nameBuf) ?? ""
let p = UInt16(0)
return (s, p)
}
public override func peerName() -> (String, UInt16) {
var addr = UnsafeMutablePointer<sockaddr_un>.alloc(1)
let len = UnsafeMutablePointer<socklen_t>.alloc(1)
defer {
addr.dealloc(1)
len.dealloc(1)
}
len.memory = socklen_t(sizeof(sockaddr_in))
getpeername(fd.fd, UnsafeMutablePointer<sockaddr>(addr), len)
var nameBuf = [CChar]()
let mirror = Mirror(reflecting: addr.memory.sun_path)
let childGen = mirror.children.generate()
for _ in 0..<1024 {
let (_, elem) = childGen.next()!
if (elem as! Int8) == 0 {
break
}
nameBuf.append(elem as! Int8)
}
nameBuf.append(0)
let s = String.fromCString(nameBuf) ?? ""
let p = UInt16(0)
return (s, p)
}
/// Bind the socket to the address path
/// - parameter address: The path on the file system at which to create and bind the socket
/// - throws: `PerfectError.NetworkError`
public func bind(address: String) throws {
initSocket()
let utf8 = address.utf8
#if os(Linux) // BSDs have a size identifier in front, Linux does not
let addrLen = sizeof(sockaddr_un)
#else
let addrLen = sizeof(UInt8) + sizeof(sa_family_t) + utf8.count + 1
#endif
let addrPtr = UnsafeMutablePointer<UInt8>.alloc(addrLen)
defer { addrPtr.destroy() }
var memLoc = 0
#if os(Linux) // BSDs use one byte for sa_family_t, Linux uses two
let afUnixShort = UInt16(AF_UNIX)
addrPtr[memLoc] = UInt8(afUnixShort & 0xFF)
memLoc += 1
addrPtr[memLoc] = UInt8((afUnixShort >> 8) & 0xFF)
memLoc += 1
#else
addrPtr[memLoc] = UInt8(addrLen)
memLoc += 1
addrPtr[memLoc] = UInt8(AF_UNIX)
memLoc += 1
#endif
for char in utf8 {
addrPtr[memLoc] = char
memLoc += 1
}
addrPtr[memLoc] = 0
#if os(Linux)
let bRes = SwiftGlibc.bind(fd.fd, UnsafePointer<sockaddr>(addrPtr), socklen_t(addrLen))
#else
let bRes = Darwin.bind(fd.fd, UnsafePointer<sockaddr>(addrPtr), socklen_t(addrLen))
#endif
if bRes == -1 {
throw PerfectError.NetworkError(errno, String.fromCString(strerror(errno))!)
}
}
/// Connect to the indicated server socket
/// - parameter address: The server socket file.
/// - parameter timeoutSeconds: The number of seconds to wait for the connection to complete. A timeout of negative one indicates that there is no timeout.
/// - parameter callBack: The closure which will be called when the connection completes. If the connection completes successfully then the current NetNamedPipe instance will be passed to the callback, otherwise, a nil object will be passed.
/// - returns: `PerfectError.NetworkError`
public func connect(address: String, timeoutSeconds: Double, callBack: (NetNamedPipe?) -> ()) throws {
initSocket()
let utf8 = address.utf8
let addrLen = sizeof(UInt8) + sizeof(sa_family_t) + utf8.count + 1
let addrPtr = UnsafeMutablePointer<UInt8>.alloc(addrLen)
defer { addrPtr.destroy() }
var memLoc = 0
addrPtr[memLoc] = UInt8(addrLen)
memLoc += 1
addrPtr[memLoc] = UInt8(AF_UNIX)
memLoc += 1
for char in utf8 {
addrPtr[memLoc] = char
memLoc += 1
}
addrPtr[memLoc] = 0
#if os(Linux)
let cRes = SwiftGlibc.connect(fd.fd, UnsafePointer<sockaddr>(addrPtr), socklen_t(addrLen))
#else
let cRes = Darwin.connect(fd.fd, UnsafePointer<sockaddr>(addrPtr), socklen_t(addrLen))
#endif
if cRes != -1 {
callBack(self)
} else {
guard errno == EINPROGRESS else {
try ThrowNetworkError()
}
let event: LibEvent = LibEvent(base: LibEvent.eventBase, fd: fd.fd, what: EV_WRITE, userData: nil) {
(fd:Int32, w:Int16, ud:AnyObject?) -> () in
if (Int32(w) & EV_TIMEOUT) != 0 {
callBack(nil)
} else {
callBack(self)
}
}
event.add(timeoutSeconds)
}
}
/// Send the existing opened file descriptor over the connection to the recipient
/// - parameter fd: The file descriptor to send
/// - parameter callBack: The callback to call when the send completes. The parameter passed will be `true` if the send completed without error.
/// - throws: `PerfectError.NetworkError`
public func sendFd(fd: Int32, callBack: (Bool) -> ()) throws {
let length = sizeof(cmsghdr) + sizeof(Int32)
#if os(Linux)
let msghdr = UnsafeMutablePointer<SwiftGlibc.msghdr>.alloc(1)
#else
let msghdr = UnsafeMutablePointer<Darwin.msghdr>.alloc(1)
#endif
let nothingPtr = UnsafeMutablePointer<iovec>.alloc(1)
let nothing = UnsafeMutablePointer<CChar>.alloc(1)
let buffer = UnsafeMutablePointer<CChar>.alloc(length)
defer {
msghdr.destroy()
msghdr.dealloc(1)
buffer.destroy()
buffer.dealloc(length)
nothingPtr.destroy()
nothingPtr.dealloc(1)
nothing.destroy()
nothing.dealloc(1)
}
let cmsg = UnsafeMutablePointer<cmsghdr>(buffer)
#if os(Linux)
cmsg.memory.cmsg_len = Int(socklen_t(length))
#else
cmsg.memory.cmsg_len = socklen_t(length)
#endif
cmsg.memory.cmsg_level = SOL_SOCKET
cmsg.memory.cmsg_type = SCM_RIGHTS
let asInts = UnsafeMutablePointer<Int32>(cmsg.advancedBy(1))
asInts.memory = fd
nothing.memory = 33
nothingPtr.memory.iov_base = UnsafeMutablePointer<Void>(nothing)
nothingPtr.memory.iov_len = 1
msghdr.memory.msg_name = UnsafeMutablePointer<Void>(nil)
msghdr.memory.msg_namelen = 0
msghdr.memory.msg_flags = 0
msghdr.memory.msg_iov = nothingPtr
msghdr.memory.msg_iovlen = 1
msghdr.memory.msg_control = UnsafeMutablePointer<Void>(buffer)
#if os(Linux)
msghdr.memory.msg_controllen = Int(socklen_t(length))
#else
msghdr.memory.msg_controllen = socklen_t(length)
#endif
let res = sendmsg(Int32(self.fd.fd), msghdr, 0)
if res > 0 {
callBack(true)
} else if res == -1 && errno == EAGAIN {
let event: LibEvent = LibEvent(base: LibEvent.eventBase, fd: self.fd.fd, what: EV_WRITE, userData: nil) {
[weak self] (fd:Int32, w:Int16, ud:AnyObject?) -> () in
if (Int32(w) & EV_TIMEOUT) != 0 {
callBack(false)
} else {
do {
try self?.sendFd(fd, callBack: callBack)
} catch {
callBack(false)
}
}
}
event.add()
} else {
try ThrowNetworkError()
}
}
/// Receive an existing opened file descriptor from the sender
/// - parameter callBack: The callback to call when the receive completes. The parameter passed will be the received file descriptor or invalidSocket.
/// - throws: `PerfectError.NetworkError`
public func receiveFd(callBack: (Int32) -> ()) throws {
let length = sizeof(cmsghdr) + sizeof(Int32)
var msghdrr = msghdr()
let nothingPtr = UnsafeMutablePointer<iovec>.alloc(1)
let nothing = UnsafeMutablePointer<CChar>.alloc(1)
let buffer = UnsafeMutablePointer<CChar>.alloc(length)
defer {
buffer.destroy()
buffer.dealloc(length)
nothingPtr.destroy()
nothingPtr.dealloc(1)
nothing.destroy()
nothing.dealloc(1)
}
nothing.memory = 33
nothingPtr.memory.iov_base = UnsafeMutablePointer<Void>(nothing)
nothingPtr.memory.iov_len = 1
msghdrr.msg_iov = UnsafeMutablePointer<iovec>(nothingPtr)
msghdrr.msg_iovlen = 1
msghdrr.msg_control = UnsafeMutablePointer<Void>(buffer)
#if os(Linux)
msghdrr.msg_controllen = Int(socklen_t(length))
#else
msghdrr.msg_controllen = socklen_t(length)
#endif
let cmsg = UnsafeMutablePointer<cmsghdr>(buffer)
#if os(Linux)
cmsg.memory.cmsg_len = Int(socklen_t(length))
#else
cmsg.memory.cmsg_len = socklen_t(length)
#endif
cmsg.memory.cmsg_level = SOL_SOCKET
cmsg.memory.cmsg_type = SCM_RIGHTS
let asInts = UnsafeMutablePointer<Int32>(cmsg.advancedBy(1))
asInts.memory = -1
let res = recvmsg(Int32(self.fd.fd), &msghdrr, 0)
if res > 0 {
let receivedInt = asInts.memory
callBack(receivedInt)
} else if res == -1 && errno == EAGAIN {
let event: LibEvent = LibEvent(base: LibEvent.eventBase, fd: self.fd.fd, what: EV_READ, userData: nil) {
[weak self] (fd:Int32, w:Int16, ud:AnyObject?) -> () in
if (Int32(w) & EV_TIMEOUT) != 0 {
callBack(invalidSocket)
} else {
do {
try self?.receiveFd(callBack)
} catch {
callBack(invalidSocket)
}
}
}
event.add()
} else {
try ThrowNetworkError()
}
}
/// Send the existing & opened `File`'s descriptor over the connection to the recipient
/// - parameter file: The `File` whose descriptor to send
/// - parameter callBack: The callback to call when the send completes. The parameter passed will be `true` if the send completed without error.
/// - throws: `PerfectError.NetworkError`
public func sendFile(file: File, callBack: (Bool) -> ()) throws {
try self.sendFd(Int32(file.fd), callBack: callBack)
}
/// Send the existing & opened `NetTCP`'s descriptor over the connection to the recipient
/// - parameter file: The `NetTCP` whose descriptor to send
/// - parameter callBack: The callback to call when the send completes. The parameter passed will be `true` if the send completed without error.
/// - throws: `PerfectError.NetworkError`
public func sendFile(file: NetTCP, callBack: (Bool) -> ()) throws {
try self.sendFd(file.fd.fd, callBack: callBack)
}
/// Receive an existing opened `File` descriptor from the sender
/// - parameter callBack: The callback to call when the receive completes. The parameter passed will be the received `File` object or nil.
/// - throws: `PerfectError.NetworkError`
public func receiveFile(callBack: (File?) -> ()) throws {
try self.receiveFd {
(fd: Int32) -> () in
if fd == invalidSocket {
callBack(nil)
} else {
callBack(File(fd: fd, path: ""))
}
}
}
/// Receive an existing opened `NetTCP` descriptor from the sender
/// - parameter callBack: The callback to call when the receive completes. The parameter passed will be the received `NetTCP` object or nil.
/// - throws: `PerfectError.NetworkError`
public func receiveNetTCP(callBack: (NetTCP?) -> ()) throws {
try self.receiveFd {
(fd: Int32) -> () in
if fd == invalidSocket {
callBack(nil)
} else {
callBack(NetTCP(fd: fd))
}
}
}
/// Receive an existing opened `NetNamedPipe` descriptor from the sender
/// - parameter callBack: The callback to call when the receive completes. The parameter passed will be the received `NetNamedPipe` object or nil.
/// - throws: `PerfectError.NetworkError`
public func receiveNetNamedPipe(callBack: (NetNamedPipe?) -> ()) throws {
try self.receiveFd {
(fd: Int32) -> () in
if fd == invalidSocket {
callBack(nil)
} else {
callBack(NetNamedPipe(fd: fd))
}
}
}
override func makeFromFd(fd: Int32) -> NetTCP {
return NetNamedPipe(fd: fd)
}
}
| unlicense | d6a79001b413a84445e57e6bb93ad708 | 28.792363 | 242 | 0.675639 | 3.183627 | false | false | false | false |
BranchMetrics/iOS-Deferred-Deep-Linking-SDK | Branch-TestBed-Swift/TestBed-Swift/CommerceEventDetailsTableViewController.swift | 1 | 7212 | //
// CommerceEventDetailsTableViewController.swift
// TestBed-Swift
//
// Created by David Westgate on 7/11/17.
// Copyright © 2017 Branch Metrics. All rights reserved.
//
import UIKit
class CommerceEventDetailsTableViewController: UITableViewController, UITextFieldDelegate, UIPickerViewDataSource, UIPickerViewDelegate {
// MARK: - Controls
@IBOutlet weak var resetAllValuesButton: UIButton!
@IBOutlet weak var transactionIDTextField: UITextField!
@IBOutlet weak var affiliationTextField: UITextField!
@IBOutlet weak var couponTextField: UITextField!
@IBOutlet weak var currencyTextField: UITextField!
@IBOutlet weak var shippingTextField: UITextField!
@IBOutlet weak var taxTextField: UITextField!
@IBOutlet weak var revenueTextField: UITextField!
var defaults = CommerceEventData.commerceEventDefaults()
let picker = UIPickerView()
let currencies = CommerceEventData.currencies()
// MARK: - Core View Functions
override func viewDidLoad() {
super.viewDidLoad()
transactionIDTextField.delegate = self
affiliationTextField.delegate = self
couponTextField.delegate = self
currencyTextField.delegate = self
shippingTextField.delegate = self
taxTextField.delegate = self
revenueTextField.delegate = self
transactionIDTextField.placeholder = defaults["transactionID"]
affiliationTextField.placeholder = defaults["affiliation"]
couponTextField.placeholder = defaults["coupon"]
currencyTextField.placeholder = defaults["currency"]
shippingTextField.placeholder = defaults["shipping"]
taxTextField.placeholder = defaults["tax"]
revenueTextField.placeholder = defaults["revenue"]
currencyTextField.inputView = picker
currencyTextField.inputAccessoryView = createToolbar(true)
picker.dataSource = self
picker.delegate = self
picker.showsSelectionIndicator = true
transactionIDTextField.becomeFirstResponder()
refreshControls()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
// MARK: - Controls
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
self.view.endEditing(true)
return true
}
@IBAction func resetAllValuesButtonTouchUpInside(_ sender: AnyObject) {
clearControls()
refreshDataStore()
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
switch((indexPath as NSIndexPath).section, (indexPath as NSIndexPath).row) {
case (1,7) :
self.performSegue(withIdentifier: "ShowProducts", sender: "Products")
default : break
}
}
@IBAction func unwindProductArrayTableViewController(_ segue:UIStoryboardSegue) {}
func textFieldDidEndEditing(_ textField: UITextField) {
refreshDataStore()
refreshControls()
}
func clearControls() {
transactionIDTextField.text = ""
affiliationTextField.text = ""
couponTextField.text = ""
currencyTextField.text = ""
shippingTextField.text = ""
taxTextField.text = ""
revenueTextField.text = ""
resetAllValuesButton.isEnabled = false
}
func refreshControls() {
guard var commerceEvent = CommerceEventData.commerceEvent() else {
return
}
guard commerceEvent["default"] as? String == "false" else {
clearControls()
return
}
var resetAllValuesEnabled = false
if (commerceEvent["transactionID"] as? String != "") {
transactionIDTextField.text = commerceEvent["transactionID"] as? String
resetAllValuesEnabled = true
}
if (commerceEvent["affiliation"] as? String != "") {
affiliationTextField.text = commerceEvent["affiliation"] as? String
resetAllValuesEnabled = true
}
if (commerceEvent["coupon"] as? String != "") {
couponTextField.text = commerceEvent["coupon"] as? String
resetAllValuesEnabled = true
}
if (commerceEvent["currency"] as? String != "") {
currencyTextField.text = commerceEvent["currency"] as? String
resetAllValuesEnabled = true
}
if (commerceEvent["shipping"] as? String != "") {
shippingTextField.text = commerceEvent["shipping"] as? String
resetAllValuesEnabled = true
}
if (commerceEvent["tax"] as? String != "") {
taxTextField.text = commerceEvent["tax"] as? String
resetAllValuesEnabled = true
}
if (commerceEvent["revenue"] as? String != "") {
revenueTextField.text = commerceEvent["revenue"] as? String
resetAllValuesEnabled = true
}
resetAllValuesButton.isEnabled = resetAllValuesEnabled
}
func refreshDataStore() {
CommerceEventData.setCommerceEvent([
"transactionID": transactionIDTextField.text!,
"affiliation": affiliationTextField.text!,
"coupon": couponTextField.text!,
"currency": currencyTextField.text!,
"shipping": shippingTextField.text!,
"tax": taxTextField.text!,
"revenue": revenueTextField.text!,
"default": "false"
])
}
//MARK: - PickerView
func createToolbar(_ withCancelButton: Bool) -> UIToolbar {
let toolbar = UIToolbar(frame: CGRect(x: 0,y: 0,width: self.view.frame.size.width,height: 44))
toolbar.tintColor = UIColor.gray
let donePickingButton = UIBarButtonItem.init(barButtonSystemItem: UIBarButtonSystemItem.done, target: self, action: #selector(self.donePicking))
let emptySpace = UIBarButtonItem.init(barButtonSystemItem: UIBarButtonSystemItem.flexibleSpace, target: nil, action: nil)
if (withCancelButton) {
let cancelPickingButton = UIBarButtonItem.init(barButtonSystemItem: UIBarButtonSystemItem.cancel, target: self, action: #selector(self.cancelPicking))
toolbar.setItems([cancelPickingButton, emptySpace, donePickingButton], animated: true)
} else {
toolbar.setItems([emptySpace, donePickingButton], animated: true)
}
return toolbar
}
@objc func cancelPicking() {
currencyTextField.resignFirstResponder()
}
@objc func donePicking() {
self.currencyTextField.text = String(currencies[picker.selectedRow(inComponent: 0)].prefix(3))
self.currencyTextField.resignFirstResponder()
}
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return currencies.count
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return currencies[row]
}
}
| mit | 759053b87ed5e93bb437afcaae5c3078 | 35.979487 | 162 | 0.646374 | 5.349407 | false | false | false | false |
OpenKitten/Meow | Sources/Meow/Reference.swift | 1 | 6278 | import Foundation
import NIO
/// Reference to a Model
public struct Reference<M: Model>: Hashable, Resolvable {
/// The referenced id
public let reference: M.Identifier
public typealias Result = M
/// Compares two references to be referring to the same entity
public static func == (lhs: Reference<M>, rhs: Reference<M>) -> Bool {
return lhs.reference == rhs.reference
}
/// Makes a reference hashable
public var hashValue: Int {
return reference.hashValue
}
/// Creates a reference to an entity
public init(to entity: M) {
reference = entity._id
}
/// Creates an unchecked reference to an entity
public init(unsafeTo target: M.Identifier) {
reference = target
}
/// Resolves a reference
public func resolve(in context: Context, where query: Query = Query()) -> EventLoopFuture<M> {
return resolveIfPresent(in: context, where: query).thenThrowing { referenced in
guard let referenced = referenced else {
throw MeowError.referenceError(id: self.reference, type: M.self)
}
return referenced
}
}
/// Resolves a reference, returning `nil` if the referenced object cannot be found
public func resolveIfPresent(in context: Context, where query: Query = Query()) -> EventLoopFuture<M?> {
return context.findOne(M.self, where: "_id" == reference && query)
}
/// Deletes the target of the reference (making it invalid)
public func deleteTarget(in context: Context) -> EventLoopFuture<Void> {
return context.deleteOne(M.self, where: "_id" == reference).map { _ in }
}
}
public postfix func * <M>(instance: M) -> Reference<M> {
return Reference(to: instance)
}
postfix operator *
extension Reference: Codable {
public func encode(to encoder: Encoder) throws {
try reference.encode(to: encoder)
}
public init(from decoder: Decoder) throws {
reference = try M.Identifier(from: decoder)
}
}
public protocol Resolvable {
associatedtype Result
associatedtype IfPresentResult
func resolve(in context: Context, where query: Query) -> EventLoopFuture<Result>
func resolveIfPresent(in context: Context, where query: Query) -> EventLoopFuture<IfPresentResult>
}
public extension Resolvable where Result: QueryableModel {
public func resolve(in context: Context, where query: ModelQuery<Result>) -> EventLoopFuture<Result> {
return self.resolve(in: context, where: query.query)
}
public func resolveIfPresent(in context: Context, where query: ModelQuery<Result>) -> EventLoopFuture<IfPresentResult> {
return self.resolveIfPresent(in: context, where: query.query)
}
}
public extension Resolvable where Result: Sequence, Result.Element: QueryableModel {
public func resolve(in context: Context, where query: ModelQuery<Result.Element>) -> EventLoopFuture<Result> {
return self.resolve(in: context, where: query.query)
}
public func resolveIfPresent(in context: Context, where query: ModelQuery<Result.Element>) -> EventLoopFuture<IfPresentResult> {
return self.resolveIfPresent(in: context, where: query.query)
}
}
extension Set: Resolvable where Element: Resolvable {}
extension Array: Resolvable where Element: Resolvable {}
extension Sequence where Element: Resolvable {
/// Resolves the contained references
///
/// - parameter context: The context to use for resolving the references
/// - returns: An EventLoopFuture that completes with an array of
public func resolve(in context: Context, where query: Query = Query()) -> EventLoopFuture<[Element.Result]> {
let futures = self.map { $0.resolve(in: context, where: query) }
return EventLoopFuture.reduce(into: [], futures, eventLoop: context.eventLoop) { array, resolved in
array.append(resolved)
}
}
public func resolveIfPresent(in context: Context, where query: Query = Query()) -> EventLoopFuture<[Element.IfPresentResult]> {
let futures = self.map { $0.resolveIfPresent(in: context, where: query) }
return EventLoopFuture.reduce(into: [], futures, eventLoop: context.eventLoop) { array, resolved in
array.append(resolved)
}
}
}
extension Dictionary: Resolvable where Value: Resolvable {
public typealias Result = [Key: Value.Result]
public typealias IfPresentResult = [Key: Value.IfPresentResult]
public func resolve(in context: Context, where query: Query = Query()) -> EventLoopFuture<[Key: Value.Result]> {
let futures = self.map { $0.value.resolve(in: context, where: query).and(result: $0.key) }
return EventLoopFuture.reduce(into: [:], futures, eventLoop: context.eventLoop) { dictionary, pair in
let (value, key) = pair
dictionary[key] = value
}
}
public func resolveIfPresent(in context: Context, where query: Query = Query()) -> EventLoopFuture<[Key: Value.IfPresentResult]> {
let futures = self.map { $0.value.resolveIfPresent(in: context, where: query).and(result: $0.key) }
return EventLoopFuture.reduce(into: [:], futures, eventLoop: context.eventLoop) { dictionary, pair in
let (value, key) = pair
dictionary[key] = value
}
}
}
extension Optional: Resolvable where Wrapped: Resolvable {
public typealias Result = Wrapped.Result?
public typealias IfPresentResult = Wrapped.IfPresentResult?
public func resolve(in context: Context, where query: Query) -> EventLoopFuture<Wrapped.Result?> {
switch self {
case .none: return context.eventLoop.newSucceededFuture(result: nil)
case .some(let value): return value.resolve(in: context, where: query).map { $0 }
}
}
public func resolveIfPresent(in context: Context, where query: Query) -> EventLoopFuture<Wrapped.IfPresentResult?> {
switch self {
case .none: return context.eventLoop.newSucceededFuture(result: nil)
case .some(let value): return value.resolveIfPresent(in: context, where: query).map { $0 }
}
}
}
| mit | f45b5a7cd24c8d0790bdcd0cefa6b321 | 38.484277 | 134 | 0.666614 | 4.532852 | false | false | false | false |
frootloops/swift | test/SILGen/generic_closures.swift | 1 | 14892 | // RUN: %target-swift-frontend -parse-stdlib -emit-silgen -enable-sil-ownership %s | %FileCheck %s
import Swift
var zero: Int
// CHECK-LABEL: sil hidden @_T016generic_closures0A21_nondependent_context{{[_0-9a-zA-Z]*}}F
func generic_nondependent_context<T>(_ x: T, y: Int) -> Int {
func foo() -> Int { return y }
func bar() -> Int { return y }
// CHECK: [[FOO:%.*]] = function_ref @_T016generic_closures0A21_nondependent_context{{.*}} : $@convention(thin) (Int) -> Int
// CHECK: [[FOO_CLOSURE:%.*]] = partial_apply [callee_guaranteed] [[FOO]](%1)
// CHECK: destroy_value [[FOO_CLOSURE]]
let _ = foo
// CHECK: [[BAR:%.*]] = function_ref @_T016generic_closures0A21_nondependent_context{{.*}} : $@convention(thin) (Int) -> Int
// CHECK: [[BAR_CLOSURE:%.*]] = partial_apply [callee_guaranteed] [[BAR]](%1)
// CHECK: destroy_value [[BAR_CLOSURE]]
let _ = bar
// CHECK: [[FOO:%.*]] = function_ref @_T016generic_closures0A21_nondependent_context{{.*}} : $@convention(thin) (Int) -> Int
// CHECK: [[FOO_CLOSURE:%.*]] = apply [[FOO]]
_ = foo()
// CHECK: [[BAR:%.*]] = function_ref @_T016generic_closures0A21_nondependent_context{{.*}} : $@convention(thin) (Int) -> Int
// CHECK: [[BAR_CLOSURE:%.*]] = apply [[BAR]]
// CHECK: [[BAR_CLOSURE]]
return bar()
}
// CHECK-LABEL: sil hidden @_T016generic_closures0A8_capture{{[_0-9a-zA-Z]*}}F
func generic_capture<T>(_ x: T) -> Any.Type {
func foo() -> Any.Type { return T.self }
// CHECK: [[FOO:%.*]] = function_ref @_T016generic_closures0A8_capture{{.*}} : $@convention(thin) <τ_0_0> () -> @thick Any.Type
// CHECK: [[FOO_CLOSURE:%.*]] = partial_apply [callee_guaranteed] [[FOO]]<T>()
// CHECK: destroy_value [[FOO_CLOSURE]]
let _ = foo
// CHECK: [[FOO:%.*]] = function_ref @_T016generic_closures0A8_capture{{.*}} : $@convention(thin) <τ_0_0> () -> @thick Any.Type
// CHECK: [[FOO_CLOSURE:%.*]] = apply [[FOO]]<T>()
// CHECK: return [[FOO_CLOSURE]]
return foo()
}
// CHECK-LABEL: sil hidden @_T016generic_closures0A13_capture_cast{{[_0-9a-zA-Z]*}}F
func generic_capture_cast<T>(_ x: T, y: Any) -> Bool {
func foo(_ a: Any) -> Bool { return a is T }
// CHECK: [[FOO:%.*]] = function_ref @_T016generic_closures0A13_capture_cast{{.*}} : $@convention(thin) <τ_0_0> (@in Any) -> Bool
// CHECK: [[FOO_CLOSURE:%.*]] = partial_apply [callee_guaranteed] [[FOO]]<T>()
// CHECK: destroy_value [[FOO_CLOSURE]]
let _ = foo
// CHECK: [[FOO:%.*]] = function_ref @_T016generic_closures0A13_capture_cast{{.*}} : $@convention(thin) <τ_0_0> (@in Any) -> Bool
// CHECK: [[FOO_CLOSURE:%.*]] = apply [[FOO]]<T>([[ARG:%.*]])
// CHECK: return [[FOO_CLOSURE]]
return foo(y)
}
protocol Concept {
var sensical: Bool { get }
}
// CHECK-LABEL: sil hidden @_T016generic_closures0A22_nocapture_existential{{[_0-9a-zA-Z]*}}F
func generic_nocapture_existential<T>(_ x: T, y: Concept) -> Bool {
func foo(_ a: Concept) -> Bool { return a.sensical }
// CHECK: [[FOO:%.*]] = function_ref @_T016generic_closures0A22_nocapture_existential{{.*}} : $@convention(thin) (@in Concept) -> Bool
// CHECK: [[FOO_CLOSURE:%.*]] = thin_to_thick_function [[FOO]]
// CHECK: destroy_value [[FOO_CLOSURE]]
let _ = foo
// CHECK: [[FOO:%.*]] = function_ref @_T016generic_closures0A22_nocapture_existential{{.*}} : $@convention(thin) (@in Concept) -> Bool
// CHECK: [[FOO_CLOSURE:%.*]] = apply [[FOO]]([[ARG:%.*]])
// CHECK: return [[FOO_CLOSURE]]
return foo(y)
}
// CHECK-LABEL: sil hidden @_T016generic_closures0A18_dependent_context{{[_0-9a-zA-Z]*}}F
func generic_dependent_context<T>(_ x: T, y: Int) -> T {
func foo() -> T { return x }
// CHECK: [[FOO:%.*]] = function_ref @_T016generic_closures0A18_dependent_context{{.*}} : $@convention(thin) <τ_0_0> (@guaranteed <τ_0_0> { var τ_0_0 } <τ_0_0>) -> @out τ_0_0
// CHECK: [[FOO_CLOSURE:%.*]] = partial_apply [callee_guaranteed] [[FOO]]<T>([[BOX:%.*]])
// CHECK: destroy_value [[FOO_CLOSURE]]
let _ = foo
// CHECK: [[FOO:%.*]] = function_ref @_T016generic_closures0A18_dependent_context{{.*}} : $@convention(thin) <τ_0_0> (@guaranteed <τ_0_0> { var τ_0_0 } <τ_0_0>) -> @out τ_0_0
// CHECK: [[FOO_CLOSURE:%.*]] = apply [[FOO]]<T>
// CHECK: return
return foo()
}
enum Optionable<Wrapped> {
case none
case some(Wrapped)
}
class NestedGeneric<U> {
class func generic_nondependent_context<T>(_ x: T, y: Int, z: U) -> Int {
func foo() -> Int { return y }
let _ = foo
return foo()
}
class func generic_dependent_inner_context<T>(_ x: T, y: Int, z: U) -> T {
func foo() -> T { return x }
let _ = foo
return foo()
}
class func generic_dependent_outer_context<T>(_ x: T, y: Int, z: U) -> U {
func foo() -> U { return z }
let _ = foo
return foo()
}
class func generic_dependent_both_contexts<T>(_ x: T, y: Int, z: U) -> (T, U) {
func foo() -> (T, U) { return (x, z) }
let _ = foo
return foo()
}
// CHECK-LABEL: sil hidden @_T016generic_closures13NestedGenericC20nested_reabstraction{{[_0-9a-zA-Z]*}}F
// CHECK: [[REABSTRACT:%.*]] = function_ref @_T0Ieg_ytytIegir_TR
// CHECK: partial_apply [callee_guaranteed] [[REABSTRACT]]
func nested_reabstraction<T>(_ x: T) -> Optionable<() -> ()> {
return .some({})
}
}
// <rdar://problem/15417773>
// Ensure that nested closures capture the generic parameters of their nested
// context.
// CHECK: sil hidden @_T016generic_closures018nested_closure_in_A0xxlF : $@convention(thin) <T> (@in T) -> @out T
// CHECK: function_ref [[OUTER_CLOSURE:@_T016generic_closures018nested_closure_in_A0xxlFxycfU_]]
// CHECK: sil private [[OUTER_CLOSURE]] : $@convention(thin) <T> (@inout_aliasable T) -> @out T
// CHECK: function_ref [[INNER_CLOSURE:@_T016generic_closures018nested_closure_in_A0xxlFxycfU_xycfU_]]
// CHECK: sil private [[INNER_CLOSURE]] : $@convention(thin) <T> (@inout_aliasable T) -> @out T {
func nested_closure_in_generic<T>(_ x:T) -> T {
return { { x }() }()
}
// CHECK-LABEL: sil hidden @_T016generic_closures16local_properties{{[_0-9a-zA-Z]*}}F
func local_properties<T>(_ t: inout T) {
var prop: T {
get {
return t
}
set {
t = newValue
}
}
// CHECK: [[GETTER_REF:%[0-9]+]] = function_ref [[GETTER_CLOSURE:@_T016generic_closures16local_properties[_0-9a-zA-Z]*]] : $@convention(thin) <τ_0_0> (@inout_aliasable τ_0_0) -> @out τ_0_0
// CHECK: apply [[GETTER_REF]]
t = prop
// CHECK: [[SETTER_REF:%[0-9]+]] = function_ref [[SETTER_CLOSURE:@_T016generic_closures16local_properties[_0-9a-zA-Z]*]] : $@convention(thin) <τ_0_0> (@in τ_0_0, @inout_aliasable τ_0_0) -> ()
// CHECK: apply [[SETTER_REF]]
prop = t
var prop2: T {
get {
return t
}
set {
// doesn't capture anything
}
}
// CHECK: [[GETTER2_REF:%[0-9]+]] = function_ref [[GETTER2_CLOSURE:@_T016generic_closures16local_properties[_0-9a-zA-Z]*]] : $@convention(thin) <τ_0_0> (@inout_aliasable τ_0_0) -> @out τ_0_0
// CHECK: apply [[GETTER2_REF]]
t = prop2
// CHECK: [[SETTER2_REF:%[0-9]+]] = function_ref [[SETTER2_CLOSURE:@_T016generic_closures16local_properties[_0-9a-zA-Z]*]] : $@convention(thin) <τ_0_0> (@in τ_0_0) -> ()
// CHECK: apply [[SETTER2_REF]]
prop2 = t
}
protocol Fooable {
static func foo() -> Bool
}
// <rdar://problem/16399018>
func shmassert(_ f: @autoclosure () -> Bool) {}
// CHECK-LABEL: sil hidden @_T016generic_closures08capture_A6_param{{[_0-9a-zA-Z]*}}F
func capture_generic_param<A: Fooable>(_ x: A) {
shmassert(A.foo())
}
// Make sure we use the correct convention when capturing class-constrained
// member types: <rdar://problem/24470533>
class Class {}
protocol HasClassAssoc { associatedtype Assoc : Class }
// CHECK-LABEL: sil hidden @_T016generic_closures027captures_class_constrained_A0yx_5AssocQzADc1ftAA08HasClassF0RzlF
// CHECK: bb0([[ARG1:%.*]] : @trivial $*T, [[ARG2:%.*]] : @owned $@callee_guaranteed (@owned T.Assoc) -> @owned T.Assoc):
// CHECK: [[GENERIC_FN:%.*]] = function_ref @_T016generic_closures027captures_class_constrained_A0yx_5AssocQzADc1ftAA08HasClassF0RzlFA2DcycfU_
// CHECK: [[ARG2_COPY:%.*]] = copy_value [[ARG2]]
// CHECK: [[CONCRETE_FN:%.*]] = partial_apply [callee_guaranteed] [[GENERIC_FN]]<T>([[ARG2_COPY]])
func captures_class_constrained_generic<T : HasClassAssoc>(_ x: T, f: @escaping (T.Assoc) -> T.Assoc) {
let _: () -> (T.Assoc) -> T.Assoc = { f }
}
// Make sure local generic functions can have captures
// CHECK-LABEL: sil hidden @_T016generic_closures06outer_A0yx1t_Si1itlF : $@convention(thin) <T> (@in T, Int) -> ()
func outer_generic<T>(t: T, i: Int) {
func inner_generic_nocapture<U>(u: U) -> U {
return u
}
func inner_generic1<U>(u: U) -> Int {
return i
}
func inner_generic2<U>(u: U) -> T {
return t
}
let _: () -> () = inner_generic_nocapture
// CHECK: [[FN:%.*]] = function_ref @_T016generic_closures06outer_A0yx1t_Si1itlF06inner_A10_nocaptureL_qd__qd__1u_tr__lF : $@convention(thin) <τ_0_0><τ_1_0> (@in τ_1_0) -> @out τ_1_0
// CHECK: [[CLOSURE:%.*]] = partial_apply [callee_guaranteed] [[FN]]<T, ()>() : $@convention(thin) <τ_0_0><τ_1_0> (@in τ_1_0) -> @out τ_1_0
// CHECK: [[THUNK:%.*]] = function_ref @_T0ytytIegir_Ieg_TR
// CHECK: [[THUNK_CLOSURE:%.*]] = partial_apply [callee_guaranteed] [[THUNK]]([[CLOSURE]])
// CHECK: destroy_value [[THUNK_CLOSURE]]
// CHECK: [[FN:%.*]] = function_ref @_T016generic_closures06outer_A0yx1t_Si1itlF06inner_A10_nocaptureL_qd__qd__1u_tr__lF : $@convention(thin) <τ_0_0><τ_1_0> (@in τ_1_0) -> @out τ_1_0
// CHECK: [[RESULT:%.*]] = apply [[FN]]<T, T>({{.*}}) : $@convention(thin) <τ_0_0><τ_1_0> (@in τ_1_0) -> @out τ_1_0
_ = inner_generic_nocapture(u: t)
// CHECK: [[FN:%.*]] = function_ref @_T016generic_closures06outer_A0yx1t_Si1itlF14inner_generic1L_Siqd__1u_tr__lF : $@convention(thin) <τ_0_0><τ_1_0> (@in τ_1_0, Int) -> Int
// CHECK: [[CLOSURE:%.*]] = partial_apply [callee_guaranteed] [[FN]]<T, ()>(%1) : $@convention(thin) <τ_0_0><τ_1_0> (@in τ_1_0, Int) -> Int
// CHECK: [[THUNK:%.*]] = function_ref @_T0ytSiIegid_SiIegd_TR
// CHECK: [[THUNK_CLOSURE:%.*]] = partial_apply [callee_guaranteed] [[THUNK]]([[CLOSURE]])
// CHECK: destroy_value [[THUNK_CLOSURE]]
let _: () -> Int = inner_generic1
// CHECK: [[FN:%.*]] = function_ref @_T016generic_closures06outer_A0yx1t_Si1itlF14inner_generic1L_Siqd__1u_tr__lF : $@convention(thin) <τ_0_0><τ_1_0> (@in τ_1_0, Int) -> Int
// CHECK: [[RESULT:%.*]] = apply [[FN]]<T, T>({{.*}}) : $@convention(thin) <τ_0_0><τ_1_0> (@in τ_1_0, Int) -> Int
_ = inner_generic1(u: t)
// CHECK: [[FN:%.*]] = function_ref @_T016generic_closures06outer_A0yx1t_Si1itlF14inner_generic2L_xqd__1u_tr__lF : $@convention(thin) <τ_0_0><τ_1_0> (@in τ_1_0, @guaranteed <τ_0_0> { var τ_0_0 } <τ_0_0>) -> @out τ_0_0
// CHECK: [[CLOSURE:%.*]] = partial_apply [callee_guaranteed] [[FN]]<T, ()>([[ARG:%.*]]) : $@convention(thin) <τ_0_0><τ_1_0> (@in τ_1_0, @guaranteed <τ_0_0> { var τ_0_0 } <τ_0_0>) -> @out τ_0_0
// CHECK: [[THUNK:%.*]] = function_ref @_T0ytxIegir_xIegr_lTR
// CHECK: [[THUNK_CLOSURE:%.*]] = partial_apply [callee_guaranteed] [[THUNK]]<T>([[CLOSURE]])
// CHECK: destroy_value [[THUNK_CLOSURE]]
let _: () -> T = inner_generic2
// CHECK: [[FN:%.*]] = function_ref @_T016generic_closures06outer_A0yx1t_Si1itlF14inner_generic2L_xqd__1u_tr__lF : $@convention(thin) <τ_0_0><τ_1_0> (@in τ_1_0, @guaranteed <τ_0_0> { var τ_0_0 } <τ_0_0>) -> @out τ_0_0
// CHECK: [[RESULT:%.*]] = apply [[FN]]<T, T>({{.*}}) : $@convention(thin) <τ_0_0><τ_1_0> (@in τ_1_0, @guaranteed <τ_0_0> { var τ_0_0 } <τ_0_0>) -> @out τ_0_0
_ = inner_generic2(u: t)
}
// CHECK-LABEL: sil hidden @_T016generic_closures14outer_concreteySi1i_tF : $@convention(thin) (Int) -> ()
func outer_concrete(i: Int) {
func inner_generic_nocapture<U>(u: U) -> U {
return u
}
func inner_generic<U>(u: U) -> Int {
return i
}
// CHECK: [[FN:%.*]] = function_ref @_T016generic_closures14outer_concreteySi1i_tF06inner_A10_nocaptureL_xx1u_tlF : $@convention(thin) <τ_0_0> (@in τ_0_0) -> @out τ_0_0
// CHECK: [[CLOSURE:%.*]] = partial_apply [callee_guaranteed] [[FN]]<()>() : $@convention(thin) <τ_0_0> (@in τ_0_0) -> @out τ_0_0
// CHECK: [[THUNK:%.*]] = function_ref @_T0ytytIegir_Ieg_TR
// CHECK: [[THUNK_CLOSURE:%.*]] = partial_apply [callee_guaranteed] [[THUNK]]([[CLOSURE]])
// CHECK: destroy_value [[THUNK_CLOSURE]]
let _: () -> () = inner_generic_nocapture
// CHECK: [[FN:%.*]] = function_ref @_T016generic_closures14outer_concreteySi1i_tF06inner_A10_nocaptureL_xx1u_tlF : $@convention(thin) <τ_0_0> (@in τ_0_0) -> @out τ_0_0
// CHECK: [[RESULT:%.*]] = apply [[FN]]<Int>({{.*}}) : $@convention(thin) <τ_0_0> (@in τ_0_0) -> @out τ_0_0
_ = inner_generic_nocapture(u: i)
// CHECK: [[FN:%.*]] = function_ref @_T016generic_closures14outer_concreteySi1i_tF06inner_A0L_Six1u_tlF : $@convention(thin) <τ_0_0> (@in τ_0_0, Int) -> Int
// CHECK: [[CLOSURE:%.*]] = partial_apply [callee_guaranteed] [[FN]]<()>(%0) : $@convention(thin) <τ_0_0> (@in τ_0_0, Int) -> Int
// CHECK: [[THUNK:%.*]] = function_ref @_T0ytSiIegid_SiIegd_TR
// CHECK: [[THUNK_CLOSURE:%.*]] = partial_apply [callee_guaranteed] [[THUNK]]([[CLOSURE]])
// CHECK: destroy_value [[THUNK_CLOSURE]]
let _: () -> Int = inner_generic
// CHECK: [[FN:%.*]] = function_ref @_T016generic_closures14outer_concreteySi1i_tF06inner_A0L_Six1u_tlF : $@convention(thin) <τ_0_0> (@in τ_0_0, Int) -> Int
// CHECK: [[RESULT:%.*]] = apply [[FN]]<Int>({{.*}}) : $@convention(thin) <τ_0_0> (@in τ_0_0, Int) -> Int
_ = inner_generic(u: i)
}
// CHECK-LABEL: sil hidden @_T016generic_closures06mixed_A19_nongeneric_nestingyx1t_tlF : $@convention(thin) <T> (@in T) -> ()
func mixed_generic_nongeneric_nesting<T>(t: T) {
func outer() {
func middle<U>(u: U) {
func inner() -> U {
return u
}
inner()
}
middle(u: 11)
}
outer()
}
// CHECK-LABEL: sil private @_T016generic_closures06mixed_A19_nongeneric_nestingyx1t_tlF5outerL_yylF : $@convention(thin) <T> () -> ()
// CHECK-LABEL: sil private @_T016generic_closures06mixed_A19_nongeneric_nestingyx1t_tlF5outerL_yylF6middleL_yqd__1u_tr__lF : $@convention(thin) <T><U> (@in U) -> ()
// CHECK-LABEL: sil private @_T016generic_closures06mixed_A19_nongeneric_nestingyx1t_tlF5outerL_yylF6middleL_yqd__1u_tr__lF5innerL_qd__yr__lF : $@convention(thin) <T><U> (@guaranteed <τ_0_0><τ_1_0> { var τ_1_0 } <T, U>) -> @out U
protocol Doge {
associatedtype Nose : NoseProtocol
}
protocol NoseProtocol {
associatedtype Squeegee
}
protocol Doggo {}
struct DogSnacks<A : Doggo> {}
func capture_same_type_representative<Daisy: Doge, Roo: Doggo>(slobber: Roo, daisy: Daisy)
where Roo == Daisy.Nose.Squeegee {
var s = DogSnacks<Daisy.Nose.Squeegee>()
_ = { _ = s }
}
| apache-2.0 | ef1665bdd9dac25b49a7e73b11141df0 | 43.143284 | 229 | 0.608331 | 2.867559 | false | false | false | false |
PiXeL16/BudgetShare | BudgetShare/UI/Util/Animations/Shakeable.swift | 1 | 720 | //
// Shakeable.swift
// BudgetShare
//
// Created by Chris Jimenez on 6/21/17.
// Copyright © 2017 Chris Jimenez. All rights reserved.
//
import UIKit
protocol Shakeable {
func shake()
}
extension Shakeable where Self: UIView {
func shake() {
let shakeAnimation = CABasicAnimation(keyPath: "position")
shakeAnimation.duration = 0.1
shakeAnimation.repeatCount = 2
shakeAnimation.autoreverses = false
shakeAnimation.fromValue = NSValue(cgPoint: CGPoint(x: self.center.x - 5.0, y: self.center.y))
shakeAnimation.toValue = NSValue(cgPoint: CGPoint(x: self.center.x + 5.0, y: self.center.y))
layer.add(shakeAnimation, forKey: "position")
}
}
| mit | 9292556b3d2e27bbda122336856675e4 | 26.653846 | 102 | 0.663421 | 3.744792 | false | false | false | false |
VoIPGRID/vialer-ios | Vialer/Extensions/UIColorExtenstions.swift | 1 | 784 | //
// UIColorExtenstions.swift
// Copyright © 2018 VoIPGRID. All rights reserved.
//
import UIKit
extension UIColor {
func isEqualTo(_ color: UIColor) -> Bool {
var originalRed: CGFloat = 0
var originalGreen: CGFloat = 0
var originalBlue: CGFloat = 0
var originalAlpha: CGFloat = 0
getRed(&originalRed, green:&originalGreen, blue:&originalBlue, alpha:&originalAlpha)
var colorRed: CGFloat = 0
var colorGreen: CGFloat = 0
var colorBlue: CGFloat = 0
var colorAlpha: CGFloat = 0
color.getRed(&colorRed, green:&colorGreen, blue:&colorBlue, alpha:&colorAlpha)
return originalRed == colorRed && originalGreen == colorGreen && originalBlue == colorBlue && originalAlpha == colorAlpha
}
}
| gpl-3.0 | e3e8b2233b68155d54cd0e6ee66f8041 | 31.625 | 129 | 0.65645 | 4.255435 | false | false | false | false |
michael-lehew/swift-corelibs-foundation | Foundation/NSString.swift | 1 | 63996 | // 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
public typealias unichar = UInt16
extension unichar : ExpressibleByUnicodeScalarLiteral {
public typealias UnicodeScalarLiteralType = UnicodeScalar
public init(unicodeScalarLiteral scalar: UnicodeScalar) {
self.init(scalar.value)
}
}
#if os(OSX) || os(iOS)
internal let kCFStringEncodingMacRoman = CFStringBuiltInEncodings.macRoman.rawValue
internal let kCFStringEncodingWindowsLatin1 = CFStringBuiltInEncodings.windowsLatin1.rawValue
internal let kCFStringEncodingISOLatin1 = CFStringBuiltInEncodings.isoLatin1.rawValue
internal let kCFStringEncodingNextStepLatin = CFStringBuiltInEncodings.nextStepLatin.rawValue
internal let kCFStringEncodingASCII = CFStringBuiltInEncodings.ASCII.rawValue
internal let kCFStringEncodingUnicode = CFStringBuiltInEncodings.unicode.rawValue
internal let kCFStringEncodingUTF8 = CFStringBuiltInEncodings.UTF8.rawValue
internal let kCFStringEncodingNonLossyASCII = CFStringBuiltInEncodings.nonLossyASCII.rawValue
internal let kCFStringEncodingUTF16 = CFStringBuiltInEncodings.UTF16.rawValue
internal let kCFStringEncodingUTF16BE = CFStringBuiltInEncodings.UTF16BE.rawValue
internal let kCFStringEncodingUTF16LE = CFStringBuiltInEncodings.UTF16LE.rawValue
internal let kCFStringEncodingUTF32 = CFStringBuiltInEncodings.UTF32.rawValue
internal let kCFStringEncodingUTF32BE = CFStringBuiltInEncodings.UTF32BE.rawValue
internal let kCFStringEncodingUTF32LE = CFStringBuiltInEncodings.UTF32LE.rawValue
internal let kCFStringGraphemeCluster = CFStringCharacterClusterType.graphemeCluster
internal let kCFStringComposedCharacterCluster = CFStringCharacterClusterType.composedCharacterCluster
internal let kCFStringCursorMovementCluster = CFStringCharacterClusterType.cursorMovementCluster
internal let kCFStringBackwardDeletionCluster = CFStringCharacterClusterType.backwardDeletionCluster
internal let kCFStringNormalizationFormD = CFStringNormalizationForm.D
internal let kCFStringNormalizationFormKD = CFStringNormalizationForm.KD
internal let kCFStringNormalizationFormC = CFStringNormalizationForm.C
internal let kCFStringNormalizationFormKC = CFStringNormalizationForm.KC
#endif
extension NSString {
public struct EncodingConversionOptions : OptionSet {
public let rawValue : UInt
public init(rawValue: UInt) { self.rawValue = rawValue }
public static let allowLossy = EncodingConversionOptions(rawValue: 1)
public static let externalRepresentation = EncodingConversionOptions(rawValue: 2)
internal static let failOnPartialEncodingConversion = EncodingConversionOptions(rawValue: 1 << 20)
}
public struct EnumerationOptions : OptionSet {
public let rawValue : UInt
public init(rawValue: UInt) { self.rawValue = rawValue }
public static let byLines = EnumerationOptions(rawValue: 0)
public static let byParagraphs = EnumerationOptions(rawValue: 1)
public static let byComposedCharacterSequences = EnumerationOptions(rawValue: 2)
public static let byWords = EnumerationOptions(rawValue: 3)
public static let bySentences = EnumerationOptions(rawValue: 4)
public static let reverse = EnumerationOptions(rawValue: 1 << 8)
public static let substringNotRequired = EnumerationOptions(rawValue: 1 << 9)
public static let localized = EnumerationOptions(rawValue: 1 << 10)
internal static let forceFullTokens = EnumerationOptions(rawValue: 1 << 20)
}
}
extension NSString {
public struct CompareOptions : OptionSet {
public let rawValue : UInt
public init(rawValue: UInt) { self.rawValue = rawValue }
public static let caseInsensitive = CompareOptions(rawValue: 1)
public static let literal = CompareOptions(rawValue: 2)
public static let backwards = CompareOptions(rawValue: 4)
public static let anchored = CompareOptions(rawValue: 8)
public static let numeric = CompareOptions(rawValue: 64)
public static let diacriticInsensitive = CompareOptions(rawValue: 128)
public static let widthInsensitive = CompareOptions(rawValue: 256)
public static let forcedOrdering = CompareOptions(rawValue: 512)
public static let regularExpression = CompareOptions(rawValue: 1024)
internal func _cfValue(_ fixLiteral: Bool = false) -> CFStringCompareFlags {
#if os(OSX) || os(iOS)
return contains(.literal) || !fixLiteral ? CFStringCompareFlags(rawValue: rawValue) : CFStringCompareFlags(rawValue: rawValue).union(.compareNonliteral)
#else
return contains(.literal) || !fixLiteral ? CFStringCompareFlags(rawValue) : CFStringCompareFlags(rawValue) | UInt(kCFCompareNonliteral)
#endif
}
}
}
internal func _createRegexForPattern(_ pattern: String, _ options: NSRegularExpression.Options) -> NSRegularExpression? {
struct local {
static let __NSRegularExpressionCache: NSCache<NSString, NSRegularExpression> = {
let cache = NSCache<NSString, NSRegularExpression>()
cache.name = "NSRegularExpressionCache"
cache.countLimit = 10
return cache
}()
}
let key = "\(options):\(pattern)"
if let regex = local.__NSRegularExpressionCache.object(forKey: key._nsObject) {
return regex
}
do {
let regex = try NSRegularExpression(pattern: pattern, options: options)
local.__NSRegularExpressionCache.setObject(regex, forKey: key._nsObject)
return regex
} catch {
}
return nil
}
internal func _bytesInEncoding(_ str: NSString, _ encoding: String.Encoding, _ fatalOnError: Bool, _ externalRep: Bool, _ lossy: Bool) -> UnsafePointer<Int8>? {
let theRange = NSMakeRange(0, str.length)
var cLength = 0
var used = 0
var options: NSString.EncodingConversionOptions = []
if externalRep {
options.formUnion(.externalRepresentation)
}
if lossy {
options.formUnion(.allowLossy)
}
if !str.getBytes(nil, maxLength: Int.max - 1, usedLength: &cLength, encoding: encoding.rawValue, options: options, range: theRange, remaining: nil) {
if fatalOnError {
fatalError("Conversion on encoding failed")
}
return nil
}
let buffer = malloc(cLength + 1)!.bindMemory(to: Int8.self, capacity: cLength + 1)
if !str.getBytes(buffer, maxLength: cLength, usedLength: &used, encoding: encoding.rawValue, options: options, range: theRange, remaining: nil) {
fatalError("Internal inconsistency; previously claimed getBytes returned success but failed with similar invocation")
}
buffer.advanced(by: cLength).initialize(to: 0)
return UnsafePointer(buffer) // leaked and should be autoreleased via a NSData backing but we cannot here
}
internal func isALineSeparatorTypeCharacter(_ ch: unichar) -> Bool {
if ch > 0x0d && ch < 0x0085 { /* Quick test to cover most chars */
return false
}
return ch == 0x0a || ch == 0x0d || ch == 0x0085 || ch == 0x2028 || ch == 0x2029
}
internal func isAParagraphSeparatorTypeCharacter(_ ch: unichar) -> Bool {
if ch > 0x0d && ch < 0x2029 { /* Quick test to cover most chars */
return false
}
return ch == 0x0a || ch == 0x0d || ch == 0x2029
}
open class NSString : NSObject, NSCopying, NSMutableCopying, NSSecureCoding, NSCoding {
private let _cfinfo = _CFInfo(typeID: CFStringGetTypeID())
internal var _storage: String
open var length: Int {
guard type(of: self) === NSString.self || type(of: self) === NSMutableString.self else {
NSRequiresConcreteImplementation()
}
return _storage.utf16.count
}
open func character(at index: Int) -> unichar {
guard type(of: self) === NSString.self || type(of: self) === NSMutableString.self else {
NSRequiresConcreteImplementation()
}
let start = _storage.utf16.startIndex
return _storage.utf16[start.advanced(by: index)]
}
public override convenience init() {
let characters = Array<unichar>(repeating: 0, count: 1)
self.init(characters: characters, length: 0)
}
internal init(_ string: String) {
_storage = string
}
public convenience required init?(coder aDecoder: NSCoder) {
guard aDecoder.allowsKeyedCoding else {
preconditionFailure("Unkeyed coding is unsupported.")
}
if type(of: aDecoder) == NSKeyedUnarchiver.self || aDecoder.containsValue(forKey: "NS.string") {
let str = aDecoder._decodePropertyListForKey("NS.string") as! String
self.init(string: str)
} else {
let decodedData : Data? = aDecoder.withDecodedUnsafeBufferPointer(forKey: "NS.bytes") {
guard let buffer = $0 else { return nil }
return Data(buffer: buffer)
}
guard let data = decodedData else { return nil }
self.init(data: data, encoding: String.Encoding.utf8.rawValue)
}
}
public required convenience init(string aString: String) {
self.init(aString)
}
open override func copy() -> Any {
return copy(with: nil)
}
open func copy(with zone: NSZone? = nil) -> Any {
return self
}
open override func mutableCopy() -> Any {
return mutableCopy(with: nil)
}
open func mutableCopy(with zone: NSZone? = nil) -> Any {
if type(of: self) === NSString.self || type(of: self) === NSMutableString.self {
if let contents = _fastContents {
return NSMutableString(characters: contents, length: length)
}
}
let characters = UnsafeMutablePointer<unichar>.allocate(capacity: length)
getCharacters(characters, range: NSMakeRange(0, length))
let result = NSMutableString(characters: characters, length: length)
characters.deinitialize()
characters.deallocate(capacity: length)
return result
}
public static var supportsSecureCoding: Bool {
return true
}
open func encode(with aCoder: NSCoder) {
if let aKeyedCoder = aCoder as? NSKeyedArchiver {
aKeyedCoder._encodePropertyList(self, forKey: "NS.string")
} else {
aCoder.encode(self)
}
}
public init(characters: UnsafePointer<unichar>, length: Int) {
_storage = String._fromWellFormedCodeUnitSequence(UTF16.self, input: UnsafeBufferPointer(start: characters, count: length))
}
public required convenience init(unicodeScalarLiteral value: StaticString) {
self.init(stringLiteral: value)
}
public required convenience init(extendedGraphemeClusterLiteral value: StaticString) {
self.init(stringLiteral: value)
}
public required init(stringLiteral value: StaticString) {
_storage = String(describing: value)
}
public convenience init?(cString nullTerminatedCString: UnsafePointer<Int8>, encoding: UInt) {
self.init(string: CFStringCreateWithCString(kCFAllocatorSystemDefault, nullTerminatedCString, CFStringConvertNSStringEncodingToEncoding(encoding))._swiftObject)
}
internal var _fastCStringContents: UnsafePointer<Int8>? {
if type(of: self) == NSString.self || type(of: self) == NSMutableString.self {
if _storage._core.isASCII {
return unsafeBitCast(_storage._core.startASCII, to: UnsafePointer<Int8>.self)
}
}
return nil
}
internal var _fastContents: UnsafePointer<UniChar>? {
if type(of: self) == NSString.self || type(of: self) == NSMutableString.self {
if !_storage._core.isASCII {
return unsafeBitCast(_storage._core.startUTF16, to: UnsafePointer<UniChar>.self)
}
}
return nil
}
internal var _encodingCantBeStoredInEightBitCFString: Bool {
if type(of: self) == NSString.self || type(of: self) == NSMutableString.self {
return !_storage._core.isASCII
}
return false
}
override open var _cfTypeID: CFTypeID {
return CFStringGetTypeID()
}
open override func isEqual(_ object: Any?) -> Bool {
guard let string = (object as? NSString)?._swiftObject else { return false }
return self.isEqual(to: string)
}
open override var description: String {
return _swiftObject
}
open override var hash: Int {
return Int(bitPattern:CFStringHashNSString(self._cfObject))
}
}
extension NSString {
public func getCharacters(_ buffer: UnsafeMutablePointer<unichar>, range: NSRange) {
for idx in 0..<range.length {
buffer[idx] = character(at: idx + range.location)
}
}
public func substring(from: Int) -> String {
if type(of: self) == NSString.self || type(of: self) == NSMutableString.self {
return String(_storage.utf16.suffix(from: _storage.utf16.startIndex.advanced(by: from)))!
} else {
return substring(with: NSMakeRange(from, length - from))
}
}
public func substring(to: Int) -> String {
if type(of: self) == NSString.self || type(of: self) == NSMutableString.self {
return String(_storage.utf16.prefix(upTo: _storage.utf16.startIndex
.advanced(by: to)))!
} else {
return substring(with: NSMakeRange(0, to))
}
}
public func substring(with range: NSRange) -> String {
if type(of: self) == NSString.self || type(of: self) == NSMutableString.self {
let start = _storage.utf16.startIndex
let min = start.advanced(by: range.location)
let max = start.advanced(by: range.location + range.length)
return String(_storage.utf16[min..<max])!
} else {
let buff = UnsafeMutablePointer<unichar>.allocate(capacity: range.length)
getCharacters(buff, range: range)
let result = String(describing: buff)
buff.deinitialize()
buff.deallocate(capacity: range.length)
return result
}
}
public func compare(_ string: String) -> ComparisonResult {
return compare(string, options: [], range: NSMakeRange(0, length))
}
public func compare(_ string: String, options mask: CompareOptions) -> ComparisonResult {
return compare(string, options: mask, range: NSMakeRange(0, length))
}
public func compare(_ string: String, options mask: CompareOptions, range compareRange: NSRange) -> ComparisonResult {
return compare(string, options: mask, range: compareRange, locale: nil)
}
public func compare(_ string: String, options mask: CompareOptions, range compareRange: NSRange, locale: AnyObject?) -> ComparisonResult {
var res: CFComparisonResult
if let loc = locale {
res = CFStringCompareWithOptionsAndLocale(_cfObject, string._cfObject, CFRange(compareRange), mask._cfValue(true), (loc as! NSLocale)._cfObject)
} else {
res = CFStringCompareWithOptionsAndLocale(_cfObject, string._cfObject, CFRange(compareRange), mask._cfValue(true), nil)
}
return ComparisonResult._fromCF(res)
}
public func caseInsensitiveCompare(_ string: String) -> ComparisonResult {
return compare(string, options: .caseInsensitive, range: NSMakeRange(0, length))
}
public func localizedCompare(_ string: String) -> ComparisonResult {
return compare(string, options: [], range: NSMakeRange(0, length), locale: Locale.current._bridgeToObjectiveC())
}
public func localizedCaseInsensitiveCompare(_ string: String) -> ComparisonResult {
return compare(string, options: .caseInsensitive, range: NSMakeRange(0, length), locale: Locale.current._bridgeToObjectiveC())
}
public func localizedStandardCompare(_ string: String) -> ComparisonResult {
return compare(string, options: [.caseInsensitive, .numeric, .widthInsensitive, .forcedOrdering], range: NSMakeRange(0, length), locale: Locale.current._bridgeToObjectiveC())
}
public func isEqual(to aString: String) -> Bool {
if type(of: self) == NSString.self || type(of: self) == NSMutableString.self {
return _storage == aString
} else {
return length == aString.length && compare(aString, options: .literal, range: NSMakeRange(0, length)) == .orderedSame
}
}
public func hasPrefix(_ str: String) -> Bool {
return range(of: str, options: .anchored, range: NSMakeRange(0, length)).location != NSNotFound
}
public func hasSuffix(_ str: String) -> Bool {
return range(of: str, options: [.anchored, .backwards], range: NSMakeRange(0, length)).location != NSNotFound
}
public func commonPrefix(with str: String, options mask: CompareOptions = []) -> String {
var currentSubstring: CFMutableString?
let isLiteral = mask.contains(.literal)
var lastMatch = NSRange()
let selfLen = length
let otherLen = str.length
var low = 0
var high = selfLen
var probe = (low + high) / 2
if (probe > otherLen) {
probe = otherLen // A little heuristic to avoid some extra work
}
if selfLen == 0 || otherLen == 0 {
return ""
}
var numCharsBuffered = 0
var arrayBuffer = [unichar](repeating: 0, count: 100)
let other = str._nsObject
return arrayBuffer.withUnsafeMutablePointerOrAllocation(selfLen, fastpath: UnsafeMutablePointer<unichar>(mutating: _fastContents)) { (selfChars: UnsafeMutablePointer<unichar>) -> String in
// Now do the binary search. Note that the probe value determines the length of the substring to check.
while true {
let range = NSMakeRange(0, isLiteral ? probe + 1 : NSMaxRange(rangeOfComposedCharacterSequence(at: probe))) // Extend the end of the composed char sequence
if range.length > numCharsBuffered { // Buffer more characters if needed
getCharacters(selfChars, range: NSMakeRange(numCharsBuffered, range.length - numCharsBuffered))
numCharsBuffered = range.length
}
if currentSubstring == nil {
currentSubstring = CFStringCreateMutableWithExternalCharactersNoCopy(kCFAllocatorSystemDefault, selfChars, range.length, range.length, kCFAllocatorNull)
} else {
CFStringSetExternalCharactersNoCopy(currentSubstring, selfChars, range.length, range.length)
}
if other.range(of: currentSubstring!._swiftObject, options: mask.union(.anchored), range: NSMakeRange(0, otherLen)).length != 0 { // Match
lastMatch = range
low = probe + 1
} else {
high = probe
}
if low >= high {
break
}
probe = (low + high) / 2
}
return lastMatch.length != 0 ? substring(with: lastMatch) : ""
}
}
public func contains(_ str: String) -> Bool {
return range(of: str, options: [], range: NSMakeRange(0, length), locale: nil).location != NSNotFound
}
public func localizedCaseInsensitiveContains(_ str: String) -> Bool {
return range(of: str, options: .caseInsensitive, range: NSMakeRange(0, length), locale: Locale.current).location != NSNotFound
}
public func localizedStandardContains(_ str: String) -> Bool {
return range(of: str, options: [.caseInsensitive, .diacriticInsensitive], range: NSMakeRange(0, length), locale: Locale.current).location != NSNotFound
}
public func localizedStandardRange(of str: String) -> NSRange {
return range(of: str, options: [.caseInsensitive, .diacriticInsensitive], range: NSMakeRange(0, length), locale: Locale.current)
}
public func range(of searchString: String) -> NSRange {
return range(of: searchString, options: [], range: NSMakeRange(0, length), locale: nil)
}
public func range(of searchString: String, options mask: CompareOptions = []) -> NSRange {
return range(of: searchString, options: mask, range: NSMakeRange(0, length), locale: nil)
}
public func range(of searchString: String, options mask: CompareOptions = [], range searchRange: NSRange) -> NSRange {
return range(of: searchString, options: mask, range: searchRange, locale: nil)
}
internal func _rangeOfRegularExpressionPattern(regex pattern: String, options mask: CompareOptions, range searchRange: NSRange, locale: Locale?) -> NSRange {
var matchedRange = NSMakeRange(NSNotFound, 0)
let regexOptions: NSRegularExpression.Options = mask.contains(.caseInsensitive) ? .caseInsensitive : []
let matchingOptions: NSMatchingOptions = mask.contains(.anchored) ? .anchored : []
if let regex = _createRegexForPattern(pattern, regexOptions) {
matchedRange = regex.rangeOfFirstMatch(in: _swiftObject, options: matchingOptions, range: searchRange)
}
return matchedRange
}
public func range(of searchString: String, options mask: CompareOptions = [], range searchRange: NSRange, locale: Locale?) -> NSRange {
let findStrLen = searchString.length
let len = length
precondition(searchRange.length <= len && searchRange.location <= len - searchRange.length, "Bounds Range {\(searchRange.location), \(searchRange.length)} out of bounds; string length \(len)")
if mask.contains(.regularExpression) {
return _rangeOfRegularExpressionPattern(regex: searchString, options: mask, range:searchRange, locale: locale)
}
if searchRange.length == 0 || findStrLen == 0 { // ??? This last item can't be here for correct Unicode compares
return NSMakeRange(NSNotFound, 0)
}
var result = CFRange()
let res = withUnsafeMutablePointer(to: &result) { (rangep: UnsafeMutablePointer<CFRange>) -> Bool in
if let loc = locale {
return CFStringFindWithOptionsAndLocale(_cfObject, searchString._cfObject, CFRange(searchRange), mask._cfValue(true), loc._cfObject, rangep)
} else {
return CFStringFindWithOptionsAndLocale(_cfObject, searchString._cfObject, CFRange(searchRange), mask._cfValue(true), nil, rangep)
}
}
if res {
return NSMakeRange(result.location, result.length)
} else {
return NSMakeRange(NSNotFound, 0)
}
}
public func rangeOfCharacter(from searchSet: CharacterSet) -> NSRange {
return rangeOfCharacter(from: searchSet, options: [], range: NSMakeRange(0, length))
}
public func rangeOfCharacter(from searchSet: CharacterSet, options mask: CompareOptions = []) -> NSRange {
return rangeOfCharacter(from: searchSet, options: mask, range: NSMakeRange(0, length))
}
public func rangeOfCharacter(from searchSet: CharacterSet, options mask: CompareOptions = [], range searchRange: NSRange) -> NSRange {
let len = length
precondition(searchRange.length <= len && searchRange.location <= len - searchRange.length, "Bounds Range {\(searchRange.location), \(searchRange.length)} out of bounds; string length \(len)")
var result = CFRange()
let res = withUnsafeMutablePointer(to: &result) { (rangep: UnsafeMutablePointer<CFRange>) -> Bool in
return CFStringFindCharacterFromSet(_cfObject, searchSet._cfObject, CFRange(searchRange), mask._cfValue(), rangep)
}
if res {
return NSMakeRange(result.location, result.length)
} else {
return NSMakeRange(NSNotFound, 0)
}
}
public func rangeOfComposedCharacterSequence(at index: Int) -> NSRange {
let range = CFStringGetRangeOfCharacterClusterAtIndex(_cfObject, index, kCFStringComposedCharacterCluster)
return NSMakeRange(range.location, range.length)
}
public func rangeOfComposedCharacterSequences(for range: NSRange) -> NSRange {
let length = self.length
var start: Int
var end: Int
if range.location == length {
start = length
} else {
start = rangeOfComposedCharacterSequence(at: range.location).location
}
var endOfRange = NSMaxRange(range)
if endOfRange == length {
end = length
} else {
if range.length > 0 {
endOfRange = endOfRange - 1 // We want 0-length range to be treated same as 1-length range.
}
end = NSMaxRange(rangeOfComposedCharacterSequence(at: endOfRange))
}
return NSMakeRange(start, end - start)
}
public func appending(_ aString: String) -> String {
return _swiftObject + aString
}
public var doubleValue: Double {
var start: Int = 0
var result = 0.0
let _ = _swiftObject.scan(CharacterSet.whitespaces, locale: nil, locationToScanFrom: &start) { (value: Double) -> Void in
result = value
}
return result
}
public var floatValue: Float {
var start: Int = 0
var result: Float = 0.0
let _ = _swiftObject.scan(CharacterSet.whitespaces, locale: nil, locationToScanFrom: &start) { (value: Float) -> Void in
result = value
}
return result
}
public var intValue: Int32 {
return Scanner(string: _swiftObject).scanInt() ?? 0
}
public var integerValue: Int {
let scanner = Scanner(string: _swiftObject)
var value: Int = 0
let _ = scanner.scanInteger(&value)
return value
}
public var longLongValue: Int64 {
return Scanner(string: _swiftObject).scanLongLong() ?? 0
}
public var boolValue: Bool {
let scanner = Scanner(string: _swiftObject)
// skip initial whitespace if present
let _ = scanner.scanCharactersFromSet(.whitespaces)
// scan a single optional '+' or '-' character, followed by zeroes
if scanner.scanString(string: "+") == nil {
let _ = scanner.scanString(string: "-")
}
// scan any following zeroes
let _ = scanner.scanCharactersFromSet(CharacterSet(charactersIn: "0"))
return scanner.scanCharactersFromSet(CharacterSet(charactersIn: "tTyY123456789")) != nil
}
public var uppercased: String {
return uppercased(with: nil)
}
public var lowercased: String {
return lowercased(with: nil)
}
public var capitalized: String {
return capitalized(with: nil)
}
public var localizedUppercase: String {
return uppercased(with: Locale.current)
}
public var localizedLowercase: String {
return lowercased(with: Locale.current)
}
public var localizedCapitalized: String {
return capitalized(with: Locale.current)
}
public func uppercased(with locale: Locale?) -> String {
let mutableCopy = CFStringCreateMutableCopy(kCFAllocatorSystemDefault, 0, self._cfObject)!
CFStringUppercase(mutableCopy, locale?._cfObject ?? nil)
return mutableCopy._swiftObject
}
public func lowercased(with locale: Locale?) -> String {
let mutableCopy = CFStringCreateMutableCopy(kCFAllocatorSystemDefault, 0, self._cfObject)!
CFStringLowercase(mutableCopy, locale?._cfObject ?? nil)
return mutableCopy._swiftObject
}
public func capitalized(with locale: Locale?) -> String {
let mutableCopy = CFStringCreateMutableCopy(kCFAllocatorSystemDefault, 0, self._cfObject)!
CFStringCapitalize(mutableCopy, locale?._cfObject ?? nil)
return mutableCopy._swiftObject
}
internal func _getBlockStart(_ startPtr: UnsafeMutablePointer<Int>?, end endPtr: UnsafeMutablePointer<Int>?, contentsEnd contentsEndPtr: UnsafeMutablePointer<Int>?, forRange range: NSRange, stopAtLineSeparators line: Bool) {
let len = length
var ch: unichar
precondition(range.length <= len && range.location < len - range.length, "Range {\(range.location), \(range.length)} is out of bounds of length \(len)")
if range.location == 0 && range.length == len && contentsEndPtr == nil { // This occurs often
startPtr?.pointee = 0
endPtr?.pointee = range.length
return
}
/* Find the starting point first */
if startPtr != nil {
var start: Int = 0
if range.location == 0 {
start = 0
} else {
var buf = _NSStringBuffer(string: self, start: range.location, end: len)
/* Take care of the special case where start happens to fall right between \r and \n */
ch = buf.currentCharacter
buf.rewind()
if ch == 0x0a && buf.currentCharacter == 0x0d {
buf.rewind()
}
while true {
if line ? isALineSeparatorTypeCharacter(buf.currentCharacter) : isAParagraphSeparatorTypeCharacter(buf.currentCharacter) {
start = buf.location + 1
break
} else if buf.location <= 0 {
start = 0
break
} else {
buf.rewind()
}
}
startPtr!.pointee = start
}
}
if (endPtr != nil || contentsEndPtr != nil) {
var endOfContents = 1
var lineSeparatorLength = 1
var buf = _NSStringBuffer(string: self, start: NSMaxRange(range) - (range.length > 0 ? 1 : 0), end: len)
/* First look at the last char in the range (if the range is zero length, the char after the range) to see if we're already on or within a end of line sequence... */
ch = buf.currentCharacter
if ch == 0x0a {
endOfContents = buf.location
buf.rewind()
if buf.currentCharacter == 0x0d {
lineSeparatorLength = 2
endOfContents -= 1
}
} else {
while true {
if line ? isALineSeparatorTypeCharacter(ch) : isAParagraphSeparatorTypeCharacter(ch) {
endOfContents = buf.location /* This is actually end of contentsRange */
buf.advance() /* OK for this to go past the end */
if ch == 0x0d && buf.currentCharacter == 0x0a {
lineSeparatorLength = 2
}
break
} else if buf.location == len {
endOfContents = len
lineSeparatorLength = 0
break
} else {
buf.advance()
ch = buf.currentCharacter
}
}
}
contentsEndPtr?.pointee = endOfContents
endPtr?.pointee = endOfContents + lineSeparatorLength
}
}
public func getLineStart(_ startPtr: UnsafeMutablePointer<Int>?, end lineEndPtr: UnsafeMutablePointer<Int>?, contentsEnd contentsEndPtr: UnsafeMutablePointer<Int>?, for range: NSRange) {
_getBlockStart(startPtr, end: lineEndPtr, contentsEnd: contentsEndPtr, forRange: range, stopAtLineSeparators: true)
}
public func lineRange(for range: NSRange) -> NSRange {
var start = 0
var lineEnd = 0
getLineStart(&start, end: &lineEnd, contentsEnd: nil, for: range)
return NSMakeRange(start, lineEnd - start)
}
public func getParagraphStart(_ startPtr: UnsafeMutablePointer<Int>?, end parEndPtr: UnsafeMutablePointer<Int>?, contentsEnd contentsEndPtr: UnsafeMutablePointer<Int>?, for range: NSRange) {
_getBlockStart(startPtr, end: parEndPtr, contentsEnd: contentsEndPtr, forRange: range, stopAtLineSeparators: false)
}
public func paragraphRange(for range: NSRange) -> NSRange {
var start = 0
var parEnd = 0
getParagraphStart(&start, end: &parEnd, contentsEnd: nil, for: range)
return NSMakeRange(start, parEnd - start)
}
public func enumerateSubstrings(in range: NSRange, options opts: EnumerationOptions = [], using block: (String?, NSRange, NSRange, UnsafeMutablePointer<ObjCBool>) -> Void) {
NSUnimplemented()
}
public func enumerateLines(_ block: (String, UnsafeMutablePointer<ObjCBool>) -> Void) {
enumerateSubstrings(in: NSMakeRange(0, length), options:.byLines) { substr, substrRange, enclosingRange, stop in
block(substr!, stop)
}
}
public var utf8String: UnsafePointer<Int8>? {
return _bytesInEncoding(self, String.Encoding.utf8, false, false, false)
}
public var fastestEncoding: UInt {
return String.Encoding.unicode.rawValue
}
public var smallestEncoding: UInt {
if canBeConverted(to: String.Encoding.ascii.rawValue) {
return String.Encoding.ascii.rawValue
}
return String.Encoding.unicode.rawValue
}
public func data(using encoding: UInt, allowLossyConversion lossy: Bool = false) -> Data? {
let len = length
var reqSize = 0
let cfStringEncoding = CFStringConvertNSStringEncodingToEncoding(encoding)
if !CFStringIsEncodingAvailable(cfStringEncoding) {
return nil
}
let convertedLen = __CFStringEncodeByteStream(_cfObject, 0, len, true, cfStringEncoding, lossy ? (encoding == String.Encoding.ascii.rawValue ? 0xFF : 0x3F) : 0, nil, 0, &reqSize)
if convertedLen != len {
return nil // Not able to do it all...
}
if 0 < reqSize {
var data = Data(count: reqSize)
data.count = data.withUnsafeMutableBytes { (mutableBytes: UnsafeMutablePointer<UInt8>) -> Int in
if __CFStringEncodeByteStream(_cfObject, 0, len, true, cfStringEncoding, lossy ? (encoding == String.Encoding.ascii.rawValue ? 0xFF : 0x3F) : 0, UnsafeMutablePointer<UInt8>(mutableBytes), reqSize, &reqSize) == convertedLen {
return reqSize
} else {
fatalError("didn't convert all characters")
}
}
return data
}
return Data()
}
public func data(using encoding: UInt) -> Data? {
return data(using: encoding, allowLossyConversion: false)
}
public func canBeConverted(to encoding: UInt) -> Bool {
if encoding == String.Encoding.unicode.rawValue || encoding == String.Encoding.nonLossyASCII.rawValue || encoding == String.Encoding.utf8.rawValue {
return true
}
return __CFStringEncodeByteStream(_cfObject, 0, length, false, CFStringConvertNSStringEncodingToEncoding(encoding), 0, nil, 0, nil) == length
}
public func cString(using encoding: UInt) -> UnsafePointer<Int8>? {
return _bytesInEncoding(self, String.Encoding(rawValue: encoding), false, false, false)
}
public func getCString(_ buffer: UnsafeMutablePointer<Int8>, maxLength maxBufferCount: Int, encoding: UInt) -> Bool {
var used = 0
if type(of: self) == NSString.self || type(of: self) == NSMutableString.self {
if _storage._core.isASCII {
used = min(self.length, maxBufferCount - 1)
buffer.moveAssign(from: unsafeBitCast(_storage._core.startASCII, to: UnsafeMutablePointer<Int8>.self)
, count: used)
buffer.advanced(by: used).initialize(to: 0)
return true
}
}
if getBytes(UnsafeMutableRawPointer(buffer), maxLength: maxBufferCount, usedLength: &used, encoding: encoding, options: [], range: NSMakeRange(0, self.length), remaining: nil) {
buffer.advanced(by: used).initialize(to: 0)
return true
}
return false
}
public func getBytes(_ buffer: UnsafeMutableRawPointer?, maxLength maxBufferCount: Int, usedLength usedBufferCount: UnsafeMutablePointer<Int>?, encoding: UInt, options: EncodingConversionOptions = [], range: NSRange, remaining leftover: NSRangePointer?) -> Bool {
var totalBytesWritten = 0
var numCharsProcessed = 0
let cfStringEncoding = CFStringConvertNSStringEncodingToEncoding(encoding)
var result = true
if length > 0 {
if CFStringIsEncodingAvailable(cfStringEncoding) {
let lossyOk = options.contains(.allowLossy)
let externalRep = options.contains(.externalRepresentation)
let failOnPartial = options.contains(.failOnPartialEncodingConversion)
let bytePtr = buffer?.bindMemory(to: UInt8.self, capacity: maxBufferCount)
numCharsProcessed = __CFStringEncodeByteStream(_cfObject, range.location, range.length, externalRep, cfStringEncoding, lossyOk ? (encoding == String.Encoding.ascii.rawValue ? 0xFF : 0x3F) : 0, bytePtr, bytePtr != nil ? maxBufferCount : 0, &totalBytesWritten)
if (failOnPartial && numCharsProcessed < range.length) || numCharsProcessed == 0 {
result = false
}
} else {
result = false /* ??? Need other encodings */
}
}
usedBufferCount?.pointee = totalBytesWritten
leftover?.pointee = NSMakeRange(range.location + numCharsProcessed, range.length - numCharsProcessed)
return result
}
public func maximumLengthOfBytes(using enc: UInt) -> Int {
let cfEnc = CFStringConvertNSStringEncodingToEncoding(enc)
let result = CFStringGetMaximumSizeForEncoding(length, cfEnc)
return result == kCFNotFound ? 0 : result
}
public func lengthOfBytes(using enc: UInt) -> Int {
let len = length
var numBytes: CFIndex = 0
let cfEnc = CFStringConvertNSStringEncodingToEncoding(enc)
let convertedLen = __CFStringEncodeByteStream(_cfObject, 0, len, false, cfEnc, 0, nil, 0, &numBytes)
return convertedLen != len ? 0 : numBytes
}
open class var availableStringEncodings: UnsafePointer<UInt> {
struct once {
static let encodings: UnsafePointer<UInt> = {
let cfEncodings = CFStringGetListOfAvailableEncodings()!
var idx = 0
var numEncodings = 0
while cfEncodings.advanced(by: idx).pointee != kCFStringEncodingInvalidId {
idx += 1
numEncodings += 1
}
let theEncodingList = UnsafeMutablePointer<String.Encoding.RawValue>.allocate(capacity: numEncodings + 1)
theEncodingList.advanced(by: numEncodings).pointee = 0 // Terminator
numEncodings -= 1
while numEncodings >= 0 {
theEncodingList.advanced(by: numEncodings).pointee = CFStringConvertEncodingToNSStringEncoding(cfEncodings.advanced(by: numEncodings).pointee)
numEncodings -= 1
}
return UnsafePointer<UInt>(theEncodingList)
}()
}
return once.encodings
}
open class func localizedName(of encoding: UInt) -> String {
if let theString = CFStringGetNameOfEncoding(CFStringConvertNSStringEncodingToEncoding(encoding)) {
// TODO: read the localized version from the Foundation "bundle"
return theString._swiftObject
}
return ""
}
open class var defaultCStringEncoding: UInt {
return CFStringConvertEncodingToNSStringEncoding(CFStringGetSystemEncoding())
}
open var decomposedStringWithCanonicalMapping: String {
let string = CFStringCreateMutable(kCFAllocatorSystemDefault, 0)!
CFStringReplaceAll(string, self._cfObject)
CFStringNormalize(string, kCFStringNormalizationFormD)
return string._swiftObject
}
open var precomposedStringWithCanonicalMapping: String {
let string = CFStringCreateMutable(kCFAllocatorSystemDefault, 0)!
CFStringReplaceAll(string, self._cfObject)
CFStringNormalize(string, kCFStringNormalizationFormC)
return string._swiftObject
}
open var decomposedStringWithCompatibilityMapping: String {
let string = CFStringCreateMutable(kCFAllocatorSystemDefault, 0)!
CFStringReplaceAll(string, self._cfObject)
CFStringNormalize(string, kCFStringNormalizationFormKD)
return string._swiftObject
}
open var precomposedStringWithCompatibilityMapping: String {
let string = CFStringCreateMutable(kCFAllocatorSystemDefault, 0)!
CFStringReplaceAll(string, self._cfObject)
CFStringNormalize(string, kCFStringNormalizationFormKC)
return string._swiftObject
}
open func components(separatedBy separator: String) -> [String] {
let len = length
var lrange = range(of: separator, options: [], range: NSMakeRange(0, len))
if lrange.length == 0 {
return [_swiftObject]
} else {
var array = [String]()
var srange = NSMakeRange(0, len)
while true {
let trange = NSMakeRange(srange.location, lrange.location - srange.location)
array.append(substring(with: trange))
srange.location = lrange.location + lrange.length
srange.length = len - srange.location
lrange = range(of: separator, options: [], range: srange)
if lrange.length == 0 {
break
}
}
array.append(substring(with: srange))
return array
}
}
open func components(separatedBy separator: CharacterSet) -> [String] {
let len = length
var range = rangeOfCharacter(from: separator, options: [], range: NSMakeRange(0, len))
if range.length == 0 {
return [_swiftObject]
} else {
var array = [String]()
var srange = NSMakeRange(0, len)
while true {
let trange = NSMakeRange(srange.location, range.location - srange.location)
array.append(substring(with: trange))
srange.location = range.location + range.length
srange.length = len - srange.location
range = rangeOfCharacter(from: separator, options: [], range: srange)
if range.length == 0 {
break
}
}
array.append(substring(with: srange))
return array
}
}
open func trimmingCharacters(in set: CharacterSet) -> String {
let len = length
var buf = _NSStringBuffer(string: self, start: 0, end: len)
while !buf.isAtEnd,
let character = UnicodeScalar(buf.currentCharacter),
set.contains(character) {
buf.advance()
}
let startOfNonTrimmedRange = buf.location // This points at the first char not in the set
if startOfNonTrimmedRange == len { // Note that this also covers the len == 0 case, which is important to do here before the len-1 in the next line.
return ""
} else if startOfNonTrimmedRange < len - 1 {
buf.location = len - 1
while let character = UnicodeScalar(buf.currentCharacter),
set.contains(character),
buf.location >= startOfNonTrimmedRange {
buf.rewind()
}
let endOfNonTrimmedRange = buf.location
return substring(with: NSMakeRange(startOfNonTrimmedRange, endOfNonTrimmedRange + 1 - startOfNonTrimmedRange))
} else {
return substring(with: NSMakeRange(startOfNonTrimmedRange, 1))
}
}
open func padding(toLength newLength: Int, withPad padString: String, startingAt padIndex: Int) -> String {
let len = length
if newLength <= len { // The simple cases (truncation)
return newLength == len ? _swiftObject : substring(with: NSMakeRange(0, newLength))
}
let padLen = padString.length
if padLen < 1 {
fatalError("empty pad string")
}
if padIndex >= padLen {
fatalError("out of range padIndex")
}
let mStr = CFStringCreateMutableCopy(kCFAllocatorSystemDefault, 0, _cfObject)!
CFStringPad(mStr, padString._cfObject, newLength, padIndex)
return mStr._swiftObject
}
open func folding(options: CompareOptions = [], locale: Locale?) -> String {
let string = CFStringCreateMutable(kCFAllocatorSystemDefault, 0)!
CFStringReplaceAll(string, self._cfObject)
CFStringFold(string, options._cfValue(), locale?._cfObject)
return string._swiftObject
}
internal func _stringByReplacingOccurrencesOfRegularExpressionPattern(_ pattern: String, withTemplate replacement: String, options: CompareOptions, range: NSRange) -> String {
let regexOptions: NSRegularExpression.Options = options.contains(.caseInsensitive) ? .caseInsensitive : []
let matchingOptions: NSMatchingOptions = options.contains(.anchored) ? .anchored : []
if let regex = _createRegexForPattern(pattern, regexOptions) {
return regex.stringByReplacingMatches(in: _swiftObject, options: matchingOptions, range: range, withTemplate: replacement)
}
return ""
}
open func replacingOccurrences(of target: String, with replacement: String, options: CompareOptions = [], range searchRange: NSRange) -> String {
if options.contains(.regularExpression) {
return _stringByReplacingOccurrencesOfRegularExpressionPattern(target, withTemplate: replacement, options: options, range: searchRange)
}
let str = mutableCopy(with: nil) as! NSMutableString
if str.replaceOccurrences(of: target, with: replacement, options: options, range: searchRange) == 0 {
return _swiftObject
} else {
return str._swiftObject
}
}
open func replacingOccurrences(of target: String, with replacement: String) -> String {
return replacingOccurrences(of: target, with: replacement, options: [], range: NSMakeRange(0, length))
}
open func replacingCharacters(in range: NSRange, with replacement: String) -> String {
let str = mutableCopy(with: nil) as! NSMutableString
str.replaceCharacters(in: range, with: replacement)
return str._swiftObject
}
open func applyingTransform(_ transform: String, reverse: Bool) -> String? {
let string = CFStringCreateMutable(kCFAllocatorSystemDefault, 0)!
CFStringReplaceAll(string, _cfObject)
if (CFStringTransform(string, nil, transform._cfObject, reverse)) {
return string._swiftObject
} else {
return nil
}
}
internal func _getExternalRepresentation(_ data: inout Data, _ dest: URL, _ enc: UInt) throws {
let length = self.length
var numBytes = 0
let theRange = NSMakeRange(0, length)
if !getBytes(nil, maxLength: Int.max - 1, usedLength: &numBytes, encoding: enc, options: [], range: theRange, remaining: nil) {
throw NSError(domain: NSCocoaErrorDomain, code: CocoaError.fileWriteInapplicableStringEncoding.rawValue, userInfo: [
NSURLErrorKey: dest,
])
}
var mData = Data(count: numBytes)
// The getBytes:... call should hopefully not fail, given it succeeded above, but check anyway (mutable string changing behind our back?)
var used = 0
// This binds mData memory to UInt8 because Data.withUnsafeMutableBytes does not handle raw pointers.
try mData.withUnsafeMutableBytes { (mutableBytes: UnsafeMutablePointer<UInt8>) -> Void in
if !getBytes(mutableBytes, maxLength: numBytes, usedLength: &used, encoding: enc, options: [], range: theRange, remaining: nil) {
throw NSError(domain: NSCocoaErrorDomain, code: CocoaError.fileWriteUnknown.rawValue, userInfo: [
NSURLErrorKey: dest,
])
}
}
data = mData
}
internal func _writeTo(_ url: URL, _ useAuxiliaryFile: Bool, _ enc: UInt) throws {
var data = Data()
try _getExternalRepresentation(&data, url, enc)
try data.write(to: url, options: useAuxiliaryFile ? .atomic : [])
}
open func write(to url: URL, atomically useAuxiliaryFile: Bool, encoding enc: UInt) throws {
try _writeTo(url, useAuxiliaryFile, enc)
}
open func write(toFile path: String, atomically useAuxiliaryFile: Bool, encoding enc: UInt) throws {
try _writeTo(URL(fileURLWithPath: path), useAuxiliaryFile, enc)
}
public convenience init(charactersNoCopy characters: UnsafeMutablePointer<unichar>, length: Int, freeWhenDone freeBuffer: Bool) /* "NoCopy" is a hint */ {
// ignore the no-copy-ness
self.init(characters: characters, length: length)
if freeBuffer { // cant take a hint here...
free(UnsafeMutableRawPointer(characters))
}
}
public convenience init?(utf8String nullTerminatedCString: UnsafePointer<Int8>) {
let count = Int(strlen(nullTerminatedCString))
if let str = nullTerminatedCString.withMemoryRebound(to: UInt8.self, capacity: count, {
let buffer = UnsafeBufferPointer<UInt8>(start: $0, count: count)
return String._fromCodeUnitSequence(UTF8.self, input: buffer)
}) as String?
{
self.init(str)
} else {
return nil
}
}
public convenience init(format: String, arguments argList: CVaListPointer) {
let str = CFStringCreateWithFormatAndArguments(kCFAllocatorSystemDefault, nil, format._cfObject, argList)!
self.init(str._swiftObject)
}
public convenience init(format: String, locale: AnyObject?, arguments argList: CVaListPointer) {
let str: CFString
if let loc = locale {
if type(of: loc) === NSLocale.self || type(of: loc) === NSDictionary.self {
str = CFStringCreateWithFormatAndArguments(kCFAllocatorSystemDefault, unsafeBitCast(loc, to: CFDictionary.self), format._cfObject, argList)
} else {
fatalError("locale parameter must be a NSLocale or a NSDictionary")
}
} else {
str = CFStringCreateWithFormatAndArguments(kCFAllocatorSystemDefault, nil, format._cfObject, argList)
}
self.init(str._swiftObject)
}
public convenience init(format: NSString, _ args: CVarArg...) {
let str = withVaList(args) { (vaPtr) -> CFString! in
CFStringCreateWithFormatAndArguments(kCFAllocatorSystemDefault, nil, format._cfObject, vaPtr)
}!
self.init(str._swiftObject)
}
public convenience init?(data: Data, encoding: UInt) {
guard let cf = data.withUnsafeBytes({ (bytes: UnsafePointer<UInt8>) -> CFString? in
return CFStringCreateWithBytes(kCFAllocatorDefault, bytes, data.count, CFStringConvertNSStringEncodingToEncoding(encoding), true)
}) else { return nil }
var str: String?
if String._conditionallyBridgeFromObjectiveC(cf._nsObject, result: &str) {
self.init(str!)
} else {
return nil
}
}
public convenience init?(bytes: UnsafeRawPointer, length len: Int, encoding: UInt) {
let bytePtr = bytes.bindMemory(to: UInt8.self, capacity: len)
guard let cf = CFStringCreateWithBytes(kCFAllocatorDefault, bytePtr, len, CFStringConvertNSStringEncodingToEncoding(encoding), true) else {
return nil
}
var str: String?
if String._conditionallyBridgeFromObjectiveC(cf._nsObject, result: &str) {
self.init(str!)
} else {
return nil
}
}
public convenience init?(bytesNoCopy bytes: UnsafeMutableRawPointer, length len: Int, encoding: UInt, freeWhenDone freeBuffer: Bool) /* "NoCopy" is a hint */ {
// just copy for now since the internal storage will be a copy anyhow
self.init(bytes: bytes, length: len, encoding: encoding)
if freeBuffer { // dont take the hint
free(bytes)
}
}
public convenience init?(CString nullTerminatedCString: UnsafePointer<Int8>, encoding: UInt) {
guard let cf = CFStringCreateWithCString(kCFAllocatorSystemDefault, nullTerminatedCString, CFStringConvertNSStringEncodingToEncoding(encoding)) else {
return nil
}
var str: String?
if String._conditionallyBridgeFromObjectiveC(cf._nsObject, result: &str) {
self.init(str!)
} else {
return nil
}
}
public convenience init(contentsOf url: URL, encoding enc: UInt) throws {
let readResult = try NSData(contentsOf: url, options: [])
let bytePtr = readResult.bytes.bindMemory(to: UInt8.self, capacity: readResult.length)
guard let cf = CFStringCreateWithBytes(kCFAllocatorDefault, bytePtr, readResult.length, CFStringConvertNSStringEncodingToEncoding(enc), true) else {
throw NSError(domain: NSCocoaErrorDomain, code: CocoaError.fileReadInapplicableStringEncoding.rawValue, userInfo: [
"NSDebugDescription" : "Unable to create a string using the specified encoding."
])
}
var str: String?
if String._conditionallyBridgeFromObjectiveC(cf._nsObject, result: &str) {
self.init(str!)
} else {
throw NSError(domain: NSCocoaErrorDomain, code: CocoaError.fileReadInapplicableStringEncoding.rawValue, userInfo: [
"NSDebugDescription" : "Unable to bridge CFString to String."
])
}
}
public convenience init(contentsOfFile path: String, encoding enc: UInt) throws {
try self.init(contentsOf: URL(fileURLWithPath: path), encoding: enc)
}
public convenience init(contentsOf url: URL, usedEncoding enc: UnsafeMutablePointer<UInt>?) throws {
NSUnimplemented()
}
public convenience init(contentsOfFile path: String, usedEncoding enc: UnsafeMutablePointer<UInt>?) throws {
NSUnimplemented()
}
}
extension NSString : ExpressibleByStringLiteral { }
open class NSMutableString : NSString {
open func replaceCharacters(in range: NSRange, with aString: String) {
guard type(of: self) === NSString.self || type(of: self) === NSMutableString.self else {
NSRequiresConcreteImplementation()
}
// this is incorrectly calculated for grapheme clusters that have a size greater than a single unichar
let start = _storage.startIndex
let min = _storage.index(start, offsetBy: range.location)
let max = _storage.index(start, offsetBy: range.location + range.length)
_storage.replaceSubrange(min..<max, with: aString)
}
public required override init(characters: UnsafePointer<unichar>, length: Int) {
super.init(characters: characters, length: length)
}
public required init(capacity: Int) {
super.init(characters: [], length: 0)
}
public convenience required init?(coder aDecoder: NSCoder) {
guard let str = NSString(coder: aDecoder) else {
return nil
}
self.init(string: String._unconditionallyBridgeFromObjectiveC(str))
}
public required convenience init(unicodeScalarLiteral value: StaticString) {
self.init(stringLiteral: value)
}
public required convenience init(extendedGraphemeClusterLiteral value: StaticString) {
self.init(stringLiteral: value)
}
public required init(stringLiteral value: StaticString) {
if value.hasPointerRepresentation {
super.init(String._fromWellFormedCodeUnitSequence(UTF8.self, input: UnsafeBufferPointer(start: value.utf8Start, count: Int(value.utf8CodeUnitCount))))
} else {
var uintValue = value.unicodeScalar.value
super.init(String._fromWellFormedCodeUnitSequence(UTF32.self, input: UnsafeBufferPointer(start: &uintValue, count: 1)))
}
}
public required init(string aString: String) {
super.init(aString)
}
internal func appendCharacters(_ characters: UnsafePointer<unichar>, length: Int) {
if type(of: self) == NSMutableString.self {
_storage.append(String._fromWellFormedCodeUnitSequence(UTF16.self, input: UnsafeBufferPointer(start: characters, count: length)))
} else {
replaceCharacters(in: NSMakeRange(self.length, 0), with: String._fromWellFormedCodeUnitSequence(UTF16.self, input: UnsafeBufferPointer(start: characters, count: length)))
}
}
internal func _cfAppendCString(_ characters: UnsafePointer<Int8>, length: Int) {
if type(of: self) == NSMutableString.self {
_storage.append(String(cString: characters))
}
}
}
extension NSMutableString {
public func insert(_ aString: String, at loc: Int) {
replaceCharacters(in: NSMakeRange(loc, 0), with: aString)
}
public func deleteCharacters(in range: NSRange) {
replaceCharacters(in: range, with: "")
}
public func append(_ aString: String) {
replaceCharacters(in: NSMakeRange(length, 0), with: aString)
}
public func setString(_ aString: String) {
replaceCharacters(in: NSMakeRange(0, length), with: aString)
}
internal func _replaceOccurrencesOfRegularExpressionPattern(_ pattern: String, withTemplate replacement: String, options: CompareOptions, range searchRange: NSRange) -> Int {
let regexOptions: NSRegularExpression.Options = options.contains(.caseInsensitive) ? .caseInsensitive : []
let matchingOptions: NSMatchingOptions = options.contains(.anchored) ? .anchored : []
if let regex = _createRegexForPattern(pattern, regexOptions) {
return regex.replaceMatches(in: self, options: matchingOptions, range: searchRange, withTemplate: replacement)
}
return 0
}
public func replaceOccurrences(of target: String, with replacement: String, options: CompareOptions = [], range searchRange: NSRange) -> Int {
let backwards = options.contains(.backwards)
let len = length
precondition(searchRange.length <= len && searchRange.location <= len - searchRange.length, "Search range is out of bounds")
if options.contains(.regularExpression) {
return _replaceOccurrencesOfRegularExpressionPattern(target, withTemplate:replacement, options:options, range: searchRange)
}
if let findResults = CFStringCreateArrayWithFindResults(kCFAllocatorSystemDefault, _cfObject, target._cfObject, CFRange(searchRange), options._cfValue(true)) {
let numOccurrences = CFArrayGetCount(findResults)
for cnt in 0..<numOccurrences {
let rangePtr = CFArrayGetValueAtIndex(findResults, backwards ? cnt : numOccurrences - cnt - 1)
replaceCharacters(in: NSRange(rangePtr!.load(as: CFRange.self)), with: replacement)
}
return numOccurrences
} else {
return 0
}
}
public func applyTransform(_ transform: String, reverse: Bool, range: NSRange, updatedRange resultingRange: NSRangePointer?) -> Bool {
var cfRange = CFRangeMake(range.location, range.length)
return withUnsafeMutablePointer(to: &cfRange) { (rangep: UnsafeMutablePointer<CFRange>) -> Bool in
if CFStringTransform(_cfMutableObject, rangep, transform._cfObject, reverse) {
resultingRange?.pointee.location = rangep.pointee.location
resultingRange?.pointee.length = rangep.pointee.length
return true
}
return false
}
}
}
extension String {
// this is only valid for the usage for CF since it expects the length to be in unicode characters instead of grapheme clusters "✌🏾".utf16.count = 3 and CFStringGetLength(CFSTR("✌🏾")) = 3 not 1 as it would be represented with grapheme clusters
internal var length: Int {
return utf16.count
}
}
extension NSString : _CFBridgeable, _SwiftBridgeable {
typealias SwiftType = String
internal var _cfObject: CFString { return unsafeBitCast(self, to: CFString.self) }
internal var _swiftObject: String { return String._unconditionallyBridgeFromObjectiveC(self) }
}
extension NSMutableString {
internal var _cfMutableObject: CFMutableString { return unsafeBitCast(self, to: CFMutableString.self) }
}
extension CFString : _NSBridgeable, _SwiftBridgeable {
typealias NSType = NSString
typealias SwiftType = String
internal var _nsObject: NSType { return unsafeBitCast(self, to: NSString.self) }
internal var _swiftObject: String { return _nsObject._swiftObject }
}
extension String : _NSBridgeable, _CFBridgeable {
typealias NSType = NSString
typealias CFType = CFString
internal var _nsObject: NSType { return _bridgeToObjectiveC() }
internal var _cfObject: CFType { return _nsObject._cfObject }
}
#if !(os(OSX) || os(iOS))
extension String {
public func hasPrefix(_ prefix: String) -> Bool {
let cfstring = self._cfObject
let range = CFRangeMake(0, CFStringGetLength(cfstring))
let opts = CFStringCompareFlags(
kCFCompareAnchored | kCFCompareNonliteral)
return CFStringFindWithOptions(cfstring, prefix._cfObject,
range, opts, nil)
}
public func hasSuffix(_ suffix: String) -> Bool {
let cfstring = self._cfObject
let range = CFRangeMake(0, CFStringGetLength(cfstring))
let opts = CFStringCompareFlags(
kCFCompareAnchored | kCFCompareBackwards | kCFCompareNonliteral)
return CFStringFindWithOptions(cfstring, suffix._cfObject,
range, opts, nil)
}
}
#endif
extension NSString : _StructTypeBridgeable {
public typealias _StructType = String
public func _bridgeToSwift() -> _StructType {
return _StructType._unconditionallyBridgeFromObjectiveC(self)
}
}
| apache-2.0 | 773bc2409c78a1acc1a5fb15bcd78af9 | 43.006878 | 274 | 0.640406 | 5.179375 | false | false | false | false |
brentsimmons/Evergreen | Shared/Extensions/RSImage-AppIcons.swift | 1 | 897 | //
// RSImage-AppIcons.swift
// NetNewsWire
//
// Created by Nate Weaver on 2019-12-07.
// Copyright © 2019 Ranchero Software. All rights reserved.
//
import Foundation
import RSCore
extension RSImage {
static var appIconImage: RSImage? {
#if os(macOS)
return RSImage(named: NSImage.applicationIconName)
#elseif os(iOS)
// https://stackoverflow.com/a/51241158/14256
if let icons = Bundle.main.infoDictionary?["CFBundleIcons"] as? [String: Any],
let primaryIcon = icons["CFBundlePrimaryIcon"] as? [String: Any],
let iconFiles = primaryIcon["CFBundleIconFiles"] as? [String],
let lastIcon = iconFiles.last {
return RSImage(named: lastIcon)
}
return nil
#endif
}
}
extension IconImage {
static var appIcon: IconImage? = {
if let image = RSImage.appIconImage {
return IconImage(image)
}
return nil
}()
}
| mit | 58422a2deec9414db5a889bee0d2c81e | 23.888889 | 86 | 0.666295 | 3.472868 | false | false | false | false |
overtake/TelegramSwift | Telegram-Mac/ChatInputAttachView.swift | 1 | 14707 |
//
// ChatInputAttachView.swift
// Telegram-Mac
//
// Created by keepcoder on 26/09/2016.
// Copyright © 2016 Telegram. All rights reserved.
//
import Cocoa
import TGUIKit
import SwiftSignalKit
import TelegramCore
import Postbox
class ChatInputAttachView: ImageButton, Notifable {
private var chatInteraction:ChatInteraction
private var controller:SPopoverViewController?
private let editMediaAccessory: ImageView = ImageView()
init(frame frameRect: NSRect, chatInteraction:ChatInteraction) {
self.chatInteraction = chatInteraction
super.init(frame: frameRect)
highlightHovered = false
updateLayout()
let context = chatInteraction.context
self.contextMenu = { [weak self] in
guard let `self` = self else {
return nil
}
let chatInteraction = self.chatInteraction
if let peer = chatInteraction.presentation.peer {
var items:[ContextMenuItem] = []
if let editState = chatInteraction.presentation.interfaceState.editState, let media = editState.originalMedia, media is TelegramMediaFile || media is TelegramMediaImage {
if editState.message.groupingKey == nil {
items.append(ContextMenuItem(strings().inputAttachPopoverPhotoOrVideo, handler: { [weak self] in
self?.chatInteraction.updateEditingMessageMedia(nil, true)
}, itemImage: MenuAnimation.menu_shared_media.value))
items.append(ContextMenuItem(strings().inputAttachPopoverFile, handler: { [weak self] in
self?.chatInteraction.updateEditingMessageMedia(nil, false)
}, itemImage: MenuAnimation.menu_file.value))
if media is TelegramMediaImage {
items.append(ContextMenuItem(strings().editMessageEditCurrentPhoto, handler: { [weak self] in
self?.chatInteraction.editEditingMessagePhoto(media as! TelegramMediaImage)
}, itemImage: MenuAnimation.menu_edit.value))
}
} else {
if let _ = editState.message.effectiveMedia as? TelegramMediaImage {
items.append(ContextMenuItem(strings().inputAttachPopoverPhotoOrVideo, handler: { [weak self] in
self?.chatInteraction.updateEditingMessageMedia(mediaExts, true)
}, itemImage: MenuAnimation.menu_edit.value))
} else if let file = editState.message.effectiveMedia as? TelegramMediaFile {
if file.isVideoFile {
items.append(ContextMenuItem(strings().inputAttachPopoverPhotoOrVideo, handler: { [weak self] in
self?.chatInteraction.updateEditingMessageMedia(mediaExts, true)
}, itemImage: MenuAnimation.menu_shared_media.value))
}
if file.isMusic {
items.append(ContextMenuItem(strings().inputAttachPopoverMusic, handler: { [weak self] in
self?.chatInteraction.updateEditingMessageMedia(audioExts, false)
}, itemImage: MenuAnimation.menu_music.value))
} else {
items.append(ContextMenuItem(strings().inputAttachPopoverFile, handler: { [weak self] in
self?.chatInteraction.updateEditingMessageMedia(nil, false)
}, itemImage: MenuAnimation.menu_file.value))
}
}
}
} else if chatInteraction.presentation.interfaceState.editState == nil {
let peerId = chatInteraction.peerId
if let slowMode = self.chatInteraction.presentation.slowMode, slowMode.hasLocked {
showSlowModeTimeoutTooltip(slowMode, for: self)
return nil
}
items.append(ContextMenuItem(strings().inputAttachPopoverPhotoOrVideo, handler: { [weak self] in
if let permissionText = permissionText(from: peer, for: .banSendMedia) {
alert(for: context.window, info: permissionText)
return
}
self?.chatInteraction.attachPhotoOrVideo()
}, itemImage: MenuAnimation.menu_shared_media.value))
let chatMode = chatInteraction.presentation.chatMode
let replyTo = chatInteraction.presentation.interfaceState.replyMessageId ?? chatMode.threadId
let threadId = chatInteraction.presentation.chatLocation.threadId
let acceptMode = chatMode == .history || (chatMode.isThreadMode || chatMode.isTopicMode)
if acceptMode, let peer = chatInteraction.presentation.peer {
for attach in chatInteraction.presentation.attachItems {
let thumbFile: TelegramMediaFile
var value: (NSColor, ContextMenuItem)-> AppMenuItemImageDrawable
if let file = attach.icons[.macOSAnimated] {
value = MenuRemoteAnimation(context, file: file, bot: attach.peer, thumb: MenuAnimation.menu_webapp_placeholder).value
thumbFile = file
} else {
value = MenuAnimation.menu_folder_bot.value
thumbFile = MenuAnimation.menu_folder_bot.file
}
let canAddAttach: Bool
if peer.isUser {
canAddAttach = attach.peerTypes.contains(.all) || attach.peerTypes.contains(.user)
} else if peer.isBot {
canAddAttach = attach.peerTypes.contains(.all) || attach.peerTypes.contains(.bot) || (attach.peerTypes.contains(.sameBot) && attach.peer.id == peer.id)
} else if peer.isGroup || peer.isSupergroup {
canAddAttach = attach.peerTypes.contains(.all) || attach.peerTypes.contains(.group)
} else if peer.isChannel {
canAddAttach = attach.peerTypes.contains(.all) || attach.peerTypes.contains(.channel)
} else {
canAddAttach = false
}
if canAddAttach {
items.append(ContextMenuItem(attach.shortName, handler: { [weak self] in
let invoke:()->Void = { [weak self] in
showModal(with: WebpageModalController(context: context, url: "", title: attach.peer.displayTitle, requestData: .normal(url: nil, peerId: peerId, threadId: threadId, bot: attach.peer, replyTo: replyTo, buttonText: "", payload: nil, fromMenu: false, hasSettings: attach.hasSettings, complete: chatInteraction.afterSentTransition), chatInteraction: self?.chatInteraction, thumbFile: thumbFile), for: context.window)
}
invoke()
}, itemImage: value))
}
}
}
items.append(ContextMenuItem(strings().inputAttachPopoverFile, handler: { [weak self] in
if let permissionText = permissionText(from: peer, for: .banSendMedia) {
alert(for: context.window, info: permissionText)
return
}
self?.chatInteraction.attachFile(false)
}, itemImage: MenuAnimation.menu_file.value))
items.append(ContextMenuItem(strings().inputAttachPopoverPicture, handler: { [weak self] in
guard let `self` = self else {return}
if let permissionText = permissionText(from: peer, for: .banSendMedia) {
alert(for: self.chatInteraction.context.window, info: permissionText)
return
}
self.chatInteraction.attachPicture()
}, itemImage: MenuAnimation.menu_camera.value))
var canAttachPoll: Bool = false
if let peer = chatInteraction.presentation.peer, peer.isGroup || peer.isSupergroup {
canAttachPoll = true
}
if let peer = chatInteraction.presentation.mainPeer, peer.isBot {
canAttachPoll = true
}
if let peer = chatInteraction.presentation.peer as? TelegramChannel {
if peer.hasPermission(.sendMessages) {
canAttachPoll = true
}
}
if canAttachPoll && permissionText(from: peer, for: .banSendPolls) != nil {
canAttachPoll = false
}
if canAttachPoll {
items.append(ContextMenuItem(strings().inputAttachPopoverPoll, handler: { [weak self] in
guard let `self` = self else {return}
if let permissionText = permissionText(from: peer, for: .banSendPolls) {
alert(for: context.window, info: permissionText)
return
}
showModal(with: NewPollController(chatInteraction: self.chatInteraction), for: self.chatInteraction.context.window)
}, itemImage: MenuAnimation.menu_poll.value))
}
items.append(ContextMenuItem(strings().inputAttachPopoverLocation, handler: { [weak self] in
self?.chatInteraction.attachLocation()
}, itemImage: MenuAnimation.menu_location.value))
}
if !items.isEmpty {
let menu = ContextMenu(betterInside: true)
for item in items {
menu.addItem(item)
}
return menu
}
}
return nil
}
//
// set(handler: { [weak self] control in
//
//
// }, for: .Hover)
//
// set(handler: { [weak self] control in
// guard let `self` = self else {return}
//
// if let _ = chatInteraction.presentation.interfaceState.editState {
// return
// }
//
// if let peer = self.chatInteraction.presentation.peer {
// if let permissionText = permissionText(from: peer, for: .banSendMedia) {
// alert(for: self.chatInteraction.context.window, info: permissionText)
// return
// }
// self.controller?.popover?.hide()
// // Queue.mainQueue().justDispatch {
// if self.chatInteraction.presentation.interfaceState.editState != nil {
// self.chatInteraction.updateEditingMessageMedia(nil, true)
// } else {
// self.chatInteraction.attachFile(true)
// }
// // }
// }
// }, for: .Click)
chatInteraction.add(observer: self)
addSubview(editMediaAccessory)
editMediaAccessory.layer?.opacity = 0
updateLocalizationAndTheme(theme: theme)
}
func isEqual(to other: Notifable) -> Bool {
if let view = other as? ChatInputAttachView {
return view === self
} else {
return false
}
}
func notify(with value: Any, oldValue: Any, animated: Bool) {
let value = value as? ChatPresentationInterfaceState
let oldValue = oldValue as? ChatPresentationInterfaceState
if value?.interfaceState.editState != oldValue?.interfaceState.editState {
if let editState = value?.interfaceState.editState {
let isMedia = editState.message.effectiveMedia is TelegramMediaFile || editState.message.effectiveMedia is TelegramMediaImage
editMediaAccessory.change(opacity: isMedia ? 1 : 0)
self.highlightHovered = false
self.autohighlight = false
} else {
editMediaAccessory.change(opacity: 0)
self.highlightHovered = false
self.autohighlight = false
}
}
// if let slowMode = value?.slowMode {
// if slowMode.hasError {
// self.highlightHovered = false
// self.autohighlight = false
// }
// }
}
override func layout() {
super.layout()
editMediaAccessory.setFrameOrigin(46 - editMediaAccessory.frame.width, 23)
}
deinit {
chatInteraction.remove(observer: self)
}
override func updateLocalizationAndTheme(theme: PresentationTheme) {
super.updateLocalizationAndTheme(theme: theme)
let theme = (theme as! TelegramPresentationTheme)
editMediaAccessory.image = theme.icons.editMessageMedia
editMediaAccessory.sizeToFit()
set(image: theme.icons.chatAttach, for: .Normal)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
required init(frame frameRect: NSRect) {
fatalError("init(frame:) has not been implemented")
}
}
| gpl-2.0 | 15de7194511abc740ed92dbe3e315bcb | 47.857143 | 453 | 0.515096 | 5.782934 | false | false | false | false |
material-foundation/github-comment | Sources/GitHub/GitHubComments.swift | 1 | 1477 | /*
Copyright 2018-present the Material Foundation 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
extension GitHub {
public struct Comment: GitHubObject {
public typealias JsonFormat = [String: Any]
public init(json: JsonFormat) {
self.json = json
}
private let json: JsonFormat
public var id: Int? { get { return json["id"] as? Int } }
public var body: String? { get { return json["body"] as? String } }
public var user: User? {
get {
guard let user = json["user"] as? User.JsonFormat else {
return nil
}
return User(json: user)
}
}
}
public struct CommentList: GitHubObject {
public typealias JsonFormat = [Comment.JsonFormat]
public init(json: JsonFormat) {
self.json = json
}
private let json: JsonFormat
public var comments: [Comment]? {
get {
return json.map { Comment(json: $0) }
}
}
}
}
| apache-2.0 | cfa0b6665e143a4c9798a74757fc0ad7 | 27.403846 | 77 | 0.670955 | 4.184136 | false | false | false | false |
optimizely/swift-sdk | Tests/TestUtils/MockEventDispatcher.swift | 1 | 2005 | //
// Copyright 2021, Optimizely, Inc. and contributors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import Foundation
class MockEventDispatcher: OPTEventDispatcher {
public var events = [EventForDispatch]()
public var totalEventsFlushed: Int
init() {
totalEventsFlushed = 0
}
func dispatchEvent(event: EventForDispatch, completionHandler: DispatchCompletionHandler?) {
events.append(event)
}
func flushEvents() {
totalEventsFlushed += events.count
events.removeAll()
}
}
class MockDefaultEventDispatcher: DefaultEventDispatcher {
var withError: Bool
init(withError: Bool) {
self.withError = withError
super.init()
}
override func getSession() -> URLSession {
return MockUrlSession(withError: withError)
}
}
class DumpEventDispatcher: DefaultEventDispatcher {
public var totalEventsSent: Int
init(dataStoreName: String = "OPTEventQueue", timerInterval: TimeInterval = DefaultValues.timeInterval) {
totalEventsSent = 0
super.init(dataStoreName: dataStoreName, timerInterval: timerInterval)
}
override func sendEvent(event: EventForDispatch, completionHandler: @escaping DispatchCompletionHandler) {
if let decodedEvent = try? JSONDecoder().decode(BatchEvent.self, from: event.body) {
totalEventsSent += decodedEvent.visitors.count
}
completionHandler(.success(Data()))
}
}
| apache-2.0 | 2c2a2605028256dc4df79e87cd215024 | 28.925373 | 110 | 0.699252 | 4.728774 | false | false | false | false |
momo13014/RayWenderlichDemo | PhotoScroll_Starter/PhotoScroll/PhotoCommentViewController.swift | 1 | 3121 | //
// PhotoCommentViewController.swift
// PhotoScroll
//
// Created by shendong on 16/9/6.
// Copyright © 2016年 raywenderlich. All rights reserved.
//
import UIKit
class PhotoCommentViewController: UIViewController {
@IBOutlet weak var imageView: UIImageView!
@IBOutlet weak var scrollView: UIScrollView!
@IBOutlet weak var nameTextField: UITextField!
public var photoName: String!
public var photoIndex: Int!
override func viewDidLoad() {
super.viewDidLoad()
if let photoName = photoName {
self.imageView.image = UIImage(named: photoName)
}
NSNotificationCenter.defaultCenter().addObserver(self,
selector: #selector(PhotoCommentViewController.keyboardWillShow(_:)),
name: UIKeyboardWillShowNotification,
object: nil)
NSNotificationCenter.defaultCenter().addObserver(self,
selector: #selector(PhotoCommentViewController.keyboardWillHide(_:)),
name: UIKeyboardWillHideNotification,
object: nil)
}
//MARK: NSNotificationCenter method
func adjustINsetForKeyboardShow(show: Bool, notification: NSNotification){
guard let value = notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue else { return }
let keyboardFrame = value.CGRectValue()
let adjustmentHeight = (CGRectGetHeight(keyboardFrame) + 20) * (show ? 1 : -1)
scrollView.contentInset.bottom += adjustmentHeight
scrollView.scrollIndicatorInsets.bottom += adjustmentHeight
}
func keyboardWillShow(notification: NSNotification){
adjustINsetForKeyboardShow(true, notification: notification)
}
func keyboardWillHide(notificaiton: NSNotification){
adjustINsetForKeyboardShow(false, notification: notificaiton)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
deinit{
NSNotificationCenter.defaultCenter().removeObserver(self)
}
@IBAction func hideKeyboard(sender: AnyObject){
nameTextField.endEditing(true)
}
@IBAction func openZoomingController(sender: AnyObject){
self.performSegueWithIdentifier("zooming", sender: nil)
}
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
if let id = segue.identifier, zoomedphotoViewController = segue.destinationViewController as? ZoomedPhotoViewController {
if id == "zooming" {
zoomedphotoViewController.photoName = photoName
}
}
}
}
| mit | 0995649cb1e2ea51d89b7e306b2c85e0 | 38.974359 | 127 | 0.649134 | 5.817164 | false | false | false | false |
ReactiveKit/ReactiveKit | Sources/SignalProtocol+Filtering.swift | 1 | 14727 | //
// The MIT License (MIT)
//
// Copyright (c) 2016-2019 Srdan Rasic (@srdanrasic)
//
// 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
extension SignalProtocol {
/// Emit an element only if `interval` time passes without emitting another element.
///
/// Check out interactive example at [https://rxmarbles.com/#debounceTime](https://rxmarbles.com/#debounceTime)
public func debounce(interval: Double, queue: DispatchQueue = DispatchQueue(label: "reactive_kit.debounce")) -> Signal<Element, Error> {
return Signal { observer in
var timerSubscription: Disposable? = nil
var previousElement: Element? = nil
return self.observe { event in
timerSubscription?.dispose()
switch event {
case .next(let element):
previousElement = element
timerSubscription = queue.disposableAfter(when: interval) {
if let _element = previousElement {
observer.next(_element)
previousElement = nil
}
}
case .failed(let error):
observer.failed(error)
case .completed:
if let previousElement = previousElement {
observer.next(previousElement)
observer.completed()
}
}
}
}
}
/// Emit first element and then all elements that are not equal to their predecessor(s).
///
/// Check out interactive example at [https://rxmarbles.com/#distinctUntilChanged](https://rxmarbles.com/#distinctUntilChanged)
public func distinctUntilChanged(_ areDistinct: @escaping (Element, Element) -> Bool) -> Signal<Element, Error> {
return zipPrevious().compactMap { (prev, next) -> Element? in
prev == nil || areDistinct(prev!, next) ? next : nil
}
}
/// Emit only the element at given index (if such element is produced).
///
/// Check out interactive example at [https://rxmarbles.com/#elementAt](https://rxmarbles.com/#elementAt)
public func element(at index: Int) -> Signal<Element, Error> {
return take(first: index + 1).last()
}
/// Emit only elements that pass the `include` test.
///
/// Check out interactive example at [https://rxmarbles.com/#filter](https://rxmarbles.com/#filter)
public func filter(_ isIncluded: @escaping (Element) -> Bool) -> Signal<Element, Error> {
return Signal { observer in
return self.observe { event in
switch event {
case .next(let element):
if isIncluded(element) {
observer.next(element)
}
default:
observer.on(event)
}
}
}
}
/// Filter the signal by executing `isIncluded` in each element and
/// propagate that element only if the returned signal emits `true`.
public func flatMapFilter(_ strategy: FlattenStrategy = .concat, _ isIncluded: @escaping (Element) -> SafeSignal<Bool>) -> Signal<Element, Error> {
return flatMap(strategy) { element -> Signal<Element, Error> in
return isIncluded(element)
.first()
.map { isIncluded -> Element? in
if isIncluded {
return element
} else {
return nil
}
}
.ignoreNils()
.castError()
}
}
/// Emit only the first element of the signal and then complete.
///
/// Check out interactive example at [https://rxmarbles.com/#first](https://rxmarbles.com/#first)
public func first() -> Signal<Element, Error> {
return take(first: 1)
}
/// Ignore all elements (just propagate terminal events).
///
/// Check out interactive example at [https://rxmarbles.com/#ignoreElements](https://rxmarbles.com/#ignoreElements)
public func ignoreElements() -> Signal<Element, Error> {
return filter { _ in false }
}
/// Ignore all terminal events (just propagate next events). The signal will never complete or error out.
public func ignoreTerminal() -> Signal<Element, Error> {
return Signal { observer in
return self.observe { event in
if case .next(let element) = event {
observer.next(element)
}
}
}
}
/// Emit only the last element of the signal and then complete.
///
/// Check out interactive example at [https://rxmarbles.com/#last](https://rxmarbles.com/#last)
public func last() -> Signal<Element, Error> {
return take(last: 1)
}
/// Supress elements while the last element on the other signal is `false`.
public func pausable<O: SignalProtocol>(by other: O) -> Signal<Element, Error> where O.Element == Bool {
return Signal { observer in
var allowed: Bool = true
let compositeDisposable = CompositeDisposable()
compositeDisposable += other.observeNext { value in
allowed = value
}
compositeDisposable += self.observe { event in
if event.isTerminal || allowed {
observer.on(event)
}
}
return compositeDisposable
}
}
/// Periodically sample the signal and emit the latest element from each interval.
///
/// Check out interactive example at [https://rxmarbles.com/#sample](https://rxmarbles.com/#sample)
public func sample(interval: Double, on queue: DispatchQueue = DispatchQueue(label: "reactive_kit.sample")) -> Signal<Element, Error> {
return Signal { observer in
let serialDisposable = SerialDisposable(otherDisposable: nil)
var latestElement: Element? = nil
var dispatch: (() -> Void)!
dispatch = {
queue.after(when: interval) {
guard !serialDisposable.isDisposed else { dispatch = nil; return }
if let element = latestElement {
observer.next(element)
latestElement = nil
}
dispatch()
}
}
serialDisposable.otherDisposable = self.observe { event in
switch event {
case .next(let element):
latestElement = element
default:
observer.on(event)
serialDisposable.dispose()
}
}
dispatch()
return serialDisposable
}
}
/// Suppress first `count` elements generated by the signal.
///
/// Check out interactive example at [https://rxmarbles.com/#skip](https://rxmarbles.com/#skip)
public func skip(first count: Int) -> Signal<Element, Error> {
return Signal { observer in
var count = count
return self.observe { event in
switch event {
case .next(let element):
if count > 0 {
count -= 1
} else {
observer.next(element)
}
default:
observer.on(event)
}
}
}
}
/// Suppress last `count` elements generated by the signal.
///
/// Check out interactive example at [https://rxmarbles.com/#skip](https://rxmarbles.com/#skip)
public func skip(last count: Int) -> Signal<Element, Error> {
guard count > 0 else { return self.toSignal() }
return Signal { observer in
var buffer: [Element] = []
return self.observe { event in
switch event {
case .next(let element):
buffer.append(element)
if buffer.count > count {
observer.next(buffer.removeFirst())
}
default:
observer.on(event)
}
}
}
}
/// Suppress elements for first `interval` seconds.
public func skip(interval: Double) -> Signal<Element, Error> {
return Signal { observer in
let startTime = Date().addingTimeInterval(interval)
return self.observe { event in
switch event {
case .next:
if startTime < Date() {
observer.on(event)
}
case .completed, .failed:
observer.on(event)
}
}
}
}
/// Emit only first `count` elements of the signal and then complete.
///
/// Check out interactive example at [https://rxmarbles.com/#take](https://rxmarbles.com/#take)
public func take(first count: Int) -> Signal<Element, Error> {
guard count > 0 else { return .completed() }
return Signal { observer in
var taken = 0
return self.observe { event in
switch event {
case .next(let element):
if taken < count {
taken += 1
observer.next(element)
}
if taken == count {
observer.completed()
}
default:
observer.on(event)
}
}
}
}
/// Emit only last `count` elements of the signal and then complete.
///
/// Check out interactive example at [https://rxmarbles.com/#takeLast](https://rxmarbles.com/#takeLast)
public func take(last count: Int) -> Signal<Element, Error> {
return Signal { observer in
var values: [Element] = []
values.reserveCapacity(count)
return self.observe(with: { (event) in
switch event {
case .completed:
values.forEach(observer.next)
observer.completed()
case .failed(let error):
observer.failed(error)
case .next(let element):
if event.isTerminal {
observer.on(event)
} else {
if values.count + 1 > count {
values.removeFirst(values.count - count + 1)
}
values.append(element)
}
}
})
}
}
/// Emit elements until the given closure returns first `false`.
///
/// Check out interactive example at [https://rxmarbles.com/#takeWhile](https://rxmarbles.com/#takeWhile)
public func take(while shouldContinue: @escaping (Element) -> Bool) -> Signal<Element, Error> {
return Signal { observer in
return self.observe { event in
switch event {
case .next(let element):
if shouldContinue(element) {
observer.next(element)
} else {
observer.completed()
}
default:
observer.on(event)
}
}
}
}
/// Emit elements until the given signal sends an event (of any kind)
/// and then complete and dispose the signal.
public func take<S: SignalProtocol>(until signal: S) -> Signal<Element, Error> {
return Signal { observer in
let disposable = CompositeDisposable()
disposable += signal.observe { _ in
observer.completed()
}
disposable += self.observe { event in
switch event {
case .completed:
observer.completed()
case .failed(let error):
observer.failed(error)
case .next(let element):
observer.next(element)
}
}
return disposable
}
}
/// Throttle the signal to emit at most one element per given `seconds` interval.
///
/// Check out interactive example at [https://rxmarbles.com/#throttle](https://rxmarbles.com/#throttle)
public func throttle(seconds: Double) -> Signal<Element, Error> {
return Signal { observer in
var lastEventTime: DispatchTime?
return self.observe { event in
switch event {
case .next(let element):
let now = DispatchTime.now()
if lastEventTime == nil || now.rawValue > (lastEventTime! + seconds).rawValue {
lastEventTime = now
observer.next(element)
}
default:
observer.on(event)
}
}
}
}
}
extension SignalProtocol where Element: Equatable {
/// Emit first element and then all elements that are not equal to their predecessor(s).
///
/// Check out interactive example at [https://rxmarbles.com/#distinctUntilChanged](https://rxmarbles.com/#distinctUntilChanged)
public func distinctUntilChanged() -> Signal<Element, Error> {
return distinctUntilChanged(!=)
}
}
| mit | feeb0a9afc31b929822c35977422e05c | 38.167553 | 151 | 0.535072 | 5.145702 | false | false | false | false |
squall09s/VegOresto | VegoResto/Ressources/Lib/FBAnnotation/FBClusteringManager.swift | 1 | 6102 | //
// FBClusteringManager.swift
// FBAnnotationClusteringSwift
//
// Created by Robert Chen on 4/2/15.
// Copyright (c) 2015 Robert Chen. All rights reserved.
//
import Foundation
import MapKit
public protocol FBClusteringManagerDelegate {
func cellSizeFactorForCoordinator(coordinator: FBClusteringManager) -> CGFloat
}
public class FBClusteringManager: NSObject {
public var delegate: FBClusteringManagerDelegate?
var tree: FBQuadTree?
var lock: NSRecursiveLock = NSRecursiveLock()
public var maxZoomLevel = 1.0
public override init() {
super.init()
}
public init(annotations: [MKAnnotation]) {
super.init()
addAnnotations(annotations: annotations)
}
public func setAnnotations(annotations: [MKAnnotation]) {
tree = nil
addAnnotations(annotations: annotations)
}
public func addAnnotations(annotations: [MKAnnotation]) {
if tree == nil {
tree = FBQuadTree()
}
lock.lock()
for annotation in annotations {
tree!.insertAnnotation(annotation: annotation)
}
lock.unlock()
}
public func clusteredAnnotationsWithinMapRect(rect: MKMapRect, withZoomScale zoomScale: Double) -> [MKAnnotation] {
guard !zoomScale.isInfinite else { return [] }
let cellSize: CGFloat = FBClusteringManager.FBCellSizeForZoomScale(zoomScale: MKZoomScale(zoomScale))
// if delegate?.respondsToSelector("cellSizeFactorForCoordinator:") {
// cellSize *= delegate.cellSizeFactorForCoordinator(self)
// }
let scaleFactor: Double = zoomScale / Double(cellSize)
let minX: Int = Int(floor(MKMapRectGetMinX(rect) * scaleFactor))
let maxX: Int = Int(floor(MKMapRectGetMaxX(rect) * scaleFactor))
let minY: Int = Int(floor(MKMapRectGetMinY(rect) * scaleFactor))
let maxY: Int = Int(floor(MKMapRectGetMaxY(rect) * scaleFactor))
var clusteredAnnotations = [MKAnnotation]()
lock.lock()
for i in minX...maxX {
for j in minY...maxY {
let mapPoint = MKMapPoint(x: Double(i)/scaleFactor, y: Double(j)/scaleFactor)
let mapSize = MKMapSize(width: 1.0/scaleFactor, height: 1.0/scaleFactor)
let mapRect = MKMapRect(origin: mapPoint, size: mapSize)
let mapBox: FBBoundingBox = FBQuadTreeNode.FBBoundingBoxForMapRect(mapRect: mapRect)
var totalLatitude: Double = 0
var totalLongitude: Double = 0
var annotations = [MKAnnotation]()
tree?.enumerateAnnotationsInBox(box: mapBox) { obj in
totalLatitude += obj.coordinate.latitude
totalLongitude += obj.coordinate.longitude
annotations.append(obj)
}
let count = annotations.count
if count == 1 {
clusteredAnnotations += annotations
}
if count > 1 && zoomScale < self.maxZoomLevel {
let coordinate = CLLocationCoordinate2D(
latitude: CLLocationDegrees(totalLatitude)/CLLocationDegrees(count),
longitude: CLLocationDegrees(totalLongitude)/CLLocationDegrees(count)
)
let cluster = FBAnnotationCluster()
cluster.coordinate = coordinate
cluster.annotations = annotations
clusteredAnnotations.append(cluster)
} else {
clusteredAnnotations += annotations
}
}
}
lock.unlock()
return clusteredAnnotations
}
public func allAnnotations() -> [MKAnnotation] {
var annotations = [MKAnnotation]()
lock.lock()
tree?.enumerateAnnotationsUsingBlock { obj in
annotations.append(obj)
}
lock.unlock()
return annotations
}
public func displayAnnotations(annotations: [MKAnnotation], onMapView mapView: MKMapView) {
DispatchQueue.main.async {
let before = NSMutableSet(array: mapView.annotations)
before.remove(mapView.userLocation)
let after = NSSet(array: annotations)
let toKeep = NSMutableSet(set: before)
toKeep.intersect(after as Set<NSObject>)
let toAdd = NSMutableSet(set: after)
toAdd.minus(toKeep as Set<NSObject>)
let toRemove = NSMutableSet(set: before)
toRemove.minus(after as Set<NSObject>)
if let toAddAnnotations = toAdd.allObjects as? [MKAnnotation] {
mapView.addAnnotations(toAddAnnotations)
}
if let removeAnnotations = toRemove.allObjects as? [MKAnnotation] {
mapView.removeAnnotations(removeAnnotations)
}
}
}
public class func FBZoomScaleToZoomLevel(scale: MKZoomScale) -> Int {
let totalTilesAtMaxZoom: Double = MKMapSizeWorld.width / 256.0
let zoomLevelAtMaxZoom: Int = Int(log2(totalTilesAtMaxZoom))
let floorLog2ScaleFloat = floor(log2f(Float(scale))) + 0.5
guard !floorLog2ScaleFloat.isInfinite else { return floorLog2ScaleFloat.sign == .plus ? 0 : 19 }
let sum: Int = zoomLevelAtMaxZoom + Int(floorLog2ScaleFloat)
let zoomLevel: Int = max(0, sum)
return zoomLevel
}
public class func FBCellSizeForZoomScale(zoomScale: MKZoomScale) -> CGFloat {
let zoomLevel: Int = FBClusteringManager.FBZoomScaleToZoomLevel(scale: zoomScale)
switch (zoomLevel) {
case 13:
return 64
case 14:
return 64
case 15:
return 64
case 16:
return 32
case 17:
return 32
case 18:
return 32
case 18 ..< Int.max:
return 16
default:
// less than 13 zoom level
return 88
}
}
}
| gpl-3.0 | 128fcb5dda18b42b26525c62687296bf | 29.663317 | 119 | 0.597509 | 5.05551 | false | false | false | false |
mercadopago/sdk-ios | MercadoPagoSDK/MercadoPagoSDK/Fingerprint.swift | 1 | 4530 | //
// Fingerprint.swift
// MercadoPagoSDK
//
// Created by Matias Gualino on 28/12/14.
// Copyright (c) 2014 com.mercadopago. All rights reserved.
//
import Foundation
import UIKit
public class Fingerprint : NSObject {
public var fingerprint : [String : AnyObject]?
public override init () {
super.init()
self.fingerprint = deviceFingerprint()
}
public func toJSONString() -> String {
return JSON(self.fingerprint!).toString()
}
public func deviceFingerprint() -> [String : AnyObject] {
let device : UIDevice = UIDevice.currentDevice()
var dictionary : [String : AnyObject] = [String : AnyObject]()
dictionary["os"] = "iOS"
let devicesId : [AnyObject]? = devicesID()
if devicesId != nil {
dictionary["vendor_ids"] = devicesId!
}
if !String.isNullOrEmpty(device.hwmodel) {
dictionary["model"] = device.hwmodel
}
dictionary["os"] = "iOS"
if !String.isNullOrEmpty(device.systemVersion) {
dictionary["system_version"] = device.systemVersion
}
let screenSize: CGRect = UIScreen.mainScreen().bounds
let width = NSString(format: "%.0f", screenSize.width)
let height = NSString(format: "%.0f", screenSize.height)
dictionary["resolution"] = "\(width)x\(height)"
dictionary["ram"] = device.totalMemory
dictionary["disk_space"] = device.totalDiskSpace
dictionary["free_disk_space"] = device.freeDiskSpace
var moreData = [String : AnyObject]()
moreData["feature_camera"] = device.cameraAvailable
moreData["feature_flash"] = device.cameraFlashAvailable
moreData["feature_front_camera"] = device.frontCameraAvailable
moreData["video_camera_available"] = device.videoCameraAvailable
moreData["cpu_count"] = device.cpuCount
moreData["retina_display_capable"] = device.retinaDisplayCapable
if device.userInterfaceIdiom == UIUserInterfaceIdiom.Pad {
moreData["device_idiom"] = "Pad"
} else {
moreData["device_idiom"] = "Phone"
}
if device.canSendSMS {
moreData["can_send_sms"] = 1
} else {
moreData["can_send_sms"] = 0
}
if device.canMakePhoneCalls {
moreData["can_make_phone_calls"] = 1
} else {
moreData["can_make_phone_calls"] = 0
}
if NSLocale.preferredLanguages().count > 0 {
moreData["device_languaje"] = NSLocale.preferredLanguages()[0]
}
if !String.isNullOrEmpty(device.model) {
moreData["device_model"] = device.model
}
if !String.isNullOrEmpty(device.platform) {
moreData["platform"] = device.platform
}
moreData["device_family"] = device.deviceFamily.rawValue
if !String.isNullOrEmpty(device.name) {
moreData["device_name"] = device.name
}
/*var simulator : Bool = false
#if TARGET_IPHONE_SIMULATOR
simulator = YES
#endif
if simulator {
moreData["simulator"] = 1
} else {
moreData["simulator"] = 0
}*/
moreData["simulator"] = 0
dictionary["vendor_specific_attributes"] = moreData
return dictionary
}
public func devicesID() -> [AnyObject]? {
let systemVersionString : String = UIDevice.currentDevice().systemVersion
let systemVersion : Float = (systemVersionString.componentsSeparatedByString(".")[0] as NSString).floatValue
if systemVersion < 6 {
let uuid : String = NSUUID().UUIDString
if !String.isNullOrEmpty(uuid) {
var dic : [String : AnyObject] = ["name" : "uuid"]
dic["value"] = uuid
return [dic]
}
}
else {
let vendorId : String = UIDevice.currentDevice().identifierForVendor!.UUIDString
let uuid : String = NSUUID().UUIDString
var dicVendor : [String : AnyObject] = ["name" : "vendor_id"]
dicVendor["value"] = vendorId
var dic : [String : AnyObject] = ["name" : "uuid"]
dic["value"] = uuid
return [dicVendor, dic]
}
return nil
}
} | mit | 1fddec36290ec59dd9501a42db198c68 | 30.685315 | 116 | 0.557616 | 4.689441 | false | false | false | false |
austinzheng/swift | test/SILOptimizer/closure_lifetime_fixup_objc.swift | 4 | 5941 | // RUN: %target-swift-frontend %s -enable-sil-ownership -sil-verify-all -emit-sil -o - -I %S/Inputs/usr/include | %FileCheck %s
// REQUIRES: objc_interop
import Foundation
import ClosureLifetimeFixupObjC
@objc
public protocol DangerousEscaper {
@objc
func malicious(_ mayActuallyEscape: () -> ())
}
// CHECK: sil @$s27closure_lifetime_fixup_objc19couldActuallyEscapeyyyyc_AA16DangerousEscaper_ptF : $@convention(thin) (@guaranteed @callee_guaranteed () -> (), @guaranteed DangerousEscaper) -> () {
// CHECK: bb0([[ARG:%.*]] : $@callee_guaranteed () -> (), [[SELF:%.*]] : $DangerousEscaper):
// CHECK: [[OE:%.*]] = open_existential_ref [[SELF]]
// Copy (1).
// CHECK: strong_retain [[ARG]] : $@callee_guaranteed () -> ()
// Extend the lifetime to the end of this function (2).
// CHECK: strong_retain [[ARG]] : $@callee_guaranteed () -> ()
// CHECK: [[OPT_CLOSURE:%.*]] = enum $Optional<@callee_guaranteed () -> ()>, #Optional.some!enumelt.1, [[ARG]] : $@callee_guaranteed () -> ()
// CHECK: [[NE:%.*]] = convert_escape_to_noescape [[ARG]] : $@callee_guaranteed () -> () to $@noescape @callee_guaranteed () -> ()
// CHECK: [[WITHOUT_ACTUALLY_ESCAPING_THUNK:%.*]] = function_ref @$sIg_Ieg_TR : $@convention(thin) (@noescape @callee_guaranteed () -> ()) -> ()
// CHECK: [[C:%.*]] = partial_apply [callee_guaranteed] [[WITHOUT_ACTUALLY_ESCAPING_THUNK]]([[NE]]) : $@convention(thin) (@noescape @callee_guaranteed () -> ()) -> ()
// Sentinel without actually escaping closure (3).
// CHECK: [[SENTINEL:%.*]] = mark_dependence [[C]] : $@callee_guaranteed () -> () on [[NE]] : $@noescape @callee_guaranteed () -> ()
// Copy of sentinel (4).
// CHECK: strong_retain [[SENTINEL]] : $@callee_guaranteed () -> ()
// CHECK: [[BLOCK_STORAGE:%.*]] = alloc_stack $@block_storage @callee_guaranteed () -> ()
// CHECK: [[CLOSURE_ADDR:%.*]] = project_block_storage [[BLOCK_STORAGE]] : $*@block_storage @callee_guaranteed () -> ()
// CHECK: store [[SENTINEL]] to [[CLOSURE_ADDR]] : $*@callee_guaranteed () -> ()
// CHECK: [[BLOCK_INVOKE:%.*]] = function_ref @$sIeg_IyB_TR : $@convention(c) (@inout_aliasable @block_storage @callee_guaranteed () -> ()) -> ()
// CHECK: [[BLOCK:%.*]] = init_block_storage_header [[BLOCK_STORAGE]] : $*@block_storage @callee_guaranteed () -> (), invoke [[BLOCK_INVOKE]] : $@convention(c) (@inout_aliasable @block_storage @callee_guaranteed () -> ()) -> (), type $@convention(block) @noescape () -> ()
// Optional sentinel (4).
// CHECK: [[OPT_SENTINEL:%.*]] = enum $Optional<@callee_guaranteed () -> ()>, #Optional.some!enumelt.1, [[SENTINEL]] : $@callee_guaranteed () -> ()
// Copy of sentinel closure (5).
// CHECK: [[BLOCK_COPY:%.*]] = copy_block [[BLOCK]] : $@convention(block) @noescape () -> ()
// Release of sentinel closure (3).
// CHECK: destroy_addr [[CLOSURE_ADDR]] : $*@callee_guaranteed () -> ()
// CHECK: dealloc_stack [[BLOCK_STORAGE]] : $*@block_storage @callee_guaranteed () -> ()
// Release of closure copy (1).
// CHECK: strong_release %0 : $@callee_guaranteed () -> ()
// CHECK: [[METH:%.*]] = objc_method [[OE]] : $@opened("{{.*}}") DangerousEscaper, #DangerousEscaper.malicious!1.foreign : <Self where Self : DangerousEscaper> (Self) -> (() -> ()) -> (), $@convention(objc_method) <τ_0_0 where τ_0_0 : DangerousEscaper> (@convention(block) @noescape () -> (), τ_0_0) -> ()
// CHECK: apply [[METH]]<@opened("{{.*}}") DangerousEscaper>([[BLOCK_COPY]], [[OE]]) : $@convention(objc_method) <τ_0_0 where τ_0_0 : DangerousEscaper> (@convention(block) @noescape () -> (), τ_0_0) -> ()
// Release sentinel closure copy (5).
// CHECK: strong_release [[BLOCK_COPY]] : $@convention(block) @noescape () -> ()
// CHECK: [[ESCAPED:%.*]] = is_escaping_closure [objc] [[OPT_SENTINEL]] : $Optional<@callee_guaranteed () -> ()>
// CHECK: cond_fail [[ESCAPED]] : $Builtin.Int1
// Release of sentinel copy (4).
// CHECK: release_value [[OPT_SENTINEL]] : $Optional<@callee_guaranteed () -> ()>
// Extendend lifetime (2).
// CHECK: release_value [[OPT_CLOSURE]] : $Optional<@callee_guaranteed () -> ()>
// CHECK: return
public func couldActuallyEscape(_ closure: @escaping () -> (), _ villian: DangerousEscaper) {
villian.malicious(closure)
}
// We need to store nil on the back-edge.
// CHECK sil {{.*}}dontCrash
// CHECK: is_escaping_closure [objc]
// CHECK: cond_fail
// CHECK: destroy_addr %0
// CHECK: [[NONE:%.*]] = enum $Optional<@callee_guaranteed () -> ()>, #Optional.none!enumelt
// CHECK: store [[NONE]] to %0 : $*Optional<@callee_guaranteed () -> ()>
public func dontCrash() {
for i in 0 ..< 2 {
let queue = DispatchQueue(label: "Foo")
queue.sync { }
}
}
@_silgen_name("getDispatchQueue")
func getDispatchQueue() -> DispatchQueue
// We must not release the closure after calling super.deinit.
// CHECK: sil hidden @$s27closure_lifetime_fixup_objc1CCfD : $@convention(method) (@owned C) -> () {
// CHECK: bb0([[SELF:%.*]] : $C):
// CHECK: [[F:%.*]] = function_ref @$s27closure_lifetime_fixup_objc1CCfdyyXEfU_
// CHECK: [[PA:%.*]] = partial_apply [callee_guaranteed] [[F]]([[SELF]])
// CHECK: [[OPT:%.*]] = enum $Optional<@callee_guaranteed () -> ()>, #Optional.some!enumelt.1, [[PA]]
// CHECK: [[DEINIT:%.*]] = objc_super_method [[SELF]] : $C, #NSObject.deinit!deallocator.1.foreign
// CHECK: release_value [[OPT]] : $Optional<@callee_guaranteed () -> ()>
// CHECK: [[SUPER:%.*]] = upcast [[SELF]] : $C to $NSObject
// CHECK-NEXT: apply [[DEINIT]]([[SUPER]]) : $@convention(objc_method) (NSObject) -> ()
// CHECK-NEXT: [[T:%.*]] = tuple ()
// CHECK-NEXT: return [[T]] : $()
class C: NSObject {
deinit {
getDispatchQueue().sync(execute: { _ = self })
}
}
// Make sure that we obey ownership invariants when we emit load_borrow.
internal typealias MyBlock = @convention(block) () -> Void
func getBlock(noEscapeBlock: () -> Void ) -> MyBlock {
return block_create_noescape(noEscapeBlock)
}
| apache-2.0 | f1c41f6231b6f5c6ff33687c84752bbc | 52.954545 | 307 | 0.615164 | 3.47076 | false | false | false | false |
MarkQSchultz/NilLiterally | LiterallyNil.playground/Pages/Int & Bool.xcplaygroundpage/Contents.swift | 1 | 457 | //: [Next](@next)
//: ### Exercise: `Int`, `Bool`
extension Int: NilLiteralConvertible {
public init(nilLiteral: ()) {
print("hello")
self.init(0)
}
}
let i: Int = nil
let iIsNil = i == nil
extension Bool: NilLiteralConvertible {
public init(nilLiteral: ()) {
self.init(false)
}
}
let b: Bool = nil
let c = false
let d = b == c
//
let bIsNil = b == nil
if !nil {
}
//: [Previous](@previous)
| mit | f41a8d20a2e372a5b5bcf5c55dfaee69 | 9.155556 | 39 | 0.536105 | 3.28777 | false | false | false | false |
abelsanchezali/ViewBuilder | Source/Vector/Model/Path.swift | 1 | 1207 | //
// Path.swift
// ViewBuilder
//
// Created by Abel Sanchez on 10/8/16.
// Copyright © 2016 Abel Sanchez. All rights reserved.
//
import CoreGraphics
open class Path: NSObject {
public let path: CGPath
init(path: CGPath) {
self.path = path
}
init?(data: String) {
guard let path = VectorHelper.getPathFromSVGPathData(data: data) else {
Log.shared.write("Warning: Invalid path format")
return nil
}
self.path = path
}
}
extension Path: TextDeserializer {
public static func deserialize(text: String?, service: TextDeserializerServiceProtocol) -> Any? {
guard let text = text else {
Log.shared.write("Warning: Missing parameter")
return nil
}
if let data = service.parseKeyValueSequence(from: text, params: ["data"]), let value = data[0] as? String {
guard let path = VectorHelper.getPathFromSVGPathData(data: value) else {
Log.shared.write("Warning: Invalid path format")
return nil
}
return Path(path: path)
}
Log.shared.write("Warning: Invalid path")
return nil
}
}
| mit | 1177b3667d581fe4e5401447963a90c0 | 27.046512 | 115 | 0.594527 | 4.246479 | false | false | false | false |
bhajian/raspi-remote | Carthage/Checkouts/ios-sdk/Source/AlchemyLanguageV1/Models/Emotions.swift | 1 | 1482 | //
// Emotions.swift
// WatsonDeveloperCloud
//
// Created by Harrison Saylor on 5/26/16.
// Copyright © 2016 Glenn R. Fisher. All rights reserved.
//
import Foundation
import Freddy
/**
Emotions and their prevalence extracted from a document
*/
public struct Emotions: JSONDecodable {
/** amount of anger extracted */
public let anger: Double?
/** amount of disgust extracted */
public let disgust: Double?
/** amount of fear extracted */
public let fear: Double?
/** amount of joy extracted */
public let joy: Double?
/** amount of sadness extracted */
public let sadness: Double?
/// Used internally to initialize a Emotions object
public init(json: JSON) throws {
if let angerString = try? json.string("anger") {
anger = Double(angerString)
} else {
anger = nil
}
if let disgustString = try? json.string("disgust") {
disgust = Double(disgustString)
} else {
disgust = nil
}
if let fearString = try? json.string("fear") {
fear = Double(fearString)
} else {
fear = nil
}
if let joyString = try? json.string("joy") {
joy = Double(joyString)
} else {
joy = nil
}
if let sadnessString = try? json.string("sadness") {
sadness = Double(sadnessString)
} else {
sadness = nil
}
}
} | mit | 3f0c8dab053f6027efe3bcab318576aa | 25.945455 | 60 | 0.564483 | 4.195467 | false | false | false | false |
HabitRPG/habitrpg-ios | HabitRPG/Views/ChallengeDetailAlert.swift | 1 | 3392 | //
// ChallengeDetailAlert.swift
// Habitica
//
// Created by Phillip Thelen on 04/03/2017.
// Copyright © 2017 HabitRPG Inc. All rights reserved.
//
import UIKit
import Down
import Habitica_Models
class ChallengeDetailAlert: UIViewController {
@IBOutlet weak private var nameLabel: UILabel!
@IBOutlet weak private var notesLabel: UITextView!
@IBOutlet weak private var ownerLabel: UILabel!
@IBOutlet weak private var gemLabel: UILabel!
@IBOutlet weak private var memberCountLabel: UILabel!
@IBOutlet weak private var joinLeaveButton: UIButton!
@IBOutlet weak private var heightConstraint: NSLayoutConstraint!
@IBOutlet weak private var habitsList: ChallengeTaskListView!
@IBOutlet weak private var dailiesList: ChallengeTaskListView!
@IBOutlet weak private var todosList: ChallengeTaskListView!
@IBOutlet weak private var rewardsList: ChallengeTaskListView!
var joinLeaveAction: ((Bool) -> Void)?
var challenge: ChallengeProtocol? {
didSet {
if let challenge = self.challenge {
configure(challenge)
}
}
}
var isMember: Bool = false {
didSet {
if !viewIsLoaded {
return
}
if isMember {
joinLeaveButton.setTitle(L10n.leave, for: .normal)
joinLeaveButton.setTitleColor(.red100, for: .normal)
} else {
joinLeaveButton.setTitle(L10n.join, for: .normal)
joinLeaveButton.setTitleColor(.green100, for: .normal)
}
}
}
private var viewIsLoaded = false
override func viewDidLoad() {
super.viewDidLoad()
viewIsLoaded = true
if let challenge = self.challenge {
configure(challenge)
}
}
override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
if let window = self.view.window {
self.heightConstraint.constant = window.frame.size.height - 200
}
}
private func configure(_ challenge: ChallengeProtocol, showTasks: Bool = true) {
if !viewIsLoaded {
return
}
nameLabel.text = challenge.name?.unicodeEmoji
if let notes = challenge.notes {
let markdownString = try? Down(markdownString: notes.unicodeEmoji).toHabiticaAttributedString()
notesLabel.attributedText = markdownString
}
ownerLabel.text = challenge.leaderName?.unicodeEmoji
gemLabel.text = String(challenge.prize)
memberCountLabel.text = String(challenge.memberCount)
//isMember = challenge.user != nil
habitsList.configure(tasks: challenge.habits.sorted(by: { (first, second) -> Bool in
first.order < second.order
}))
dailiesList.configure(tasks: challenge.dailies.sorted(by: { (first, second) -> Bool in
first.order < second.order
}))
todosList.configure(tasks: challenge.todos.sorted(by: { (first, second) -> Bool in
first.order < second.order
}))
rewardsList.configure(tasks: challenge.rewards.sorted(by: { (first, second) -> Bool in
first.order < second.order
}))
}
@IBAction func joinLeaveTapped(_ sender: Any) {
if let action = joinLeaveAction {
action(!isMember)
}
}
}
| gpl-3.0 | 798cdf575d6e649d6714973e10ec6f41 | 31.92233 | 107 | 0.628723 | 4.651578 | false | true | false | false |
milseman/swift | stdlib/public/core/StringBuffer.swift | 9 | 6545 | //===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
@_versioned
struct _StringBufferIVars {
internal init(_elementWidth: Int) {
_sanityCheck(_elementWidth == 1 || _elementWidth == 2)
usedEnd = nil
capacityAndElementShift = _elementWidth - 1
}
internal init(
_usedEnd: UnsafeMutableRawPointer,
byteCapacity: Int,
elementWidth: Int
) {
_sanityCheck(elementWidth == 1 || elementWidth == 2)
_sanityCheck((byteCapacity & 0x1) == 0)
self.usedEnd = _usedEnd
self.capacityAndElementShift = byteCapacity + (elementWidth - 1)
}
// This stored property should be stored at offset zero. We perform atomic
// operations on it using _HeapBuffer's pointer.
var usedEnd: UnsafeMutableRawPointer?
var capacityAndElementShift: Int
var byteCapacity: Int {
return capacityAndElementShift & ~0x1
}
var elementShift: Int {
return capacityAndElementShift & 0x1
}
}
// FIXME: Wanted this to be a subclass of
// _HeapBuffer<_StringBufferIVars, UTF16.CodeUnit>, but
// <rdar://problem/15520519> (Can't call static method of derived
// class of generic class with dependent argument type) prevents it.
public struct _StringBuffer {
// Make this a buffer of UTF-16 code units so that it's properly
// aligned for them if that's what we store.
typealias _Storage = _HeapBuffer<_StringBufferIVars, UTF16.CodeUnit>
typealias HeapBufferStorage
= _HeapBufferStorage<_StringBufferIVars, UTF16.CodeUnit>
init(_ storage: _Storage) {
_storage = storage
}
public init(capacity: Int, initialSize: Int, elementWidth: Int) {
_sanityCheck(elementWidth == 1 || elementWidth == 2)
_sanityCheck(initialSize <= capacity)
// We don't check for elementWidth overflow and underflow because
// elementWidth is known to be 1 or 2.
let elementShift = elementWidth &- 1
// We need at least 1 extra byte if we're storing 8-bit elements,
// because indexing will always grab 2 consecutive bytes at a
// time.
let capacityBump = 1 &- elementShift
// Used to round capacity up to nearest multiple of 16 bits, the
// element size of our storage.
let divRound = 1 &- elementShift
_storage = _Storage(
HeapBufferStorage.self,
_StringBufferIVars(_elementWidth: elementWidth),
(capacity + capacityBump + divRound) &>> divRound
)
// This conditional branch should fold away during code gen.
if elementShift == 0 {
start.bindMemory(to: UTF8.CodeUnit.self, capacity: initialSize)
}
else {
start.bindMemory(to: UTF16.CodeUnit.self, capacity: initialSize)
}
self.usedEnd = start + (initialSize &<< elementShift)
_storage.value.capacityAndElementShift
= ((_storage.capacity - capacityBump) &<< 1) + elementShift
}
static func fromCodeUnits<Input : Sequence, Encoding : _UnicodeEncoding>(
_ input: Input, encoding: Encoding.Type, repairIllFormedSequences: Bool,
minimumCapacity: Int = 0
) -> (_StringBuffer?, hadError: Bool)
where Input.Element == Encoding.CodeUnit {
// Determine how many UTF-16 code units we'll need
let inputStream = input.makeIterator()
guard let (utf16Count, isAscii) = UTF16.transcodedLength(
of: inputStream,
decodedAs: encoding,
repairingIllFormedSequences: repairIllFormedSequences) else {
return (nil, true)
}
// Allocate storage
let result = _StringBuffer(
capacity: max(utf16Count, minimumCapacity),
initialSize: utf16Count,
elementWidth: isAscii ? 1 : 2)
if isAscii {
var p = result.start.assumingMemoryBound(to: UTF8.CodeUnit.self)
let sink: (UTF32.CodeUnit) -> Void = {
p.pointee = UTF8.CodeUnit($0)
p += 1
}
let hadError = transcode(
input.makeIterator(),
from: encoding, to: UTF32.self,
stoppingOnError: true,
into: sink)
_sanityCheck(!hadError, "string cannot be ASCII if there were decoding errors")
return (result, hadError)
}
else {
var p = result._storage.baseAddress
let sink: (UTF16.CodeUnit) -> Void = {
p.pointee = $0
p += 1
}
let hadError = transcode(
input.makeIterator(),
from: encoding, to: UTF16.self,
stoppingOnError: !repairIllFormedSequences,
into: sink)
return (result, hadError)
}
}
/// A pointer to the start of this buffer's data area.
public // @testable
var start: UnsafeMutableRawPointer {
return UnsafeMutableRawPointer(_storage.baseAddress)
}
/// A past-the-end pointer for this buffer's stored data.
var usedEnd: UnsafeMutableRawPointer {
get {
return _storage.value.usedEnd!
}
set(newValue) {
_storage.value.usedEnd = newValue
}
}
var usedCount: Int {
return (usedEnd - start) &>> elementShift
}
/// A past-the-end pointer for this buffer's available storage.
var capacityEnd: UnsafeMutableRawPointer {
return start + _storage.value.byteCapacity
}
/// The number of elements that can be stored in this buffer.
public var capacity: Int {
return _storage.value.byteCapacity &>> elementShift
}
/// 1 if the buffer stores UTF-16; 0 otherwise.
var elementShift: Int {
return _storage.value.elementShift
}
/// The number of bytes per element.
var elementWidth: Int {
return elementShift + 1
}
// Return `true` iff we have the given capacity for the indicated
// substring. This is what we need to do so that users can call
// reserveCapacity on String and subsequently use that capacity, in
// two separate phases. Operations with one-phase growth should use
// "grow()," below.
func hasCapacity(
_ cap: Int, forSubRange r: Range<UnsafeRawPointer>
) -> Bool {
// The substring to be grown could be pointing in the middle of this
// _StringBuffer.
let offset = (r.lowerBound - UnsafeRawPointer(start)) &>> elementShift
return cap + offset <= capacity
}
var _anyObject: AnyObject? {
return _storage.storage
}
var _storage: _Storage
}
| apache-2.0 | f05a71f304ecaccec4791e3b39f446bf | 31.40099 | 85 | 0.658976 | 4.501376 | false | false | false | false |
overtake/TelegramSwift | Telegram-Mac/LottieBufferCompressor.swift | 1 | 15114 | //
// BufferCompressor.swift
// Telegram
//
// Created by Mikhail Filimonov on 19/06/2019.
// Copyright © 2019 Telegram. All rights reserved.
//
import Cocoa
import Compression
import Accelerate
import Postbox
import SwiftSignalKit
import TGUIKit
import ApiCredentials
private let enableDifference = true
private let maxFrameBufferSizeCache = 7200
private enum WriteResult {
case success
case failed
}
private enum ReadResult {
case success(Data)
case cached(Data, ()->Void)
case failed
}
private var sharedData:Atomic<[LottieAnimationEntryKey:WeakReference<TRLotData>]> = Atomic(value: [:])
private struct FrameDst : Codable {
let offset: Int
let length: Int
let finished: Bool
init(offset: Int, length: Int, finished: Bool) {
self.offset = offset
self.length = length
self.finished = finished
}
}
private struct DstData : Codable {
var dest: [Int : FrameDst]
var fps: Int32
var startFrame: Int32
var endFrame: Int32
}
private let version = 65
final class TRLotData {
fileprivate var map:DstData
fileprivate let bufferSize: Int
private let mapPath: String
private let dataPath: String
var isFinished: Bool = false {
didSet {
assert(queue.isCurrent())
let cpy = map
for (key, value) in cpy.dest {
map.dest[key] = .init(offset: value.offset, length: value.length, finished: isFinished)
}
}
}
private var readHandle: FileHandle?
private var writeHandle: FileHandle?
private let key: LottieAnimationEntryKey
fileprivate let queue: Queue
fileprivate func hasAlreadyFrame(_ frame: Int) -> Bool {
assert(queue.isCurrent())
return map.dest[frame] != nil
}
fileprivate func readFrame(frame: Int) -> ReadResult {
self.writeHandle?.closeFile()
self.writeHandle = nil
assert(queue.isCurrent())
if !isFinished {
return .failed
}
if let dest = map.dest[frame] {
let readHande: FileHandle?
if let handle = self.readHandle {
readHande = handle
} else {
readHande = FileHandle(forReadingAtPath: self.dataPath)
self.readHandle = readHande
}
guard let dataHandle = readHande else {
self.map.dest.removeAll()
return .failed
}
dataHandle.seek(toFileOffset: UInt64(dest.offset))
let data = dataHandle.readData(ofLength: dest.length)
if data.count == dest.length {
return .success(data)
} else {
self.map.dest.removeValue(forKey: frame)
return .failed
}
}
return .failed
}
deinit {
queue.sync {
self.readHandle?.closeFile()
self.writeHandle?.closeFile()
let data = try? PropertyListEncoder().encode(self.map)
if let data = data {
_ = NSKeyedArchiver.archiveRootObject(data, toFile: self.mapPath)
}
}
_ = sharedData.modify { value in
var value = value
value.removeValue(forKey: self.key)
return value
}
}
fileprivate func writeFrame(frame: Int, data:Data) -> WriteResult {
self.readHandle?.closeFile()
self.readHandle = nil
assert(queue.isCurrent())
if map.dest[frame] == nil {
let writeHandle: FileHandle?
if let handle = self.writeHandle {
writeHandle = handle
} else {
writeHandle = FileHandle(forWritingAtPath: self.dataPath)
self.writeHandle = writeHandle
}
guard let dataHandle = writeHandle else {
return .failed
}
let length = dataHandle.seekToEndOfFile()
dataHandle.write(data)
var frames = self.map.dest
frames[frame] = FrameDst(offset: Int(length), length: data.count, finished: isFinished)
self.map = DstData(dest: frames, fps: self.map.fps, startFrame: self.map.startFrame, endFrame: self.map.endFrame)
}
return .success
}
fileprivate static var directory: String {
let groupPath = ApiEnvironment.containerURL!.path
let path = groupPath + "/trlottie-animations/"
try? FileManager.default.createDirectory(atPath: path, withIntermediateDirectories: true, attributes: nil)
return path
}
static func mapPath(_ animation: LottieAnimation, bufferSize: Int) -> String {
let path = TRLotData.directory + animation.cacheKey
return path + "-v\(version)-lzfse-bs\(bufferSize)-lt\(animation.liveTime)-map"
}
static func dataPath(_ animation: LottieAnimation, bufferSize: Int) -> String {
let path = TRLotData.directory + animation.cacheKey
return path + "-v\(version)-lzfse-bs\(bufferSize)-lt\(animation.liveTime)-data"
}
init(_ animation: LottieAnimation, bufferSize: Int, queue: Queue) {
self.queue = queue
self.mapPath = TRLotData.mapPath(animation, bufferSize: bufferSize)
self.dataPath = TRLotData.dataPath(animation, bufferSize: bufferSize)
self.key = animation.key
var mapHandle:FileHandle?
let deferr:(TRLotData)->Void = { data in
if !FileManager.default.fileExists(atPath: data.mapPath) {
FileManager.default.createFile(atPath: data.mapPath, contents: nil, attributes: nil)
}
if !FileManager.default.fileExists(atPath: data.dataPath) {
FileManager.default.createFile(atPath: data.dataPath, contents: nil, attributes: nil)
}
try? FileManager.default.setAttributes([.modificationDate : Date()], ofItemAtPath: data.mapPath)
try? FileManager.default.setAttributes([.modificationDate : Date()], ofItemAtPath: data.dataPath)
_ = sharedData.modify { value in
var value = value
value[data.key] = WeakReference(value: data)
return value
}
mapHandle?.closeFile()
}
guard let handle = FileHandle(forReadingAtPath: self.mapPath) else {
self.map = .init(dest: [:], fps: 0, startFrame: 0, endFrame: 0)
self.bufferSize = bufferSize
deferr(self)
return
}
mapHandle = handle
guard let data = NSKeyedUnarchiver.unarchiveObject(withFile: self.mapPath) as? Data else {
self.map = .init(dest: [:], fps: 0, startFrame: 0, endFrame: 0)
self.bufferSize = bufferSize
deferr(self)
return
}
do {
self.map = try PropertyListDecoder().decode(DstData.self, from: data)
self.bufferSize = bufferSize
deferr(self)
} catch {
self.map = .init(dest: [:], fps: 0, startFrame: 0, endFrame: 0)
self.bufferSize = bufferSize
deferr(self)
}
if !self.map.dest.isEmpty {
self.isFinished = self.map.dest.filter { $0.value.finished }.count == self.map.dest.count
} else {
self.isFinished = false
}
}
func initialize(fps: Int32, startFrame: Int32, endFrame: Int32) {
self.map.fps = fps
self.map.startFrame = startFrame
self.map.endFrame = endFrame
}
}
private let lzfseQueue = Queue(name: "LZFSE BUFFER Queue", qos: DispatchQoS.default)
final class TRLotFileSupplyment {
fileprivate let bufferSize: Int
fileprivate let data:TRLotData
fileprivate let queue: Queue
init(_ animation:LottieAnimation, bufferSize: Int, queue: Queue) {
let cached = sharedData.with { $0[animation.key]?.value }
let queue = cached?.queue ?? queue
self.data = cached ?? TRLotData(animation, bufferSize: bufferSize, queue: queue)
self.queue = queue
self.bufferSize = bufferSize
}
func initialize(fps: Int32, startFrame: Int32, endFrame: Int32) {
queue.sync {
self.data.initialize(fps: fps, startFrame: startFrame, endFrame: endFrame)
}
}
var fps: Int32 {
var fps: Int32 = 0
queue.sync {
fps = self.data.map.fps
}
return fps
}
var endFrame: Int32 {
var endFrame: Int32 = 0
queue.sync {
endFrame = self.data.map.endFrame
}
return endFrame
}
var startFrame: Int32 {
var startFrame: Int32 = 0
queue.sync {
startFrame = self.data.map.startFrame
}
return startFrame
}
func markFinished() {
queue.async {
self.data.isFinished = true
}
}
var isFinished: Bool {
var isFinished: Bool = false
queue.sync {
isFinished = self.data.isFinished
}
return isFinished
}
func addFrame(_ previous: Data?, _ current: (Data, Int32)) {
queue.async {
if !self.data.hasAlreadyFrame(Int(current.1)) {
current.0.withUnsafeBytes { pointer in
let address = pointer.baseAddress!.assumingMemoryBound(to: UInt8.self)
let ui64Address = pointer.baseAddress!.assumingMemoryBound(to: UInt64.self)
let dst: UnsafeMutablePointer<UInt8> = malloc(self.bufferSize)!.assumingMemoryBound(to: UInt8.self)
var length:Int = self.bufferSize
if let previous = previous, enableDifference {
let uint64Bs = self.bufferSize / 8
let dstDelta: UnsafeMutablePointer<UInt8> = malloc(self.bufferSize)!.assumingMemoryBound(to: UInt8.self)
previous.withUnsafeBytes { pointer in
memcpy(dstDelta, pointer.baseAddress!.assumingMemoryBound(to: UInt8.self), self.bufferSize)
let ui64Dst = dstDelta.withMemoryRebound(to: UInt64.self, capacity: uint64Bs, { previousBytes in
return previousBytes
})
var i: Int = 0
while i < uint64Bs {
ui64Dst[i] = ui64Dst[i] ^ ui64Address[i]
i &+= 1
}
let ui8 = ui64Dst.withMemoryRebound(to: UInt8.self, capacity: self.bufferSize, { body in
return body
})
length = compression_encode_buffer(dst, self.bufferSize, ui8, self.bufferSize, nil, COMPRESSION_LZFSE)
dstDelta.deallocate()
}
} else {
length = compression_encode_buffer(dst, self.bufferSize, address, self.bufferSize, nil, COMPRESSION_LZFSE)
}
let _ = self.data.writeFrame(frame: Int(current.1), data: Data(bytes: dst, count: length))
dst.deallocate()
}
}
}
}
func readFrame(previous: Data?, frame: Int) -> Data? {
var rendered: Data? = nil
queue.sync {
if self.data.isFinished {
switch self.data.readFrame(frame: frame) {
case let .success(data):
let address = malloc(bufferSize)!.assumingMemoryBound(to: UInt8.self)
data.withUnsafeBytes { dataBytes in
let unsafeBufferPointer = dataBytes.bindMemory(to: UInt8.self)
let unsafePointer = unsafeBufferPointer.baseAddress!
let _ = compression_decode_buffer(address, bufferSize, unsafePointer, data.count, nil, COMPRESSION_LZFSE)
if let previous = previous, enableDifference {
previous.withUnsafeBytes { pointer in
let previousBytes = pointer.baseAddress!.assumingMemoryBound(to: UInt64.self)
let uint64Bs = self.bufferSize / 8
address.withMemoryRebound(to: UInt64.self, capacity: uint64Bs, { address in
var i = 0
while i < uint64Bs {
address[i] = previousBytes[i] ^ address[i]
i &+= 1
}
})
}
}
}
rendered = Data(bytes: address, count: bufferSize)
address.deallocate()
default:
rendered = nil
}
}
}
return rendered
}
}
private final class CacheRemovable {
init() {
}
fileprivate func start() {
let signal = Signal<Void, NoError>.single(Void()) |> deliverOn(lzfseQueue) |> then (Signal<Void, NoError>.single(Void()) |> delay(30 * 60, queue: lzfseQueue) |> restart)
_ = signal.start(next: {
self.clean()
})
}
private func clean() {
let fileURLs = try? FileManager.default.contentsOfDirectory(at: URL(fileURLWithPath: TRLotData.directory), includingPropertiesForKeys: nil, options: .skipsHiddenFiles )
if let fileURLs = fileURLs {
for url in fileURLs {
let path = url.path
let name = path.nsstring.lastPathComponent
if let index = name.range(of: "lt") {
let tail = String(name[index.upperBound...])
if let until = tail.range(of: "-") {
if let liveTime = TimeInterval(tail[..<until.lowerBound]) {
if let createdAt = FileManager.default.modificationDateForFileAtPath(path: path), createdAt.timeIntervalSince1970 + liveTime < Date().timeIntervalSince1970 {
try? FileManager.default.removeItem(at: url)
}
continue
}
}
}
try? FileManager.default.removeItem(at: url)
}
}
}
}
private let cleaner = CacheRemovable()
func startLottieCacheCleaner() {
cleaner.start()
}
| gpl-2.0 | ac5e61088089c6b602885505ddd10054 | 33.192308 | 185 | 0.534308 | 4.964849 | false | false | false | false |
danielsaidi/iExtra | iExtra/UI/Extensions/UIDevice/UIDevice+SystemVersion.swift | 1 | 996 | //
// UIDevice+SystemVersion.swift
// iExtra
//
// Created by Daniel Saidi on 2017-12-07.
// Copyright © 2018 Daniel Saidi. All rights reserved.
//
import UIKit
public extension UIDevice {
var normalizedSystemVersion: String {
return normalizeSystemVersion(systemVersion)
}
func normalizeSystemVersion(_ version: String) -> String {
let components = version.components(separatedBy: ".")
let dotCount = components.count - 1
switch dotCount {
case 0: return "\(version).0.0"
case 1: return "\(version).0"
default: return version
}
}
func systemVersion(isAtLeast version: String) -> Bool {
let systemVersion = normalizedSystemVersion
let compare = systemVersion.compare(version, options: .numeric)
return compare != .orderedAscending
}
func systemVersion(isLessThan version: String) -> Bool {
return !systemVersion(isAtLeast: version)
}
}
| mit | c62538ea71f530d123a828b28e42a0ad | 25.891892 | 71 | 0.640201 | 4.693396 | false | false | false | false |
panyam/SwiftHTTP | Sources/Core/HttpStatusCode.swift | 2 | 3649 | //
// HttpStatusCode.swift
// SwiftHTTP
//
// Created by Sriram Panyam on 12/27/15.
// Copyright © 2015 Sriram Panyam. All rights reserved.
//
import Foundation
public enum HttpStatusCode : Int
{
case Continue = 100
case SwitchingProtocols = 101
case Ok = 200
case Created = 201
case Accepted = 202
case NonAuthoritativeInformation = 203
case NoContent = 204
case ResetContent = 205
case PartialContent = 206
case MultipleChoices = 300
case MovedPermanently = 301
case Found = 302
case SeeOther = 303
case NotModified = 304
case UseProxy = 305
case TemporaryRedirect = 307
case BadRequest = 400
case Unauthorized = 401
case PaymentRequired = 402
case Forbidden = 403
case NotFound = 404
case MethodNotAllowed = 405
case NotAcceptable = 406
case ProxyAuthenticationRequired = 407
case RequestTimeout = 408
case Conflict = 409
case Gone = 410
case LengthRequired = 411
case PerconditionFailed = 412
case RequestEntityTooLarge = 413
case RequestURITooLong = 414
case UnsupportedMediaType = 415
case RequestRangeNotSatisfiable = 416
case ExpectationFailed = 417
case InternalServerError = 500
case NotImplemented = 501
case BadGateway = 502
case ServiceUnavailable = 503
case GatewayTimeout = 504
case HTTPVersionNotSupported = 505
}
extension HttpStatusCode
{
static let reasonPhrases : [Int : String] = [
Continue.rawValue: "Continue",
SwitchingProtocols.rawValue: "SwitchingProtocols",
Ok.rawValue: "Ok",
Created.rawValue: "Created",
Accepted.rawValue: "Accepted",
NonAuthoritativeInformation.rawValue: "NonAuthoritativeInformation",
NoContent.rawValue: "NoContent",
ResetContent.rawValue: "ResetContent",
PartialContent.rawValue: "PartialContent",
MultipleChoices.rawValue: "MultipleChoices",
MovedPermanently.rawValue: "MovedPermanently",
Found.rawValue: "Found",
SeeOther.rawValue: "SeeOther",
NotModified.rawValue: "NotModified",
UseProxy.rawValue: "UseProxy",
TemporaryRedirect.rawValue: "TemporaryRedirect",
BadRequest.rawValue: "BadRequest",
Unauthorized.rawValue: "Unauthorized",
PaymentRequired.rawValue: "PaymentRequired",
Forbidden.rawValue: "Forbidden",
NotFound.rawValue: "NotFound",
MethodNotAllowed.rawValue: "MethodNotAllowed",
NotAcceptable.rawValue: "NotAcceptable",
ProxyAuthenticationRequired.rawValue: "ProxyAuthenticationRequired",
RequestTimeout.rawValue: "RequestTimeout",
Conflict.rawValue: "Conflict",
Gone.rawValue: "Gone",
LengthRequired.rawValue: "LengthRequired",
PerconditionFailed.rawValue: "PerconditionFailed",
RequestEntityTooLarge.rawValue: "RequestEntityTooLarge",
RequestURITooLong.rawValue: "RequestURITooLong",
UnsupportedMediaType.rawValue: "UnsupportedMediaType",
RequestRangeNotSatisfiable.rawValue: "RequestRangeNotSatisfiable",
ExpectationFailed.rawValue: "ExpectationFailed",
InternalServerError.rawValue: "InternalServerError",
NotImplemented.rawValue: "NotImplemented",
BadGateway.rawValue: "BadGateway",
ServiceUnavailable.rawValue: "ServiceUnavailable",
GatewayTimeout.rawValue: "GatewayTimeout",
HTTPVersionNotSupported.rawValue: "HTTPVersionNotSupported"
]
public func reasonPhrase() -> String?
{
return HttpStatusCode.reasonPhrases[self.rawValue]
}
}
| apache-2.0 | ec584b16e012911b95eff5dbf22181f7 | 31.283186 | 76 | 0.69216 | 4.976808 | false | false | false | false |
xsunsmile/TwitterApp | Twitter/MainViewController.swift | 1 | 8598 | //
// MainViewController.swift
// Twitter
//
// Created by Hao Sun on 2/26/15.
// Copyright (c) 2015 Hao Sun. All rights reserved.
//
import UIKit
class MainViewController: UIViewController,
MenuDelegate,
AccountSwitch
{
var storyBoard = UIStoryboard(name: "Main", bundle: nil)
var viewInContainer = "HomeTimelineNav"
var homeTimelineNavVC: UINavigationController?
var burgerNavVC: UINavigationController?
var profileNavVC: UINavigationController?
var metionsNavVC: UINavigationController?
var accountNavVC: UINavigationController?
var menuIsOpen = false
var dragBeganPointX: CGFloat?
@IBOutlet weak var containerView: UIView!
@IBOutlet weak var menuView: UIView!
override func viewDidLoad() {
super.viewDidLoad()
applyPlainShadow(containerView)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "userDidLogout", name: userDidLogoutNotification, object: nil)
initMenuView()
initTimelineView()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func applyPlainShadow(view: UIView) {
var layer = view.layer
layer.shadowColor = UIColor.blackColor().CGColor
layer.shadowOpacity = 0.4
layer.shadowRadius = 2
}
func initMenuView() {
burgerNavVC = storyBoard.instantiateViewControllerWithIdentifier("BergerViewNav") as? UINavigationController
let burgerVC = burgerNavVC?.childViewControllers[0] as BergerViewController
burgerVC.delegate = self
initViewController(menuView, controller: burgerNavVC!)
}
func initAccountView() {
if accountNavVC == nil {
accountNavVC = storyBoard.instantiateViewControllerWithIdentifier("AccountNavView") as? UINavigationController
let accountVC = accountNavVC?.childViewControllers[0] as AccountViewController
accountVC.delegate = self
}
}
func initTimelineView() {
removeSubviewFromContainer()
viewInContainer = "HomeTimelineNav"
homeTimelineNavVC = storyBoard.instantiateViewControllerWithIdentifier("HomeTimelineNav") as? UINavigationController
initViewController(containerView, controller: homeTimelineNavVC!)
}
func initProfileView() {
removeSubviewFromContainer()
viewInContainer = "ProfileNavController"
profileNavVC = storyBoard.instantiateViewControllerWithIdentifier("ProfileNavController") as? UINavigationController
initViewController(containerView, controller: profileNavVC!)
}
func initMetionsView() {
removeSubviewFromContainer()
viewInContainer = "MentionsNavController"
metionsNavVC = storyBoard.instantiateViewControllerWithIdentifier("MentionsNavController") as? UINavigationController
initViewController(containerView, controller: metionsNavVC!)
}
func initViewController(container: UIView, controller: UIViewController) {
addChildViewController(controller)
controller.view.frame = container.bounds
container.addSubview(controller.view)
controller.didMoveToParentViewController(self)
}
@IBAction func onContainerViewDrag(sender: UIPanGestureRecognizer) {
let point = sender.locationInView(view)
let velocity = sender.velocityInView(view)
if velocity.x > 0 && !menuIsOpen {
if sender.state == .Began {
dragBeganPointX = point.x
} else if sender.state == .Changed {
UIView.animateWithDuration(1, animations: { () -> Void in
self.containerView.transform = CGAffineTransformMakeTranslation(point.x - self.dragBeganPointX!, 0)
})
} else if sender.state == .Ended {
openMenu()
}
} else if velocity.x < 0 && menuIsOpen {
if sender.state == .Began {
dragBeganPointX = point.x
} else if sender.state == .Changed {
UIView.animateWithDuration(1, animations: { () -> Void in
self.containerView.transform = CGAffineTransformMakeTranslation(point.x - self.dragBeganPointX!, 0)
})
} else if sender.state == .Ended {
closeMenu()
}
}
}
func closeMenu() {
UIView.animateWithDuration(1, animations: { () -> Void in
self.menuView.alpha = 0
self.containerView.transform = CGAffineTransformIdentity
})
self.menuIsOpen = false
}
func openMenu() {
UIView.animateWithDuration(1, animations: { () -> Void in
self.menuView.alpha = 1
self.containerView.transform = CGAffineTransformMakeTranslation(250, 0)
})
self.menuIsOpen = true
}
func removeSubviewFromContainer() {
switch(viewInContainer) {
case "HomeTimelineNav":
if homeTimelineNavVC != nil {
removeVC(homeTimelineNavVC!)
}
break
case "ProfileNavController":
if profileNavVC != nil {
removeVC(profileNavVC!)
}
break
case "MentionsNavController":
if metionsNavVC != nil {
removeVC(metionsNavVC!)
}
break
default:
println()
}
}
func removeVC(vc: UIViewController) {
vc.willMoveToParentViewController(nil)
vc.view.removeFromSuperview()
vc.removeFromParentViewController()
}
func onProfileImageTouched() {
closeMenu()
initProfileView()
}
func onMenuItemSelected(index: NSInteger) {
switch(index) {
case 0:
closeMenu()
initTimelineView()
break
case 1:
closeMenu()
initMetionsView()
break
default:
println()
}
}
func onUserSwitch() {
initAccountView()
let views = (frontView: burgerNavVC, backView: accountNavVC)
let transitionOptions = UIViewAnimationOptions.TransitionCurlUp
UIView.transitionWithView(menuView, duration: 1.0, options: transitionOptions, animations: {
self.removeVC(views.frontView!)
self.initViewController(self.menuView, controller: views.backView!)
}, completion: { finished in
// any code entered here will be applied
// .once the animation has completed
})
}
func switchAccount(user: User) {
println("switch account called for user \(user.name())")
User.currentUser = user
let token = user.getAccessToken()
println("switch to new token \(token.token)")
TwitterClient.sharedInstance.requestSerializer.removeAccessToken()
TwitterClient.sharedInstance.requestSerializer.saveAccessToken(token)
let views = (backView: burgerNavVC, frontView: accountNavVC)
let transitionOptions = UIViewAnimationOptions.TransitionCurlUp
UIView.transitionWithView(menuView, duration: 1.0, options: transitionOptions, animations: {
let nvc = views.frontView as UINavigationController?
let avc = nvc!.childViewControllers[0] as AccountViewController
avc.refresh()
self.removeVC(views.frontView!)
var vc = views.backView as UINavigationController?
let bvc = vc!.childViewControllers[0] as BergerViewController
bvc.refreshUserInfo()
self.initViewController(self.menuView, controller: views.backView!)
}, completion: { finished in
// any code entered here will be applied
// .once the animation has completed
self.initTimelineView()
})
}
func userDidLogout() {
if User.currentUser != nil {
onUserSwitch()
}
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| apache-2.0 | 06ae28201f7c02bacc6a3e52b7ed4d75 | 33.669355 | 135 | 0.620028 | 5.583117 | false | false | false | false |
calkinssean/woodshopBMX | WoodshopBMX/Pods/Charts/Charts/Classes/Highlight/CombinedHighlighter.swift | 7 | 2038 | //
// CombinedHighlighter.swift
// Charts
//
// Created by Daniel Cohen Gindi on 26/7/15.
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/ios-charts
//
import Foundation
import CoreGraphics
public class CombinedHighlighter: ChartHighlighter
{
/// Returns a list of SelectionDetail object corresponding to the given xIndex.
/// - parameter xIndex:
/// - returns:
public override func getSelectionDetailsAtIndex(xIndex: Int) -> [ChartSelectionDetail]
{
var vals = [ChartSelectionDetail]()
if let data = self.chart?.data as? CombinedChartData
{
// get all chartdata objects
var dataObjects = data.allData
var pt = CGPoint()
for i in 0 ..< dataObjects.count
{
for j in 0 ..< dataObjects[i].dataSetCount
{
let dataSet = dataObjects[i].getDataSetByIndex(j)
// dont include datasets that cannot be highlighted
if !dataSet.isHighlightEnabled
{
continue
}
// extract all y-values from all DataSets at the given x-index
let yVal = dataSet.yValForXIndex(xIndex)
if yVal.isNaN
{
continue
}
pt.y = CGFloat(yVal)
self.chart!.getTransformer(dataSet.axisDependency).pointValueToPixel(&pt)
if !pt.y.isNaN
{
vals.append(ChartSelectionDetail(value: Double(pt.y), dataSetIndex: j, dataSet: dataSet))
}
}
}
}
return vals
}
}
| apache-2.0 | e75139d6600bf9bac8d4f4474f5324dd | 29.41791 | 113 | 0.489696 | 5.724719 | false | false | false | false |
manfengjun/KYMart | Section/LogAndReg/Controller/SJBRegisterViewController.swift | 1 | 5221 | //
// RegisterViewController.swift
// HNLYSJB
//
// Created by jun on 2017/6/2.
// Copyright © 2017年 JUN. All rights reserved.
//
import UIKit
import ReactiveCocoa
import ReactiveSwift
import Result
import IQKeyboardManagerSwift
class SJBRegisterViewController: BaseViewController {
@IBOutlet weak var textView: UIView!
@IBOutlet weak var phoneT: UITextField!
@IBOutlet weak var cardT: UITextField!
@IBOutlet weak var passwordT: UITextField!
@IBOutlet weak var repassT: UITextField!
@IBOutlet weak var verCodeBtn: UIButton!
@IBOutlet weak var regBtn: UIButton!
var isReg = false
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
IQKeyboardManager.sharedManager().enable = true
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillAppear(animated)
IQKeyboardManager.sharedManager().enable = false
}
override func viewDidLoad() {
super.viewDidLoad()
setupUI()
validated()
verCodeBtn.reactive.controlEvents(.touchUpInside).observeValues { (button) in
button.isUserInteractionEnabled = false
self.regCodeHandle()
}
}
func setupUI() {
self.title = "注册"
regBtn.layer.masksToBounds = true
regBtn.layer.cornerRadius = 5
textView.layer.masksToBounds = true
textView.layer.cornerRadius = 5
setLeftButtonInNav(imageUrl: "nav_back.png", action: #selector(back))
}
func regCodeHandle() {
SJBRequestModel.pull_fetchVerifyCodeData { (response, status) in
self.verCodeBtn.isUserInteractionEnabled = true
if status == 1 {
let verifycode = response as! String
SingleManager.instance.verify_code = verifycode
let account = self.phoneT.text
SJBRequestModel.push_fetchRegVerifyCodeData(phone: account!, code: verifycode, completion: { (response, status) in
if status == 1{
let countDown = SJBCountDown(button: self.verCodeBtn)
countDown.isCounting = true
}
})
}
}
}
func regHandle() {
let verifycode = SingleManager.instance.verify_code
let account = self.phoneT.text
let card = self.cardT.text
let password = self.passwordT.text
let password2 = self.repassT.text
let params = ["username":account!,"password":password!,"password2":password2!,"code":card!,"unique_id":SingleManager.getUUID(),"capache":verifycode!,"push_id":""]
SJBRequestModel.push_fetchRegisterData(params: params as [String : AnyObject], completion: { (response, status) in
if status == 1{
self.Toast(content: "注册成功")
//注册成功
self.navigationController?.popViewController(animated: true)
}
else
{
}
})
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
// MARK: - 响应事件
extension SJBRegisterViewController{
func back() {
self.navigationController?.popViewController(animated: true)
}
@IBAction func regAction(_ sender: UIButton) {
if passwordT.text == repassT.text {
regHandle()
}
else{
Toast(content: "两次输入密码不一致")
}
}
}
// MARK: - 业务逻辑
extension SJBRegisterViewController{
/// 验证数据正确性
func validated() {
let phoneSignal = phoneT.reactive.continuousTextValues.map { (text) -> Bool in
if let str = text {
return self.PhoneNumberIsValidated(text: str)
}
return false
}
let cardSignal = cardT.reactive.continuousTextValues.map { (text) -> Bool in
if let str = text {
return self.NumberIsVailidated(text: str)
}
return false
}
let passwordSignal = passwordT.reactive.continuousTextValues.map { (text) -> Bool in
if let str = text {
return self.PassWordIsValidated(text: str)
}
return false
}
let rePassSignal = repassT.reactive.continuousTextValues.map { (text) -> Bool in
if let str = text {
return self.PassWordIsValidated(text: str)
}
return false
}
Signal.combineLatest(phoneSignal, cardSignal, passwordSignal, rePassSignal).observeValues { (phoneLegal,cardLegal,passwordLegal,rePassLegal) in
if phoneLegal && cardLegal && passwordLegal && rePassLegal {
self.regBtn.isUserInteractionEnabled = true
self.regBtn.backgroundColor = BAR_TINTCOLOR
}
else
{
self.regBtn.isUserInteractionEnabled = false
self.regBtn.backgroundColor = UIColor.lightGray
}
}
}
}
| mit | a1586cbd5520438a91a723b9c2e5419c | 32.660131 | 170 | 0.59165 | 4.795158 | false | false | false | false |
urbanthings/urbanthings-sdk-apple | UrbanThingsAPI/Internal/Response/UTTransitAgency.swift | 1 | 1608 | //
// UTTransitAgency.swift
// UrbanThingsAPI
//
// Created by Mark Woollard on 29/04/2016.
// Copyright © 2016 UrbanThings. All rights reserved.
//
import Foundation
class UTTransitAgency : UTObject, TransitAgency {
let agencyID:String
let agencyName:String
let agencyURL:URL
let agencyTimeZone:NSTimeZone
let agencyLanguage:String?
let agencyPhone:String?
let agencyFareURL:URL?
let agencyRegion:String?
let agencyImportSource:String?
override init(json:[String:Any]) throws {
self.agencyID = try parse(required:json, key: JSONKey.AgencyID, type: UTTransitAgency.self)
self.agencyName = try parse(required:json, key: .AgencyName, type: UTTransitAgency.self)
self.agencyURL = try parse(required:json, key:. AgencyURL, type: UTTransitAgency.self) { try URL.fromJSON(required:$0) }
self.agencyTimeZone = try parse(required:json, key: .AgencyTimeZone, type: UTTransitAgency.self) { try NSTimeZone(required: $0 as Any) }
self.agencyLanguage = try parse(optional: json, key: .AgencyLanguage, type: UTTransitAgency.self)
self.agencyPhone = try parse(optional: json, key: .AgencyPhone, type: UTTransitAgency.self)
self.agencyFareURL = try parse(optional:json, key:. AgencyFareURL, type: UTTransitAgency.self) { try URL.fromJSON(optional:$0) }
self.agencyRegion = try parse(optional: json, key: JSONKey.AgencyRegion, type: UTTransitAgency.self)
self.agencyImportSource = try parse(optional: json, key: .AgencyImportSource, type: UTTransitAgency.self)
try super.init(json:json)
}
}
| apache-2.0 | 0eee2e1d4c03a281e149e49e2f45685c | 43.638889 | 144 | 0.719975 | 3.7723 | false | false | false | false |
jjochen/photostickers | MessagesExtension/Protocols/WiggleEffect.swift | 1 | 2555 | //
// WiggleEffect.swift
// MessagesExtension
//
// Created by Jochen on 04.04.19.
// Copyright © 2019 Jochen Pfeiffer. All rights reserved.
//
import UIKit
protocol WiggleEffect {
func startWiggle()
func stopWiggle()
}
extension WiggleEffect where Self: UIView {
func startWiggle() {
let wiggleBounceY = 1.5
let wiggleBounceDuration = 0.18
let wiggleBounceDurationVariance = 0.025
let wiggleRotateAngle = 0.02
let wiggleRotateDuration = 0.14
let wiggleRotateDurationVariance = 0.025
guard !hasWiggleAnimation else {
return
}
// Create rotation animation
let rotationAnimation = CAKeyframeAnimation(keyPath: "transform.rotation.z")
rotationAnimation.values = [-wiggleRotateAngle, wiggleRotateAngle]
rotationAnimation.autoreverses = true
rotationAnimation.duration = randomize(interval: wiggleRotateDuration, withVariance: wiggleRotateDurationVariance)
rotationAnimation.repeatCount = .infinity
rotationAnimation.isRemovedOnCompletion = false
// Create bounce animation
let bounceAnimation = CAKeyframeAnimation(keyPath: "transform.translation.y")
bounceAnimation.values = [wiggleBounceY, 0]
bounceAnimation.autoreverses = true
bounceAnimation.duration = randomize(interval: wiggleBounceDuration, withVariance: wiggleBounceDurationVariance)
bounceAnimation.repeatCount = .infinity
bounceAnimation.isRemovedOnCompletion = false
// Apply animations to view
UIView.animate(withDuration: 0) {
self.layer.add(rotationAnimation, forKey: AnimationKey.Rotation)
self.layer.add(bounceAnimation, forKey: AnimationKey.Bounce)
self.transform = .identity
}
}
func stopWiggle() {
layer.removeAnimation(forKey: AnimationKey.Rotation)
layer.removeAnimation(forKey: AnimationKey.Bounce)
}
// Utility
private var hasWiggleAnimation: Bool {
guard let keys = layer.animationKeys() else {
return false
}
return keys.contains(AnimationKey.Bounce) || keys.contains(AnimationKey.Rotation)
}
private func randomize(interval: TimeInterval, withVariance variance: Double) -> Double {
let random = (Double(arc4random_uniform(1000)) - 500.0) / 500.0
return interval + variance * random
}
}
private struct AnimationKey {
static let Rotation = "wiggle.rotation"
static let Bounce = "wiggle.bounce"
}
| mit | e97afe7adfb4fa7c9391f63d96b3f338 | 31.74359 | 122 | 0.6852 | 4.703499 | false | false | false | false |
Incipia/Goalie | Goalie/CoreDataStack.swift | 1 | 895 | //
// CoreDataStack.swift
// Goalie
//
// Created by Gregory Klein on 12/4/15.
// Copyright © 2015 Incipia. All rights reserved.
//
import CoreData
import Foundation
import UIKit
private let storeURL = URL.documentsURL.appendingPathComponent("Goalie.goalie")
public func createGoalieMainContext() -> NSManagedObjectContext
{
let path = Bundle.main.path(forResource: "Task", ofType: "momd")
let momURL = URL(fileURLWithPath: path!)
guard let model = NSManagedObjectModel(contentsOf: momURL) else {
fatalError("model not found")
}
let psc = NSPersistentStoreCoordinator(managedObjectModel: model)
try! psc.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: storeURL, options: nil)
let context = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType)
context.persistentStoreCoordinator = psc
return context
}
| apache-2.0 | 270e53c51d27eb47be0ff9186f39d787 | 27.83871 | 109 | 0.748322 | 4.632124 | false | false | false | false |
beamly/BMYCircleStepView | BMYCircleStepView/CircleStepView.swift | 1 | 2735 | //
// CircleStepView.swift
// BMYCircleStepViewDemo
//
// Created by Alberto De Bortoli on 24/09/2014.
// Copyright (c) 2014 Beamly. All rights reserved.
//
import UIKit
class CircleStepView: UIView {
private var _circleViews: Array<CircleView>
var font: UIFont?
var selectedColor: UIColor? = UIColor.lightGrayColor()
var unselectedColor: UIColor? = UIColor.whiteColor()
var borderThickness: CGFloat = 0.0
var numberOfSteps: Int {
set {
_circleViews.removeAll(keepCapacity: 0)
for subview in subviews {
subview.removeFromSuperview()
}
for i in 0..<newValue {
let cv = CircleView(frame: CGRectZero)
cv.value = String(i+1)
if let fnt = font {
cv.font = fnt
}
cv.selectedColor = selectedColor
cv.unselectedColor = unselectedColor
cv.borderThickness = borderThickness
cv.backgroundColor = UIColor.clearColor()
_circleViews.append(cv)
addSubview(cv)
}
setNeedsDisplay()
}
get {
return subviews.count
}
}
var currentStep: Int = 0 {
didSet {
setNeedsDisplay()
}
}
var fillSteps: Bool = false {
didSet {
setNeedsDisplay()
}
}
required init(coder aDecoder: NSCoder) {
_circleViews = Array<CircleView>()
super.init(coder: aDecoder)
}
override func layoutSubviews() {
super.layoutSubviews()
var width = CGRectGetWidth(bounds)
var height = CGRectGetHeight(bounds)
var numberOfCircleViews = CGFloat(_circleViews.count)
if (numberOfCircleViews > 1) {
var unusedSpace = width - (height * numberOfCircleViews)
width += (unusedSpace / (numberOfCircleViews - 1))
for (i, circleView) in enumerate(_circleViews) {
circleView.frame = CGRect(
x: (width / numberOfCircleViews) * CGFloat(i),
y: 0.0,
width: height,
height: height
)
circleView.selected = ((i <= currentStep) && fillSteps) ||
((i == currentStep) && !fillSteps)
}
}
else if (numberOfCircleViews == 1){
var circleView = _circleViews.first as CircleView?
circleView!.frame = CGRectMake((width / 2) - (height / 2),
0.0,
height,
height)
circleView!.selected = (currentStep == 0)
}
}
}
| bsd-3-clause | 7c116461241b46864ad2e352ba2dac57 | 30.079545 | 74 | 0.519927 | 4.963702 | false | false | false | false |
AboutObjects/Modelmatic | Example/Modelmatic/DateTransformer.swift | 1 | 1005 | //
// Copyright (C) 2015 About Objects, Inc. All Rights Reserved.
// See LICENSE.txt for this example's licensing information.
//
import Foundation
@objc (MDLDateTransformer)
class DateTransformer: ValueTransformer
{
static let transformerName = NSValueTransformerName("Date")
override class func transformedValueClass() -> AnyClass { return NSString.self }
override class func allowsReverseTransformation() -> Bool { return true }
override func transformedValue(_ value: Any?) -> Any? {
guard let date = value as? Date else { return nil }
return serializedDateFormatter.string(from: date)
}
override func reverseTransformedValue(_ value: Any?) -> Any? {
guard let stringVal = value as? String else { return nil }
return serializedDateFormatter.date(from: stringVal)
}
}
private let serializedDateFormatter: DateFormatter = {
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd"
return formatter
}()
| mit | f889bd4425c1b54c66d38f1f56c768fa | 31.419355 | 84 | 0.702488 | 4.902439 | false | false | false | false |
aldopolimi/mobilecodegenerator | examples/ParkTraining/completed/ios/ParkTraining/ParkTraining/LocationEditViewController.swift | 2 | 3900 |
import UIKit
import MapKit
import CoreData
class LocationEditViewController: UIViewController, MKMapViewDelegate
{
@IBOutlet weak var deleteLocationButton: UIButton!
@IBOutlet weak var mMap: MKMapView!
var locationIndex: Int = 0
var location: NSManagedObject!
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
}
override func viewDidLoad() {
super.viewDidLoad()
deleteLocationButton.layer.cornerRadius = 36
self.mMap.delegate = self
//Legge la loc
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
let managedContext = appDelegate.managedObjectContext
let fetchRequest = NSFetchRequest(entityName: "Location")
do {
let results = try managedContext.executeFetchRequest(fetchRequest)
self.location = results[self.locationIndex] as! NSManagedObject
} catch {
print("Error")
}
let lat = self.location.valueForKey("lat") as? Double
let lon = self.location.valueForKey("lon") as? Double
let coordinates = CLLocationCoordinate2D(latitude: lat!, longitude: lon!)
let region = MKCoordinateRegionMake(CLLocationCoordinate2DMake(lat!, lon!), MKCoordinateSpanMake(0.005, 0.005))
let annotation = MKPointAnnotation()
annotation.coordinate = coordinates
annotation.title = "MARKER TITLE HERE"
self.mMap.setRegion(region, animated: true)
self.mMap.addAnnotation(annotation)
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
}
override func viewDidDisappear(animated: Bool) {
super.viewDidDisappear(animated)
}
@IBAction func deleteLocationButtonTouchDown(sender: UIButton) {
// Changes background color of button when clicked
sender.backgroundColor = UIColor(red: 0.7019608, green: 0.019607844, blue: 0.019607844, alpha: 1)
//TODO Implement the action
}
@IBAction func deleteLocationButtonTouchUpInside(sender: UIButton) {
// Restore original background color of button after click
sender.backgroundColor = UIColor(red: 0.8, green: 0.0, blue: 0.0, alpha: 1)
//TODO Implement the action
//Create the AlertController
let deleteLocationDialog: UIAlertController = UIAlertController(title: "Delete Location", message: "Are you sure?", preferredStyle: .Alert)
//Create and add the Cancel action
let deleteLocationDialogCancelAction: UIAlertAction = UIAlertAction(title: "Cancel", style: .Cancel) { action -> Void in
//Just dismiss the alert
}
//Create and add the Ok action
let deleteLocationDialogOkAction: UIAlertAction = UIAlertAction(title: "Ok", style: .Default) { action -> Void in
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
let managedContext = appDelegate.managedObjectContext
managedContext.deleteObject(self.location)
do {
try managedContext.save()
} catch {
print("error")
}
self.navigationController?.popViewControllerAnimated(true)
}
deleteLocationDialog.addAction(deleteLocationDialogCancelAction)
deleteLocationDialog.addAction(deleteLocationDialogOkAction)
//Present the AlertController
self.presentViewController(deleteLocationDialog, animated: true, completion: nil)
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
}
}
| gpl-3.0 | f19ec1c8d1ba24c767fd60a7ad5d3fc3 | 32.913043 | 147 | 0.679744 | 5.13834 | false | false | false | false |
Takanu/Pelican | Sources/Pelican/Session/Modules/Moderator/SessionModerator.swift | 1 | 5376 | //
// SessionModerator.swift
// PelicanTests
//
// Created by Takanu Kyriako on 26/07/2017.
//
//
import Foundation
/**
Contains the permissions associated with a single user or chat. A SessionModerator can only be
applied to a Chat or User, as every other ID lacks any kind of persistence to be useful for
moderation purposes. (Don't do it, please).
*/
public class SessionModerator {
/// The session the moderator is delegating for, as identified by it's tag.
private var tag: SessionTag
private var changeTitleCallback: (SessionIDType, String, [String], Bool) -> ()
private var checkTitleCallback: (String, SessionIDType) -> ([String])
public var getID: String { return tag.id }
public var getTitles: [String] { return checkTitleCallback(tag.id, tag.idType) }
/**
Attempts to create a SessionModerator.
- warning: This should not be used under any circumstances if your session does not represent a User or Chat session, and
if the SessionBuilder used to create is is not using User or Chat IDs respectively. 🙏
*/
init?(tag: SessionTag, moderator: Moderator) {
self.tag = tag
self.changeTitleCallback = moderator.switchTitle
self.checkTitleCallback = moderator.getTitles
if tag.idType != .chat || tag.idType != .user { return }
}
/**
Adds a title to this session.
*/
public func addTitle(_ title: String) {
changeTitleCallback(tag.idType, title, [tag.id], false)
}
/**
Adds a title to the IDs of the users specified.
*/
public func addTitleToUsers(title: String, users: User...) {
changeTitleCallback(.user, title, users.map({$0.tgID}), false)
}
/**
Adds a title to the IDs of the chats specified.
*/
public func addTitleToChats(title: String, chats: Chat...) {
changeTitleCallback(.chat, title, chats.map({$0.tgID}), false)
}
/**
Removes a title from this session, if associated with it.
*/
public func removeTitle(_ title: String) {
changeTitleCallback(tag.idType, title, [tag.id], true)
}
/**
Adds a title to the IDs of the users specified.
*/
public func removeTitleFromUsers(title: String, users: User...) {
changeTitleCallback(.user, title, users.map({$0.tgID}), true)
}
/**
Adds a title to the IDs of the chats specified.
*/
public func removeTitleFromChats(title: String, chats: Chat...) {
changeTitleCallback(.chat, title, chats.map({$0.tgID}), true)
}
/**
Checks to see whether a User has the specified title.
- returns: True if it does, false if not.
*/
public func getTitles(forUser user: User) -> [String] {
return checkTitleCallback(user.tgID, .user)
}
/**
Checks to see whether a Chat has the specified title.
- returns: True if it does, false if not.
*/
public func getTitles(forChat chat: Chat) -> [String] {
return checkTitleCallback(chat.tgID, .chat)
}
/**
Checks to see whether this Session has a given title.
- returns: True if it does, false if not.
*/
public func checkTitle(_ title: String) -> Bool {
let titles = checkTitleCallback(tag.id, tag.idType)
if titles.contains(title) { return true }
return false
}
/**
Checks to see whether a User has the specified title.
- returns: True if it does, false if not.
*/
public func checkTitle(forUser user: User, title: String) -> Bool {
let titles = checkTitleCallback(user.tgID, .user)
if titles.contains(title) { return true }
return false
}
/**
Checks to see whether a Chat has the specified title.
- returns: True if it does, false if not.
*/
public func checkTitle(forChat chat: Chat, title: String) -> Bool {
let titles = checkTitleCallback(chat.tgID, .chat)
if titles.contains(title) { return true }
return false
}
/**
Removes all titles associated with this session ID.
*/
public func clearTitles() {
let titles = checkTitleCallback(tag.id, tag.idType)
for title in titles {
changeTitleCallback(tag.idType, title, [tag.id], true)
}
}
/**
Blacklists the Session ID, which closes the Session and any associated ScheduleEvents, and adds the session
to the Moderator blacklist, preventing the ID from being able to make updates that
the bot can interpret or that could propogate a new, active session.
This continues until the ID is removed from the blacklist.
- note: This does not immediately deinitialize the Session, to avoid scenarios where the Session potentially needs
to be used by another operation at or near the timeframe where this occurs.
*/
public func blacklist() {
PLog.info("Adding to blacklist - \(tag.builderID)")
tag.sendEvent(type: .blacklist, action: .blacklist)
}
/**
Blacklists a different session from the one attached to this delegate, which does the following:
- Closes the Session and any associated ScheduleEvents
- Adds the session to the Moderator blacklist, preventing the ID from being able to make updates that
the bot can interpret or that could propogate a new, active session.
This continues until the ID is removed from the blacklist.
- note: This will only work with Sessions that subclass from ChatSession or UserSession - all else will fail.
*/
// This has been commented out to prevent unforeseen problems in how Session removal occurs.
/*
func blacklist(sessions: Session...) {
for session in sessions {
if session is UserSession || session is ChatSession {
}
}
}
*/
}
| mit | b3cfddab526c6655ec9fe9ae06f5e44e | 26.553846 | 123 | 0.707426 | 3.565362 | false | false | false | false |
banxi1988/BXCityPicker | Example/Pods/BXForm/Pod/Classes/View/TagLabel.swift | 2 | 1502 | //
// TagLabel.swift
// Pods
//
// Created by Haizhen Lee on 16/2/25.
//
//
import Foundation
//
// OvalLabel.swift
// Pods
//
// Created by Haizhen Lee on 15/12/29.
//
//
import UIKit
open class TagLabel:UILabel{
open var horizontalPadding:CGFloat = 4
open var outlineStyle = BXOutlineStyle.oval{
didSet{
updateOvalPath()
}
}
open var tagColor:UIColor = UIColor.gray{
didSet{
updateOvalPath()
}
}
open var cornerRadius:CGFloat = 4.0 {
didSet{
updateOvalPath()
}
}
lazy var maskLayer : CAShapeLayer = { [unowned self] in
let maskLayer = CAShapeLayer()
maskLayer.frame = self.frame
self.layer.insertSublayer(maskLayer,at:0)
return maskLayer
}()
open override func layoutSubviews() {
super.layoutSubviews()
maskLayer.frame = bounds
updateOvalPath()
}
fileprivate func updateOvalPath(){
if bounds.size.width < 1{
return
}
var radius:CGFloat
switch outlineStyle{
case .rounded:
radius = cornerRadius
case .oval:
radius = bounds.width * 0.5
case .semicircle:
radius = bounds.width * 0.5
}
let image = UIImage.bx_roundImage(tagColor, size: bounds.size, cornerRadius: radius)
maskLayer.contents = image.cgImage
}
open override var intrinsicContentSize : CGSize {
let size = super.intrinsicContentSize
return CGSize(width: size.width + horizontalPadding, height: size.height + horizontalPadding)
}
}
| mit | 6d5f4d700c508f9f3afef9eae99f1978 | 18.506494 | 97 | 0.646471 | 3.952632 | false | false | false | false |
slightair/syu | Syu/ViewController/MainContentViewController.swift | 1 | 1689 | import Cocoa
import WebKit
import Mustache
class MainContentViewController: NSViewController {
@IBOutlet weak var webView: WebView!
var content: Content? {
didSet {
updateContentView()
}
}
let contentBaseURL = Bundle.main.resourceURL!
override func viewDidLoad() {
super.viewDidLoad()
}
func updateContentView() {
webView.mainFrame.loadHTMLString(makeHTMLString(), baseURL: contentBaseURL)
}
func makeHTMLString() -> String {
guard let content = content else {
return "<h1>No content</h1>"
}
do {
let removeTags = Filter { (text: String?) -> String? in
guard let text = text else {
return nil
}
guard let regexp = try? NSRegularExpression(pattern: "<.+?>", options: []) else {
return nil
}
let result = regexp.stringByReplacingMatches(in: text, options: [], range: NSMakeRange(0, text.utf16.count), withTemplate: "")
return result
}
let template = try Template(named: "document")
template.register(removeTags, forKey: "removeTags")
return try template.render(content)
} catch let error as MustacheError {
let template = try! Template(string: "<h1>Rendering error</h1><p>{{description}}</p>")
let rendering = try? template.render([
"description": error.description,
])
return rendering ?? "<h1>Rendering error</h1>"
} catch {
return "<h1>Unknown error</h1>"
}
}
}
| mit | 1ee8e108a0e90b676add4c02a0fdc84b | 29.160714 | 142 | 0.551806 | 4.953079 | false | false | false | false |
timgrohmann/vertretungsplan_ios | Vertretungsplan/XMLParser.swift | 1 | 6410 | //
// XMLParser.swift
// Vertretungsplan
//
// Created by Tim Grohmann on 11.06.16.
// Copyright © 2016 Tim Grohmann. All rights reserved.
//
import Foundation
import UIKit
/**
**DEPRECATED**
*/
class XMLParser: NSObject, XMLParserDelegate{
var parser: Foundation.XMLParser?
var url: String
var parsed: NSDictionary = NSDictionary()
var callback: (ChangedTimeTableData)->()
var lessons: [ChangedLesson] = []
var inLesson = false
var currentLesson: ChangedLesson = ChangedLesson()
var inHour = false
var inSubject = false
var inTeacher = false
var inRoom = false
var inKlasse = false
var inInfo = false
var inLastRefreshed = false
var inSchoolName = false
var lastRefreshed = ""
var schoolName = ""
var inTitle = false
var title = ""
var day: Int?
func parser(_ parser: Foundation.XMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String]){
switch elementName{
case "aktion":
inLesson = true
lessons.append(ChangedLesson())
break
case "klasse":
inKlasse = true
break
case "stunde":
inHour = true
break
case "fach":
inSubject = true
break
case "lehrer":
inTeacher = true
break
case "raum":
inRoom = true
break
case "info":
inInfo = true
break
case "titel":
inTitle = true
break
case "datum":
inLastRefreshed = true
break
case "schulname":
inSchoolName = true
break
default:
break
}
}
func parser(_ parser: Foundation.XMLParser, foundCharacters string: String) {
if inHour{
lessons.last?.hour = Int(string) ?? 0
}
if inSubject{
lessons.last?.subject += string
}
if inTeacher{
lessons.last?.teacher += string
}
if inRoom{
lessons.last?.room += string
}
if inKlasse{
//lessons.last?.rawKlasse += string
}
if inInfo{
lessons.last?.info += string
}
if inTitle{
title += string
}
if inLastRefreshed{
lastRefreshed += string
}
if inSchoolName{
schoolName += string
}
}
func parser(_ parser: Foundation.XMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?) {
switch elementName{
case "aktion":
lessons.last?.day = day
//lessons.last?.parsed()
inLesson = false
break
case "klasse":
inKlasse = false
break
case "stunde":
inHour = false
break
case "fach":
inSubject = false
break
case "lehrer":
inTeacher = false
break
case "raum":
inRoom = false
break
case "info":
inInfo = false
break
case "titel":
inTitle = false
let dayName = title.components(separatedBy: ",")[0]
let days = ["Montag":0,"Dienstag":1,"Mittwoch":2,"Donnerstag":3,"Freitag":4]
day = days[dayName]
break
case "datum":
inLastRefreshed = false
break
case "schulname":
inSchoolName = false
break
default:
break
}
}
func parserDidEndDocument(_ parser: Foundation.XMLParser) {
let data = ChangedTimeTableData(changedLessons: lessons, schoolName: schoolName, lastRefreshed: lastRefreshed)
self.callback(data)
}
func parser(_ parser: Foundation.XMLParser, parseErrorOccurred parseError: Error) {
callback(ChangedTimeTableData(changedLessons: [], schoolName: "", lastRefreshed: "Vertretungsplan hat falsches Dateiformat. Bitte melde dich bei deiner Schule."))
//reset callback to stop recalling it with parserDidEndDocument:
self.callback = {_ in}
}
init(url: String, callback: @escaping (ChangedTimeTableData)->()) {
self.url = url
self.callback = callback
super.init()
if let nsurl = URL(string: url){
let session = URLSession(configuration: URLSessionConfiguration.default)
let task = session.dataTask(with: nsurl, completionHandler: {
data, response, error in
if let error = error{
callback(ChangedTimeTableData(changedLessons: [], schoolName: "", lastRefreshed: "Vertretungsplan konnte nicht geladen werden. "+error.localizedDescription))
}
if let r = response as? HTTPURLResponse{
switch r.statusCode{
case 200:
break
case 404:
callback(ChangedTimeTableData(changedLessons: [], schoolName: "", lastRefreshed: "Vertretungsplan konnte nicht geladen werden. Der Vertretungsplan konnte nicht auf dem Server deiner Schule gefunden werden."))
break
default:
callback(ChangedTimeTableData(changedLessons: [], schoolName: "", lastRefreshed: "Vertretungsplan konnte nicht geladen werden. Unbekannter Fehler"))
break
}
}
if let data = data{
self.parser = Foundation.XMLParser(data: data)
self.parser?.delegate = self
self.parser?.parse()
}
})
task.resume()
}else{
callback(ChangedTimeTableData(changedLessons: [], schoolName: "", lastRefreshed: "'"+url+"' ist kein gültiger Link"))
}
}
}
| apache-2.0 | a742f3e1bff6283e37bc41baaed4cdd9 | 28.127273 | 232 | 0.514513 | 5.073634 | false | false | false | false |
coolmacmaniac/swift-ios | LearnSwift/MusicAlbum/MusicAlbum/Controller/ViewController.swift | 1 | 3659 | //
// ViewController.swift
// MusicAlbum
//
// Created by Sourabh on 22/06/17.
// Copyright © 2017 Home. All rights reserved.
//
import UIKit
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, HorizontalScrollerDelegate {
private var dataTable: UITableView!
private var allAlbums: Array<Album>!
private var currentAlbum: Dictionary<String, Array<String>>?
private var horizontalScroller: HorizontalScroller!
private var currentAlbumIndex: Int = 0
private static let kTableOffset = CGFloat(120)
private static let kTableCellId = "albumInfoCell"
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor(
red: 0.76,
green: 0.81,
blue: 0.87,
alpha: 0.1
)
self.allAlbums = LibraryApi.sharedInstance.getAlbums()
var rect = CGRect(
x: 0,
y: ViewController.kTableOffset,
width: self.view.frame.size.width,
height: self.view.frame.size.height - ViewController.kTableOffset
)
self.dataTable = UITableView(frame: rect, style: .grouped)
self.dataTable.delegate = self
self.dataTable.dataSource = self
self.dataTable.backgroundView = nil
self.view.addSubview(self.dataTable)
//self.dataTable.register(UITableViewCell.self, forCellReuseIdentifier: ViewController.kTableCellId)
rect = CGRect(
x: 0,
y: 0,
width: self.view.frame.size.width,
height: ViewController.kTableOffset
)
self.horizontalScroller = HorizontalScroller(frame: rect)
self.horizontalScroller.backgroundColor = UIColor(
red: 0.24,
green: 0.35,
blue: 0.49,
alpha: 1.0
)
self.horizontalScroller.delegate = self
self.view.addSubview(self.horizontalScroller)
self.showDataForAlbum(at: self.currentAlbumIndex)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
private func showDataForAlbum(at index: Int) {
if index < self.allAlbums.count {
let album = self.allAlbums[index]
self.currentAlbum = album.tr_tableRepresentation()
} else {
self.currentAlbum = nil
}
self.dataTable.reloadData()
}
//MARK: - UITableViewDataSource
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.currentAlbum?[Album.kKeys]?.count ?? 0
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cell: UITableViewCell! = tableView.dequeueReusableCell(withIdentifier: ViewController.kTableCellId)
if nil == cell {
cell = UITableViewCell(style: .value1, reuseIdentifier: ViewController.kTableCellId)
}
cell.textLabel?.text = self.currentAlbum?[Album.kKeys]?[indexPath.row]
cell.detailTextLabel?.text = self.currentAlbum?[Album.kValues]?[indexPath.row]
return cell
}
//MARK: - UITableViewDelegate
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
}
//MARK: - HorizontalScrollerDelegate
func numberOfViews(in horizontalScroller: HorizontalScroller) -> Int {
return self.allAlbums.count
}
func initialViewIndex(in horizontalScroller: HorizontalScroller) -> Int {
return 0
}
func horizontalScroller(_ horizontalScroller: HorizontalScroller, viewAt index: Int) -> UIView {
let album = self.allAlbums[index]
let albumView = AlbumView(frame: CGRect(x: 0, y: 0, width: 100, height: 100), albumCover: album.coverUrl)
return albumView
}
func horizontalScroller(_ horizontalScroller: HorizontalScroller, didSelectViewAt index: Int) {
self.currentAlbumIndex = index
self.showDataForAlbum(at: index)
}
}
| gpl-3.0 | 8b8113de9c66c9c8a5202454f5bfc083 | 24.58042 | 112 | 0.730454 | 3.755647 | false | false | false | false |
zjjzmw1/robot | robot/Pods/CocoaLumberjack/Classes/CocoaLumberjack.swift | 64 | 5828 | // Software License Agreement (BSD License)
//
// Copyright (c) 2014-2016, Deusty, LLC
// All rights reserved.
//
// Redistribution and use of this software 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.
//
// * Neither the name of Deusty nor the names of its contributors may be used
// to endorse or promote products derived from this software without specific
// prior written permission of Deusty, LLC.
import Foundation
extension DDLogFlag {
public static func fromLogLevel(logLevel: DDLogLevel) -> DDLogFlag {
return DDLogFlag(rawValue: logLevel.rawValue)
}
public init(_ logLevel: DDLogLevel) {
self = DDLogFlag(rawValue: logLevel.rawValue)
}
///returns the log level, or the lowest equivalant.
public func toLogLevel() -> DDLogLevel {
if let ourValid = DDLogLevel(rawValue: self.rawValue) {
return ourValid
} else {
let logFlag:DDLogFlag = self
if logFlag.contains(.Verbose) {
return .Verbose
} else if logFlag.contains(.Debug) {
return .Debug
} else if logFlag.contains(.Info) {
return .Info
} else if logFlag.contains(.Warning) {
return .Warning
} else if logFlag.contains(.Error) {
return .Error
} else {
return .Off
}
}
}
}
public var defaultDebugLevel = DDLogLevel.Verbose
public func resetDefaultDebugLevel() {
defaultDebugLevel = DDLogLevel.Verbose
}
@available(*, deprecated, message="Use one of the DDLog*() functions if appropriate or call _DDLogMessage()")
public func SwiftLogMacro(isAsynchronous: Bool, level: DDLogLevel, flag flg: DDLogFlag, context: Int = 0, file: StaticString = #file, function: StaticString = #function, line: UInt = #line, tag: AnyObject? = nil, @autoclosure string: () -> String, ddlog: DDLog = DDLog.sharedInstance()) {
_DDLogMessage(string, level: level, flag: flg, context: context, file: file, function: function, line: line, tag: tag, asynchronous: isAsynchronous, ddlog: ddlog)
}
public func _DDLogMessage(@autoclosure message: () -> String, level: DDLogLevel, flag: DDLogFlag, context: Int, file: StaticString, function: StaticString, line: UInt, tag: AnyObject?, asynchronous: Bool, ddlog: DDLog) {
if level.rawValue & flag.rawValue != 0 {
// Tell the DDLogMessage constructor to copy the C strings that get passed to it.
let logMessage = DDLogMessage(message: message(), level: level, flag: flag, context: context, file: file.stringValue, function: function.stringValue, line: line, tag: tag, options: [.CopyFile, .CopyFunction], timestamp: nil)
ddlog.log(asynchronous, message: logMessage)
}
}
public func DDLogDebug(@autoclosure message: () -> String, level: DDLogLevel = defaultDebugLevel, context: Int = 0, file: StaticString = #file, function: StaticString = #function, line: UInt = #line, tag: AnyObject? = nil, asynchronous async: Bool = true, ddlog: DDLog = DDLog.sharedInstance()) {
_DDLogMessage(message, level: level, flag: .Debug, context: context, file: file, function: function, line: line, tag: tag, asynchronous: async, ddlog: ddlog)
}
public func DDLogInfo(@autoclosure message: () -> String, level: DDLogLevel = defaultDebugLevel, context: Int = 0, file: StaticString = #file, function: StaticString = #function, line: UInt = #line, tag: AnyObject? = nil, asynchronous async: Bool = true, ddlog: DDLog = DDLog.sharedInstance()) {
_DDLogMessage(message, level: level, flag: .Info, context: context, file: file, function: function, line: line, tag: tag, asynchronous: async, ddlog: ddlog)
}
public func DDLogWarn(@autoclosure message: () -> String, level: DDLogLevel = defaultDebugLevel, context: Int = 0, file: StaticString = #file, function: StaticString = #function, line: UInt = #line, tag: AnyObject? = nil, asynchronous async: Bool = true, ddlog: DDLog = DDLog.sharedInstance()) {
_DDLogMessage(message, level: level, flag: .Warning, context: context, file: file, function: function, line: line, tag: tag, asynchronous: async, ddlog: ddlog)
}
public func DDLogVerbose(@autoclosure message: () -> String, level: DDLogLevel = defaultDebugLevel, context: Int = 0, file: StaticString = #file, function: StaticString = #function, line: UInt = #line, tag: AnyObject? = nil, asynchronous async: Bool = true, ddlog: DDLog = DDLog.sharedInstance()) {
_DDLogMessage(message, level: level, flag: .Verbose, context: context, file: file, function: function, line: line, tag: tag, asynchronous: async, ddlog: ddlog)
}
public func DDLogError(@autoclosure message: () -> String, level: DDLogLevel = defaultDebugLevel, context: Int = 0, file: StaticString = #file, function: StaticString = #function, line: UInt = #line, tag: AnyObject? = nil, asynchronous async: Bool = false, ddlog: DDLog = DDLog.sharedInstance()) {
_DDLogMessage(message, level: level, flag: .Error, context: context, file: file, function: function, line: line, tag: tag, asynchronous: async, ddlog: ddlog)
}
/// Returns a String of the current filename, without full path or extension.
///
/// Analogous to the C preprocessor macro `THIS_FILE`.
public func CurrentFileName(fileName: StaticString = #file) -> String {
var str = fileName.stringValue
if let idx = str.rangeOfString("/", options: .BackwardsSearch)?.endIndex {
str = str.substringFromIndex(idx)
}
if let idx = str.rangeOfString(".", options: .BackwardsSearch)?.startIndex {
str = str.substringToIndex(idx)
}
return str
}
| mit | 507e62ba3986e14f993ba9c36d3fa4b6 | 56.137255 | 298 | 0.690975 | 4.317037 | false | false | false | false |
Otbivnoe/NxEnabled | NxEnabledTests/KVOChangesTests.swift | 1 | 5318 | //
// KVOChangesTests.swift
// NxEnabled
//
// Created by Nikita Ermolenko on 08/02/2017.
//
//
import XCTest
import NxEnabled
final class KVOChangesTests: BaseTests {
override func setUp() {
super.setUp()
}
override func tearDown() {
super.tearDown()
}
func testThatCorrectlyHandlesKVOChangesForOneTextableElement_Textfield() {
button.isEnabled(by: textfield1) { [unowned self] v1 in
self.value1 = v1
return true
}
XCTAssertEqual(value1, textfield1.text)
textfield1.text = "$1"
XCTAssertEqual(value1, textfield1.text)
}
func testThatCorrectlyHandlesKVOChangesForOneTextableElement_Textview() {
button.isEnabled(by: textview1) { [unowned self] v1 in
self.value1 = v1
return true
}
XCTAssertEqual(value1, textview1.text)
textview1.text = "$1"
XCTAssertEqual(value1, textview1.text)
}
func testThatCorrectlyHandlesKVOChangesForTwoTextableElements() {
button.isEnabled(by: textfield1, textview1) { [unowned self] v1, v2 in
self.value1 = v1
self.value2 = v2
return true
}
XCTAssertEqual(value1, textfield1.text)
XCTAssertEqual(value2, textview1.text)
textfield1.text = "$1"
textview1.text = "%1"
XCTAssertEqual(value1, textfield1.text)
XCTAssertEqual(value2, textview1.text)
}
func testThatCorrectlyHandlesKVOChangesForThreeTextableElements() {
button.isEnabled(by: textfield1, textview1, textfield2) { [unowned self] v1, v2, v3 in
self.value1 = v1
self.value2 = v2
self.value3 = v3
return true
}
XCTAssertEqual(value1, textfield1.text)
XCTAssertEqual(value2, textview1.text)
XCTAssertEqual(value3, textfield2.text)
textfield1.text = "$1"
textview1.text = "%1"
textfield2.text = "$2"
XCTAssertEqual(value1, textfield1.text)
XCTAssertEqual(value2, textview1.text)
XCTAssertEqual(value3, textfield2.text)
}
func testThatCorrectlyHandlesKVOChangesForFourTextableElements() {
button.isEnabled(by: textfield1, textview1, textfield2, textview2) { [unowned self] v1, v2, v3, v4 in
self.value1 = v1
self.value2 = v2
self.value3 = v3
self.value4 = v4
return true
}
XCTAssertEqual(value1, textfield1.text)
XCTAssertEqual(value2, textview1.text)
XCTAssertEqual(value3, textfield2.text)
XCTAssertEqual(value4, textview2.text)
textfield1.text = "$1"
textview1.text = "%1"
textfield2.text = "$2"
textview2.text = "%2"
XCTAssertEqual(value1, textfield1.text)
XCTAssertEqual(value2, textview1.text)
XCTAssertEqual(value3, textfield2.text)
XCTAssertEqual(value4, textview2.text)
}
func testThatCorrectlyHandlesKVOChangesForFiveTextableElements() {
button.isEnabled(by: textfield1, textview1, textfield2, textview2, textfield3) { [unowned self] v1, v2, v3, v4, v5 in
self.value1 = v1
self.value2 = v2
self.value3 = v3
self.value4 = v4
self.value5 = v5
return true
}
XCTAssertEqual(value1, textfield1.text)
XCTAssertEqual(value2, textview1.text)
XCTAssertEqual(value3, textfield2.text)
XCTAssertEqual(value4, textview2.text)
XCTAssertEqual(value5, textfield3.text)
textfield1.text = "$1"
textview1.text = "%1"
textfield2.text = "$2"
textview2.text = "%2"
textfield3.text = "$3"
XCTAssertEqual(value1, textfield1.text)
XCTAssertEqual(value2, textview1.text)
XCTAssertEqual(value3, textfield2.text)
XCTAssertEqual(value4, textview2.text)
XCTAssertEqual(value5, textfield3.text)
}
func testThatCorrectlyHandlesKVOChangesForSixTextableElements() {
button.isEnabled(by: textfield1, textview1, textfield2, textview2, textfield3, textview3) { [unowned self] v1, v2, v3, v4, v5, v6 in
self.value1 = v1
self.value2 = v2
self.value3 = v3
self.value4 = v4
self.value5 = v5
self.value6 = v6
return true
}
XCTAssertEqual(value1, textfield1.text)
XCTAssertEqual(value2, textview1.text)
XCTAssertEqual(value3, textfield2.text)
XCTAssertEqual(value4, textview2.text)
XCTAssertEqual(value5, textfield3.text)
XCTAssertEqual(value6, textview3.text)
textfield1.text = "$1"
textview1.text = "%1"
textfield2.text = "$2"
textview2.text = "%2"
textfield3.text = "$3"
textview3.text = "%3"
XCTAssertEqual(value1, textfield1.text)
XCTAssertEqual(value2, textview1.text)
XCTAssertEqual(value3, textfield2.text)
XCTAssertEqual(value4, textview2.text)
XCTAssertEqual(value5, textfield3.text)
XCTAssertEqual(value6, textview3.text)
}
}
| mit | 656c7f7bd92fc94459c5514a3eed3827 | 30.654762 | 140 | 0.604927 | 4.093918 | false | true | false | false |
tise/SwipeableViewController | SwipeableViewController/Source/SwipeableCollectionViewFlowLayout.swift | 1 | 1278 | //
// SwipeableCollectionViewFlowLayout.swift
// SwipingViewController
//
// Created by Oscar Apeland on 12.10.2017.
// Copyright © 2017 Tise. All rights reserved.
//
import UIKit
open class SwipeableCollectionViewFlowLayout: UICollectionViewFlowLayout {
override init() {
super.init()
setup()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup()
}
private var collectionViewObservation: NSKeyValueObservation?
private func setup() {
collectionViewObservation = observe(\.collectionView, options: [.new]) { (layout, change) in
guard let newCollectionView = change.newValue as? UICollectionView, let layout = newCollectionView.collectionViewLayout as? SwipeableCollectionViewFlowLayout else {
return
}
//
layout.sectionInset = UIEdgeInsets(top: 0.0, left: 10.0, bottom: 0.0, right: 10.0)
layout.estimatedItemSize = CGSize(width: 60, height: newCollectionView.frame.height)
layout.minimumInteritemSpacing = .leastNonzeroMagnitude
layout.minimumLineSpacing = .leastNonzeroMagnitude
layout.scrollDirection = .horizontal
}
}
}
| mit | 59c8a413d5eb7b745c1231b159eb9662 | 33.513514 | 176 | 0.656226 | 5.212245 | false | false | false | false |
AllisonWangJiaoJiao/KnowledgeAccumulation | 17.PayToolsDemo/PayToolsDemo/PayTools/PayTools.swift | 1 | 3470 | //
// PayTools.swift
// PayToolsDemo
//
// Created by Allison on 2017/8/15.
// Copyright © 2017年 Allison. All rights reserved.
//
import Foundation
import SVProgressHUD
class PayTool {
var canPay : Bool = true
/// 支付成功回调
var paySuccess : (()->())?
init() {
NotificationCenter.default.addObserver(self, selector: #selector(alipayBack), name: NSNotification.Name(rawValue: AlipayBackNotification), object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(wechatPayDidDone), name: NSNotification.Name(rawValue: WXpayBackNotification), object: nil)
}
/// 支付
///
/// - Parameters:
/// - orderId: 订单id,预约单ID,换电单,救援工单
/// - orderType:工单类型,1 预约单ID,2 换电单,3救援工单
/// - payType: 支付方式,1微信 2支付宝
func createPayment(orderId : Int, orderType : Int, payType : Int,payinfo:String) {
if payType == 2{//支付宝支付
self.pay_alipay(order: payinfo, scheme: appScheme)
}
}
private func pay_alipay(order : String, scheme : String) {
let alipaySDK = AlipaySDK.defaultService()
alipaySDK?.payOrder(order, fromScheme: scheme, callback: { (resultDic) in
//快捷支付开发包回调函数,返回免登、支付结果。本地未安装支付宝客户端,或未成功调用支付宝客户端进行支付的情况下(走H5收银台),会通过该本callback返回支付结果。
self.alipayPayDidDone(resultDic: resultDic ?? [:])
self.canPay = true
})
}
private func alipayPayDidDone(resultDic : [AnyHashable : Any]) -> Void{
if let status = resultDic["resultStatus"] as? String{
switch status {
case "9000" :
SVProgressHUD.showSuccess(withStatus: "支付成功")
if self.paySuccess != nil {
self.paySuccess!()
}
case "8000" :
SVProgressHUD.showInfo(withStatus: "正在处理中")
case "4000" :
SVProgressHUD.showError(withStatus: "订单支付失败")
case "6001" :
SVProgressHUD.showInfo(withStatus: "取消支付")
case "6002" :
SVProgressHUD.showError(withStatus: "网络连接出错")
default :
if let memo = resultDic["memo"] as? String{
SVProgressHUD.showError(withStatus: memo)
} else {
SVProgressHUD.showError(withStatus: "支付失败")
}
}
}
}
/// 正常调用支付宝app通过appdelegate中返回结果,通过发通知在本处调用
@objc private func alipayBack(notification : Notification) {
if let resultDic = notification.object as? [AnyHashable : Any] {
alipayPayDidDone(resultDic: resultDic)
}
}
@objc private func wechatPayDidDone(notification : Notification){
}
deinit {
NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: AlipayBackNotification), object: nil)
NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: WXpayBackNotification), object: nil)
}
}
| mit | d91ae3a2f1c270e5160cc575fffcf305 | 30.663265 | 164 | 0.582662 | 4.142857 | false | false | false | false |
natecook1000/swift | stdlib/public/SDK/Network/NWProtocolIP.swift | 6 | 5849 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2018 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
//
//===----------------------------------------------------------------------===//
@available(macOS 10.14, iOS 12.0, watchOS 5.0, tvOS 12.0, *)
public class NWProtocolIP : NWProtocol {
public static let definition: NWProtocolDefinition = {
NWProtocolDefinition(nw_protocol_copy_ip_definition(), "ip")
}()
public class Options : NWProtocolOptions {
public enum Version {
/// Allow any IP version
case any
/// Use only IP version 4 (IPv4)
case v4
/// Use only IP version 6 (IPv6)
case v6
internal var nw: nw_ip_version_t {
switch self {
case .v4:
return Network.nw_ip_version_4
case .v6:
return Network.nw_ip_version_6
default:
return Network.nw_ip_version_any
}
}
internal init(_ nw: nw_ip_version_t) {
switch nw {
case Network.nw_ip_version_4:
self = .v4
case Network.nw_ip_version_6:
self = .v6
default:
self = .any
}
}
}
private var _version: Version = .any
/// Specify a single version of the Internet NWProtocol to allow.
/// Setting this value will constrain which address endpoints can
/// be used, and will filter DNS results during connection establishment.
public var version: Version {
set {
self._version = newValue
nw_ip_options_set_version(self.nw, newValue.nw)
}
get {
return self._version
}
}
private var _hopLimit: UInt8 = 0
/// Configure the IP hop limit, equivalent to IP_TTL for IPv4
/// and IPV6_HOPLIMIT for IPv6.
public var hopLimit: UInt8 {
set {
self._hopLimit = newValue
nw_ip_options_set_hop_limit(self.nw, newValue)
}
get {
return self._hopLimit
}
}
private var _useMinimumMTU: Bool = false
/// Configure IP to use the minimum MTU value, which
/// is 1280 bytes for IPv6 (IPV6_USE_MIN_MTU). This value has
/// no effect for IPv4.
public var useMinimumMTU: Bool {
set {
self._useMinimumMTU = newValue
nw_ip_options_set_use_minimum_mtu(self.nw, newValue)
}
get {
return self._useMinimumMTU
}
}
private var _disableFragmentation: Bool = false
/// Configure IP to disable fragmentation on outgoing
/// packets (IPV6_DONTFRAG). This value has no effect
/// for IPv4.
public var disableFragmentation: Bool {
set {
self._disableFragmentation = newValue
nw_ip_options_set_disable_fragmentation(self.nw, newValue)
}
get {
return self._disableFragmentation
}
}
private var _shouldCalculateReceiveTime: Bool = false
/// Configure IP to calculate receive time for inbound
/// packets.
public var shouldCalculateReceiveTime: Bool {
set {
self._shouldCalculateReceiveTime = newValue
nw_ip_options_set_calculate_receive_time(self.nw, newValue)
}
get {
return self._shouldCalculateReceiveTime
}
}
override internal init(_ nw: nw_protocol_options_t) {
super.init(nw)
}
}
/// Values for Explicit Congestion Notification flags
public enum ECN {
/// Non ECN-Capable Transport
case nonECT
/// ECN Capable Transport (0)
case ect0
/// ECN Capable Transport (1)
case ect1
/// Congestion Experienced
case ce
fileprivate init(_ nw: nw_ip_ecn_flag_t) {
switch nw {
case Network.nw_ip_ecn_flag_non_ect:
self = .nonECT
case Network.nw_ip_ecn_flag_ect_0:
self = .ect0
case Network.nw_ip_ecn_flag_ect_1:
self = .ect1
case Network.nw_ip_ecn_flag_ce:
self = .ce
default:
self = .nonECT
}
}
fileprivate var nw : nw_ip_ecn_flag_t {
switch self {
case .nonECT:
return Network.nw_ip_ecn_flag_non_ect
case .ect0:
return Network.nw_ip_ecn_flag_ect_0
case .ect1:
return Network.nw_ip_ecn_flag_ect_1
case .ce:
return Network.nw_ip_ecn_flag_ce
}
}
}
/// IP Metadata can be sent or received as part of ContentContext
public class Metadata: NWProtocolMetadata {
/// Set ECN flags to be sent on a packet, or get ECN flags
/// received on a packet. These flags will not take effect
/// for protocols such as TCP that deliver data without accounting
/// for packet boundaries.
public var ecn: ECN {
set {
nw_ip_metadata_set_ecn_flag(nw, newValue.nw)
}
get {
return ECN(nw_ip_metadata_get_ecn_flag(nw))
}
}
/// Set the network service class to be sent on a packet. The per-packet
/// service class will not take effect for protocols such as TCP that deliver
/// data without accounting for packet boundaries. If you need to set
/// service class for TCP, use the serviceClass property of NWParameters.
public var serviceClass : NWParameters.ServiceClass {
set {
nw_ip_metadata_set_service_class(nw, newValue.nw)
}
get {
return NWParameters.ServiceClass(nw_ip_metadata_get_service_class(nw))
}
}
/// The time at which a packet was received, in nanoseconds.
/// Equivalent to timestamps returned by CLOCK_MONOTONIC_RAW.
public var receiveTime: UInt64 {
get {
return nw_ip_metadata_get_receive_time(nw)
}
}
override internal init(_ nw: nw_protocol_metadata_t) {
super.init(nw)
}
/// Create an empty IP metadata to send with ContentContext
public init() {
super.init(nw_ip_create_metadata())
}
}
}
| apache-2.0 | f8c64f3ae07a39c49e3b08c30ce7961e | 26.331776 | 86 | 0.626774 | 3.446671 | false | false | false | false |
fgengine/quickly | Quickly/Compositions/Standart/QMultiTextFieldComposition.swift | 1 | 6648 | //
// Quickly
//
open class QMultiTextFieldComposable : QComposable {
public typealias ShouldClosure = (_ composable: QMultiTextFieldComposable) -> Bool
public typealias Closure = (_ composable: QMultiTextFieldComposable) -> Void
public var fieldStyle: QMultiTextFieldStyleSheet
public var maximumNumberOfCharecters: UInt
public var maximumNumberOfLines: UInt
public var minimumHeight: CGFloat
public var maximumHeight: CGFloat
public var height: CGFloat
public var text: String
public var isValid: Bool {
get {
guard let validator = self.fieldStyle.validator else { return true }
return validator.validate(self.text).isValid
}
}
public var isEditing: Bool
public var shouldBeginEditing: ShouldClosure?
public var beginEditing: Closure?
public var editing: Closure?
public var shouldEndEditing: ShouldClosure?
public var endEditing: Closure?
public var changedHeight: Closure?
public init(
edgeInsets: UIEdgeInsets = UIEdgeInsets.zero,
fieldStyle: QMultiTextFieldStyleSheet,
text: String,
maximumNumberOfCharecters: UInt = 0,
maximumNumberOfLines: UInt = 0,
minimumHeight: CGFloat = 0,
maximumHeight: CGFloat = 0,
height: CGFloat = 44,
shouldBeginEditing: ShouldClosure? = nil,
beginEditing: Closure? = nil,
editing: Closure? = nil,
shouldEndEditing: ShouldClosure? = nil,
endEditing: Closure? = nil,
changedHeight: Closure? = nil
) {
self.fieldStyle = fieldStyle
self.text = text
self.maximumNumberOfCharecters = maximumNumberOfCharecters
self.maximumNumberOfLines = maximumNumberOfLines
self.minimumHeight = minimumHeight
self.maximumHeight = maximumHeight
self.height = height
self.isEditing = false
self.shouldBeginEditing = shouldBeginEditing
self.beginEditing = beginEditing
self.editing = editing
self.shouldEndEditing = shouldEndEditing
self.endEditing = endEditing
self.changedHeight = changedHeight
super.init(edgeInsets: edgeInsets)
}
}
open class QMultiTextFieldComposition< Composable: QMultiTextFieldComposable > : QComposition< Composable >, IQEditableComposition {
public lazy private(set) var fieldView: QMultiTextField = {
let view = QMultiTextField(frame: self.contentView.bounds)
view.translatesAutoresizingMaskIntoConstraints = false
view.onShouldBeginEditing = { [weak self] _ in return self?._shouldBeginEditing() ?? true }
view.onBeginEditing = { [weak self] _ in self?._beginEditing() }
view.onEditing = { [weak self] _ in self?._editing() }
view.onShouldEndEditing = { [weak self] _ in return self?._shouldEndEditing() ?? true }
view.onEndEditing = { [weak self] _ in self?._endEditing() }
view.onChangedHeight = { [weak self] _ in self?._changedHeight() }
self.contentView.addSubview(view)
return view
}()
private var _edgeInsets: UIEdgeInsets?
private var _constraints: [NSLayoutConstraint] = [] {
willSet { self.contentView.removeConstraints(self._constraints) }
didSet { self.contentView.addConstraints(self._constraints) }
}
open override class func size(composable: Composable, spec: IQContainerSpec) -> CGSize {
return CGSize(
width: spec.containerSize.width,
height: composable.edgeInsets.top + composable.height + composable.edgeInsets.bottom
)
}
deinit {
if let observer = self.owner as? IQMultiTextFieldObserver {
self.fieldView.remove(observer: observer)
}
}
open override func setup(owner: AnyObject) {
super.setup(owner: owner)
if let observer = owner as? IQMultiTextFieldObserver {
self.fieldView.add(observer: observer, priority: 0)
}
}
open override func preLayout(composable: Composable, spec: IQContainerSpec) {
if self._edgeInsets != composable.edgeInsets {
self._edgeInsets = composable.edgeInsets
self._constraints = [
self.fieldView.topLayout == self.contentView.topLayout.offset(composable.edgeInsets.top),
self.fieldView.leadingLayout == self.contentView.leadingLayout.offset(composable.edgeInsets.left),
self.fieldView.trailingLayout == self.contentView.trailingLayout.offset(-composable.edgeInsets.right),
self.fieldView.bottomLayout == self.contentView.bottomLayout.offset(-composable.edgeInsets.bottom)
]
}
}
open override func apply(composable: Composable, spec: IQContainerSpec) {
self.fieldView.apply(composable.fieldStyle)
self.fieldView.unformatText = composable.text
}
// MARK: IQCompositionEditable
open func beginEditing() {
self.fieldView.beginEditing()
}
open func endEditing() {
self.fieldView.endEditing(false)
}
// MARK: Private
private func _shouldBeginEditing() -> Bool {
guard let composable = self.composable else { return true }
if let closure = composable.shouldBeginEditing {
return closure(composable)
}
return true
}
private func _beginEditing() {
guard let composable = self.composable else { return }
composable.isEditing = self.fieldView.isEditing
if let closure = composable.beginEditing {
closure(composable)
}
}
private func _editing() {
guard let composable = self.composable else { return }
composable.text = self.fieldView.unformatText
if let closure = composable.editing {
closure(composable)
}
}
private func _shouldEndEditing() -> Bool {
guard let composable = self.composable else { return true }
if let closure = composable.shouldEndEditing {
return closure(composable)
}
return true
}
private func _endEditing() {
guard let composable = self.composable else { return }
composable.isEditing = self.fieldView.isEditing
if let closure = composable.endEditing {
closure(composable)
}
}
private func _changedHeight() {
guard let composable = self.composable else { return }
composable.height = self.fieldView.textHeight
if let closure = composable.changedHeight {
closure(composable)
}
}
}
| mit | 7f820cef719d0d70d36eadb53859b01f | 34.741935 | 132 | 0.651173 | 5.259494 | false | false | false | false |
saeta/penguin | Tests/PenguinStructuresTests/Tracked.swift | 1 | 1552 | //******************************************************************************
// Copyright 2020 Penguin Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
/// A wrapper over an arbitrary type that can be used to count instances and
/// make sure they're being properly disposed of.
final class Tracked<T> {
/// The wrapped value.
var value: T
/// An arbitrary counter of instances.
///
/// This function that is passed 1 for each instance of `self` created, and -1
/// for each instance destroyed.
let track: (Int) -> Void
/// Creates an instance holding `value` and invoking `track` to count
/// instances.
///
/// - Parameter track: called with 1 for each instance of `self` created, and
/// -1 for each instance destroyed.
init(_ value: T, track: @escaping (Int)->Void) {
self.value = value
self.track = track
track(1)
}
deinit { track(-1) }
}
extension Tracked: Equatable where T: Equatable {
static func == (lhs: Tracked, rhs: Tracked) -> Bool { lhs.value == rhs.value }
}
| apache-2.0 | ab3c7e287d71c9a534155b638968145b | 33.488889 | 80 | 0.653995 | 4.217391 | false | false | false | false |
danghoa/GGModules | GGModules/Controllers/GGNetwork/GGCore/GGWSError.swift | 1 | 820 | //
// GGWSError.swift
// SwiftTutorial
//
// Created by Đăng Hoà on 8/12/15.
// Copyright (c) 2015 ___GREENGLOBAL___. All rights reserved.
//
import UIKit
let GGWSErrorNotification: String = "GGWSErrorNotification"
class GGWSError: NSObject {
static var _error: GGWSError!
/**
* Property of class
* @property error_id : id of error
* @property error_msg : message of error
*/
var error_id: Int = 0
var error_msg: String = ""
/**
* Function share instance error
*/
class func errorWithMessage(_ msg: String) -> GGWSError {
if _error == nil {
_error = GGWSError()
_error.error_id = 69
_error.error_msg = msg
return _error
} else {
_error.error_id = 69
_error.error_msg = msg
return _error;
}
}
}
| mit | 571ced83c22b1e665b821d891df0f789 | 17.155556 | 62 | 0.585067 | 3.583333 | false | false | false | false |
huankong/Weibo | Weibo/Weibo/Lib/Tools/DataServer.swift | 1 | 1499 | //
// DataServer.swift
// Weibo
//
// Created by ldy on 16/7/4.
// Copyright © 2016年 ldy. All rights reserved.
//
import UIKit
import AFNetworking
public enum NetMethod: String {
case GET = "GET"
case POST = "POST"
}
class DataServer: AFHTTPSessionManager {
let dateBaseURL: String = "https://api.weibo.com/"
private static let instance: DataServer = {
let instance = DataServer()
instance.responseSerializer.acceptableContentTypes?.insert("text/plain")
return instance
}()
class func shareInstance() -> DataServer {
return instance
}
//回调别名
typealias SuccessCallBack = (response: AnyObject?) -> ()
typealias FailureCallBack = (error: NSError?) -> ()
func requsetData(method: NetMethod,urlStr: String,paramer: AnyObject?,success: SuccessCallBack,failure: FailureCallBack){
let urlStr = dateBaseURL + urlStr
switch method {
case .GET:
GET(urlStr, parameters: paramer,progress: nil, success: { (_,response: AnyObject?) in
success(response: response)
},failure: { (_,error: NSError) in
failure(error: error)
})
case .POST:
POST(urlStr, parameters: paramer,progress: nil, success: { (_, response: AnyObject?) in
success(response: response)
}, failure: { (_, error: NSError) in
failure(error: error)
})
}
}
}
| apache-2.0 | 06d0953c9503da0a090289a2d45292b7 | 32.066667 | 125 | 0.592742 | 4.495468 | false | false | false | false |
wuhduhren/Mr-Ride-iOS | Mr-Ride-iOS/Model/StopWatch.swift | 1 | 1046 | //
// StopWatch.swift
// Mr-Ride-iOS
//
// Created by Eph on 2016/5/29.
// Copyright © 2016年 AppWorks School WuDuhRen. All rights reserved.
//
import Foundation
class Stopwatch {
init() { }
private var startTime: NSDate?
var intervalBeforPause: NSTimeInterval?
var elapsedTimeLabelText: String = ""
var elapsedTime: NSTimeInterval {
if let startTime = self.startTime {
return -startTime.timeIntervalSinceNow
} else {
return 0
}
}
var isRunning: Bool {
return startTime != nil
}
func start() {
startTime = NSDate()
}
func stop() {
elapsedTimeLabelText = "00:00:00.00"
intervalBeforPause = nil
startTime = nil
}
func pause() {
if intervalBeforPause != nil {
intervalBeforPause = elapsedTime + intervalBeforPause!
} else {
intervalBeforPause = elapsedTime
}
startTime = nil
}
} | mit | f2762ec486017b9c7658029340ddf153 | 18.698113 | 68 | 0.548418 | 4.615044 | false | false | false | false |
KennethTsang/GrowingTextView | Example/GrowingTextView/Example3.swift | 1 | 1642 | //
// Example3.swift
// GrowingTextView
//
// Created by Kenneth on 29/7/2017.
// Copyright © 2017 CocoaPods. All rights reserved.
//
import UIKit
import GrowingTextView
class Example3: UIViewController {
@IBOutlet weak var textView: GrowingTextView!
override func viewDidLoad() {
super.viewDidLoad()
// *** Customize GrowingTextView ***
textView.layer.cornerRadius = 4.0
textView.placeholder = "Say something..."
textView.font = UIFont.systemFont(ofSize: 15)
textView.minHeight = 30
textView.maxHeight = 100
// *** Hide keyboard when tapping outside ***
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(tapGestureHandler))
view.addGestureRecognizer(tapGesture)
}
@objc func tapGestureHandler() {
view.endEditing(true)
}
@IBAction func minHeightChanged(_ sender: UISegmentedControl) {
textView.minHeight = sender.selectedSegmentIndex == 0 ? 30 : 60
}
@IBAction func maxHeightChanged(_ sender: UISegmentedControl) {
textView.maxHeight = sender.selectedSegmentIndex == 0 ? 100 : 150
}
}
extension Example3: GrowingTextViewDelegate {
// *** Call layoutIfNeeded on superview for animation when changing height ***
func textViewDidChangeHeight(_ textView: GrowingTextView, height: CGFloat) {
UIView.animate(withDuration: 0.3, delay: 0.0, usingSpringWithDamping: 0.7, initialSpringVelocity: 0.7, options: [.curveLinear], animations: { () -> Void in
self.view.layoutIfNeeded()
}, completion: nil)
}
}
| mit | 366b757dd0d17fb59fe2db67aa3bdaac | 29.962264 | 163 | 0.660573 | 4.942771 | false | false | false | false |
CoderLiLe/Swift | 函数定义/main.swift | 1 | 2570 | //
// main.swift
// 函数定义
//
// Created by LiLe on 15/3/17.
// Copyright (c) 2015年 LiLe. All rights reserved.
//
import Foundation
/*
函数: 完成某个特定任务的代码块, 给代码起一个合适的名称称之为函数名称. 以后需要执行代码块只需要利用函数名称调用即可, 好比每个人都有一个名字, 叫名字就能找到对应的人
格式:
func 函数名称(参数名:参数类型, 参数名:参数类型...) -> 函数返回值 {函数实现部分}
OC:
- (void)say
{
NSLog(@"hello");
}
- (void)sayWithName:(NSString *)name
{
NSLog(@"hello %@", name);
}
- (void)sayWithName:(NSString *)name age:(NSInteger)age
{
NSLog(@"hello %@ , I'm %tu years old", name, age);
}
- (NSString *)info
{
return @"name = lnj, age = 30";
}
- (NSString *)infoWithName:(NSString *)name age:(NSInteger)age
{
return [NSString stringWithFormat:@"name = %@, age = %tu", name, age];
}
Person *p = [[Person alloc] init];
[p say];
[p sayWithName:@"lnj"];
[p sayWithName:@"lnj" age:30];
NSLog(@"%@", [p info]);
NSLog(@"%@", [p infoWithName:@"lnj" age:30]);
*/
// 无参无返回值
func say() -> Void
{
print("hello")
}
func say1() // 如果没有返回值可以不写
{
print("hello")
}
say1()
// 有参无返回值
func sayWithName(_ name:String)
{
print("hello \(name)")
}
sayWithName("lnj")
func sayWithName1(_ name:String, age:Int)
{
print("hello \(name) , I'm \(age) years old ")
}
sayWithName1("lnj", age: 30)
// 无参有返回值
func info() -> String
{
return "name = lnj, age = 30"
}
print(info())
// 有参有返回值
func info(_ name:String, age:Int) -> String
{
return "name = \(name), age = \(age)"
}
print(info("lnj", age:30))
/*
嵌套函数
*/
func showArray(_ array:[Int])
{
for number in array
{
print("\(number), ")
}
}
/*
func swap(inout a:Int, inout b:Int)
{
let temp = a
a = b
b = temp
}
*/
var number = 998;
func bubbleSort(_ array:inout [Int])
{
print(number)
func swap(_ a:inout Int, b:inout Int)
{
print(number)
let temp = a
a = b
b = temp
}
let count = array.count;
for i in 1 ..< count
{
for j in 0 ..< (count - i)
{
if array[j] > array[j + 1]
{
swap(&array[j], b: &array[j + 1])
// let temp = array[j]
// array[j] = array[j + 1]
// array[j + 1] = temp
}
}
}
}
var arr:Array<Int> = [31, 13, 52, 84, 5]
bubbleSort(&arr)
showArray(arr)
| mit | b8453db09d9621231f628a0cfc0470ba | 15.554745 | 86 | 0.53836 | 2.817391 | false | false | false | false |
voudeonibus/vdb-ios | Drifter/Line.swift | 1 | 392 | //
// Line.swift
// Drifter
//
// Created by Lucas da Silva on 2/1/16.
// Copyright © 2016 Vou de ônibus. All rights reserved.
//
import Foundation
import RealmSwift
class Line: Object {
dynamic var _id = ""
dynamic var route_long_name = ""
dynamic var route_short_name = ""
dynamic var country = ""
dynamic var state = ""
let trips = List<Trip>()
}
| mit | 5fa23651736b48485450de53be60ead2 | 17.571429 | 56 | 0.610256 | 3.421053 | false | false | false | false |
MrPudin/Skeem | IOS/Prevoir/TaskListVC.swift | 1 | 4967 | //
// TaskListVC.swift
// Skeem
//
// Created by Zhu Zhan Yan on 2/11/16.
// Copyright © 2016 SSTInc. All rights reserved.
//
import UIKit
class TaskListVC: UITableViewController
{
//Link
var DBC:SKMDataController!
//Data
var arr_task:Array<SKMTask>!
//Data Functions
/*
* public func updateData()
* - Updates data to reflect database
*/
public func updateData()
{
//Update Data
self.DBC.updateTask()
self.arr_task = self.DBC.sortedTask(sattr: SKMTaskSort.deadline)
}
//UI Functions
/*
* public func updateUI()
* - Triggers UI update to reflect current data
*/
public func updateUI()
{
//Relead UI Data
self.tableView.reloadData()
}
//Event Functions
override func viewDidLoad() {
self.DBC = (UIApplication.shared.delegate as! AppDelegate).DBC
self.arr_task = Array<SKMTask>()
self.updateData()
//Reload UI Data
super.viewDidLoad()
}
override func viewWillAppear(_ animated: Bool) {
self.updateData()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
let section = 1 //Only one section
return section
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
switch section {
case 0:
//First Section
return self.arr_task.count
default:
abort() //Unhanded Section
}
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if self.arr_task.count > 0
{
//Create/Update Table View Cell
let cell = (tableView.dequeueReusableCell(withIdentifier: "uitcell.list.task", for: indexPath) as! TaskListTBC)
let task = self.arr_task[indexPath.row]
cell.updateUI(name: task.name, subject: task.subject ,completion: task.completion)
return cell
}
else
{
//Empty Void Duration Cell
let cell = tableView.dequeueReusableCell(withIdentifier: "uitcell.list.task.null")!
return cell
}
}
override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
if self.arr_task.count <= 0
{
//Cannot Edit Null cell
return false
}
else
{
return true
}
}
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == UITableViewCellEditingStyle.delete {
//Delete From Database
switch indexPath.section {
case 0:
//First Section
let task = self.arr_task[indexPath.row]
let rst = self.DBC.deleteTask(name: task.name)
assert(rst) //Terminates Executable if delete fails
default:
abort() //Unhandled Section
}
self.updateData()
//Delete From UI
tableView.deleteRows(at: [indexPath], with: UITableViewRowAnimation.fade)
}
else if editingStyle == UITableViewCellEditingStyle.insert {
//Data Should be in database
tableView.insertRows(at: [indexPath], with: UITableViewRowAnimation.automatic)
}
}
// MARK: - Navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let sge_idf = segue.identifier
{
switch sge_idf {
case "uisge.task.add":
//Add Segue
let taskeditvc = (segue.destination as! TaskEditVC)
let _ = taskeditvc.view //Force View Load
taskeditvc.loadAddTask()
case "uisge.task.edit":
//Edit Segue
let taskeditvc = (segue.destination as! TaskEditVC)
let _ = taskeditvc.view //Force View Load
let task = self.arr_task[self.tableView.indexPathForSelectedRow!.row]
taskeditvc.loadEditTask(task: task)
default:
//Unhandled Segue
abort()
}
}
else
{
abort()
}
}
@IBAction func unwind_taskListVC(sge:UIStoryboardSegue)
{
if let sge_idf = sge.identifier
{
switch sge_idf {
case "uisge.task.list.unwind":
//Update UI for current data
self.updateData()
self.updateUI()
default:
abort()
}
}
else
{
abort()
}
}
}
| mit | f5bcd19fa075c8ebcd3b31911c774271 | 26.898876 | 136 | 0.55437 | 4.878193 | false | false | false | false |
tnantoka/edhita | Edhita/Views/FontSettingsView.swift | 1 | 2453 | //
// FontSettingsView.swift
// Edhita
//
// Created by Tatsuya Tobioka on 2022/08/02.
//
import SwiftUI
struct FontSettingsView: View {
@State var fontName = Settings.shared.fontName
@State var fontSize = Settings.shared.fontSize
@State var textColor = Settings.shared.textColor
@State var backgroundColor = Settings.shared.backgroundColor
var body: some View {
Form {
Section(header: Text("Settings")) {
Picker("Font name", selection: $fontName) {
ForEach(FontManager.shared.fontNames, id: \.self) { name in
Text(name).font(FontManager.font(for: name))
}
}
Picker("Font size", selection: $fontSize) {
ForEach(FontManager.shared.fontSizes, id: \.self) { size in
Text("\(Int(size))").font(.system(size: fontSize))
}
}
ColorPicker("Text color", selection: $textColor)
ColorPicker("Background color", selection: $backgroundColor)
}
Section(header: Text("Preview")) {
Text("ABCDEFGHIJKLM NOPQRSTUVWXYZ abcdefghijklm nopqrstuvwxyz 1234567890")
.font(.custom(fontName, size: fontSize))
.foregroundColor(textColor)
.background(backgroundColor)
}
}
.navigationTitle("Font")
.navigationBarTitleDisplayMode(.inline)
.toolbar {
ToolbarItem(placement: .navigationBarTrailing) {
Button("Reset") {
fontName = FontManager.defaultFontName
fontSize = FontManager.defaultFontSize
textColor = FontManager.defaultTextColor
backgroundColor = FontManager.defaultBackgroundColor
}
}
}
.onChange(of: fontName) {
Settings.shared.fontName = $0
}
.onChange(of: fontSize) {
Settings.shared.fontSize = $0
}
.onChange(of: textColor) {
Settings.shared.textColor = $0
}
.onChange(of: backgroundColor) {
Settings.shared.backgroundColor = $0
}
}
}
struct FontSettingsView_Previews: PreviewProvider {
static var previews: some View {
NavigationView {
FontSettingsView()
}
}
}
| mit | 4d6fab9f001990826d6fa204fb38693a | 33.069444 | 90 | 0.543009 | 5.197034 | false | false | false | false |
sharkspeed/dororis | platforms/iOS/FoodTracker/FoodTrackerTests/FoodTrackerTests.swift | 1 | 1966 | //
// FoodTrackerTests.swift
// FoodTrackerTests
//
// Created by liuxiangyu on 5/6/17.
// Copyright © 2017 42vision. All rights reserved.
//
import XCTest
@testable import FoodTracker
//class FoodTrackerTests: XCTestCase {
//
// override func setUp() {
// super.setUp()
// // Put setup code here. This method is called before the invocation of each test method in the class.
// }
//
// override func tearDown() {
// // Put teardown code here. This method is called after the invocation of each test method in the class.
// super.tearDown()
// }
//
// func testExample() {
// // This is an example of a functional test case.
// // Use XCTAssert and related functions to verify your tests produce the correct results.
// }
//
// func testPerformanceExample() {
// // This is an example of a performance test case.
// self.measure {
// // Put the code you want to measure the time of here.
// }
// }
//
//}
class FoodTrackerTests: XCTestCase {
// Mark: Meal Class Tests
// Confirm Meal initializer returns a Meal object when passed valid parameters
func testMealInitializerSucceeds() {
let zeroRatingMeal = Meal.init(name: "Zero", photo: nil, rating: 0)
XCTAssertNotNil(zeroRatingMeal)
let positiveRatingMeal = Meal.init(name: "Positive", photo: nil, rating: 5)
XCTAssertNotNil(positiveRatingMeal)
}
func testMealInitializerFails() {
let negativeRatingMeal = Meal.init(name: "Negative", photo: nil, rating: -1)
XCTAssertNil(negativeRatingMeal)
// Empty String
let emptyStringMeal = Meal.init(name: "", photo: nil, rating: 0)
XCTAssertNil(emptyStringMeal)
// Rating exceeds maximum
let largeRatingMeal = Meal.init(name: "Large", photo: nil, rating: 6)
XCTAssertNil(largeRatingMeal)
}
}
| bsd-2-clause | 602add07582fe0221622b46d0ee69506 | 30.693548 | 113 | 0.625445 | 4.309211 | false | true | false | false |
vsubrahmanian/iRemind | iRemind/ReminderListTableVC.swift | 2 | 3154 | //
// ReminderListTableVC.swift
// iRemind
//
// Created by Vijay Subrahmanian on 03/06/15.
// Copyright (c) 2015 Vijay Subrahmanian. All rights reserved.
//
import UIKit
class ReminderListTableVC: UITableViewController, UITableViewDataSource, UITableViewDelegate {
var reminderList = (UIApplication.sharedApplication().delegate as! AppDelegate).reminderList
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
self.reminderList = (UIApplication.sharedApplication().delegate as! AppDelegate).reminderList
self.tableView.reloadData()
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
if count(self.reminderList) > 0 {
return 2
}
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if section == 0 {
return 1 // First section contains Add Reminder Cell.
}
return self.reminderList.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
if indexPath.section == 0 {
let cell = tableView.dequeueReusableCellWithIdentifier("AddReminder") as! UITableViewCell
cell.textLabel?.text = "Create New Reminder"
return cell
}
let cell = tableView.dequeueReusableCellWithIdentifier("ReminderInfo") as! UITableViewCell
let reminderInfo = self.reminderList[indexPath.row] as ReminderInfoModel
cell.textLabel?.text = reminderInfo.name
let dateFormat = NSDateFormatter()
dateFormat.dateStyle = NSDateFormatterStyle.ShortStyle
dateFormat.timeStyle = NSDateFormatterStyle.ShortStyle
cell.detailTextLabel?.text = dateFormat.stringFromDate(reminderInfo.time!)
return cell
}
override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
if section == 0 {
return "New Reminder"
}
return "Reminders"
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
var aReminderInfo: ReminderInfoModel
let reminderInfoVC = self.storyboard!.instantiateViewControllerWithIdentifier("ReminderInfoVCID") as! ReminderInfoVC
if indexPath.section == 0 {
reminderInfoVC.reminderInfo = ReminderInfoModel()
} else {
reminderInfoVC.reminderInfo = self.reminderList[indexPath.row]
reminderInfoVC.index = indexPath.row
}
self.navigationController?.pushViewController(reminderInfoVC, animated: true)
tableView.deselectRowAtIndexPath(indexPath, animated: true)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| apache-2.0 | 0f99e05029134bdbc6e1e48265cef9f1 | 33.659341 | 124 | 0.674065 | 5.592199 | false | false | false | false |
tomquist/CoreJSON | Sources/CoreJSONLiterals/JSONLiterals.swift | 1 | 2506 | /**
* CoreJSON
*
* Copyright (c) 2016 Tom Quist. Licensed under the MIT license, as follows:
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#if SWIFT_PACKAGE
import CoreJSON
#endif
extension JSON: ExpressibleByIntegerLiteral {
public init(integerLiteral value: Int) {
self = .number(.int(value))
}
}
extension JSON: ExpressibleByNilLiteral {
public init(nilLiteral: ()) {
self = .null
}
}
extension JSON: ExpressibleByStringLiteral {
public init(unicodeScalarLiteral value: String) {
self = .string(value)
}
public init(extendedGraphemeClusterLiteral value: String) {
self = .string(value)
}
public init(stringLiteral value: String) {
self = .string(value)
}
}
extension JSON: ExpressibleByFloatLiteral {
public init(floatLiteral value: Double) {
self = .number(.double(value))
}
}
extension JSON: ExpressibleByBooleanLiteral {
public init(booleanLiteral value: Bool) {
self = .bool(value)
}
}
extension JSON: ExpressibleByArrayLiteral {
public init(arrayLiteral elements: JSON...) {
self = .array(elements)
}
}
extension JSON: ExpressibleByDictionaryLiteral {
public init(dictionaryLiteral elements: (String, JSON)...) {
self = .object(elements.reduce([:]) { (dict, tuple) -> [String: JSON] in
var dict = dict
dict[tuple.0] = tuple.1
return dict
})
}
}
| mit | c46563e9d6642204b31c03ff8cb0a7c5 | 30.721519 | 82 | 0.688348 | 4.396491 | false | false | false | false |
AnRanScheme/magiGlobe | magi/magiGlobe/magiGlobe/Classes/Tool/Extension/AVFoundation/AVAsset/AVAsset+Man.swift | 1 | 3738 | //
// AVAsset+Man.swift
// swift-magic
//
// Created by 安然 on 17/2/15.
// Copyright © 2017年 安然. All rights reserved.
//
import AVFoundation
public extension AVAsset {
public var m_title: String? {
var error: NSError?
let status = self.statusOfValue(forKey: "commonMetadata", error: &error)
if error != nil {
return nil
}
if status == .loaded{
let metadataItems = AVMetadataItem.metadataItems(from: self.commonMetadata, withKey: AVMetadataCommonKeyTitle, keySpace: AVMetadataKeySpaceCommon)
if metadataItems.count > 0 {
let titleItem = metadataItems.first
return titleItem?.value as? String
}
}
return nil
}
/// 获取所有cc
public var m_closedCaption: [AVMediaSelectionOption]? {
var closedCaptions = [AVMediaSelectionOption]()
if let mediaSelectionGroup = self.mediaSelectionGroup(forMediaCharacteristic: AVMediaCharacteristicLegible){
for option in mediaSelectionGroup.options {
if option.mediaType == "clcp" {
closedCaptions.append(option)
}
}
}
if closedCaptions.count > 0{
return closedCaptions
}
return nil
}
/// 获取所有subtitle
public var m_subtitles: [(subtitle: AVMediaSelectionOption,localDisplayName: String)]? {
var subtitles = [(subtitle: AVMediaSelectionOption,localDisplayName: String)]()
if let mediaSelectionGroup = self.mediaSelectionGroup(forMediaCharacteristic: AVMediaCharacteristicLegible){
for option in mediaSelectionGroup.options {
if !option.hasMediaCharacteristic(AVMediaCharacteristicContainsOnlyForcedSubtitles) {
if let localDisplayName = self.m_localDisplayName(forMediaSelectionOption: option){
subtitles.append((option,localDisplayName))
}
}
}
}
if subtitles.count > 0{
return subtitles
}
return nil
}
/// 获取所有audio
public var m_audios: [(audio: AVMediaSelectionOption,localDisplayName: String)]? {
var audios = [(audio: AVMediaSelectionOption,localDisplayName: String)]()
if let mediaSelectionGroup = self.mediaSelectionGroup(forMediaCharacteristic: AVMediaCharacteristicAudible){
for option in mediaSelectionGroup.options {
if let localDisplayName = self.m_localDisplayName(forMediaSelectionOption: option){
audios.append((option,localDisplayName))
}
}
if audios.count > 0{
return audios
}
}
return nil
}
public func m_localDisplayName(forMediaSelectionOption subtitle: AVMediaSelectionOption) -> String?{
var title: String? = nil
var metadataItems = AVMetadataItem.metadataItems(from: subtitle.commonMetadata, withKey: AVMetadataCommonKeyTitle, keySpace: AVMetadataKeySpaceCommon)
if metadataItems.count > 0 {
let preferredLanguages = NSLocale.preferredLanguages
for language: String in preferredLanguages {
let locale = Locale(identifier: language)
var titlesForLocale = AVMetadataItem.metadataItems(from: metadataItems, with: locale)
if titlesForLocale.count > 0 {
title = titlesForLocale[0].stringValue
break
}
}
if title == nil {
title = metadataItems[0].stringValue
}
}
return title
}
}
| mit | dbcc68ed7f4c6e60518d6d0ec016c6d7 | 36.785714 | 158 | 0.607345 | 5.208158 | false | false | false | false |
maximedegreve/TinyFaces | Sources/App/Tools/Cloudinary/CloudinaryRequest.swift | 1 | 797 | //
// CloudinaryRequest.swift
// App
//
// Created by Maxime on 28/06/2020.
//
import Vapor
struct CloudinaryRequest: Error, Content {
var apiKey: String
var signature: String
var file: File
var timestamp: Int
var folder: String?
var eager: String?
var publicId: String?
var transformation: String?
var allowedFormats: String?
var format: String?
enum CodingKeys: String, CodingKey {
case file = "file"
case apiKey = "api_key"
case publicId = "public_id"
case folder = "folder"
case signature = "signature"
case timestamp = "timestamp"
case eager = "eager"
case transformation = "transformation"
case allowedFormats = "allowed_formats"
case format = "format"
}
}
| mit | b0d0b2b61b306f95597c6898760af504 | 22.441176 | 47 | 0.61857 | 4.194737 | false | false | false | false |
sbcmadn1/swift | swiftweibo05/GZWeibo05/Class/Model/CZUserAccount.swift | 2 | 5403 | //
// CZUserAccount.swift
// GZWeibo05
//
// Created by zhangping on 15/10/28.
// Copyright © 2015年 zhangping. All rights reserved.
//
import UIKit
/*
iOS保存数据的方式:
1.plist
2.偏好设置
3.归档
4.sqlite
5.CoreData
*/
class CZUserAccount: NSObject, NSCoding {
// class var userLogin2: Bool {
// get {
// return CZUserAccount.loadAccount() != nil
// }
// }
// 当做类方法. 返回值就是属性的类型
// 有账号返回true
class func userLogin() -> Bool {
return CZUserAccount.loadAccount() != nil
}
/// 用于调用access_token,接口获取授权后的access token
var access_token: String?
/// access_token的生命周期,单位是秒数
/// 对于基本数据类型不能定义为可选
var expires_in: NSTimeInterval = 0 {
didSet {
expires_date = NSDate(timeIntervalSinceNow: expires_in)
print("expires_date:\(expires_date)")
}
}
/// 当前授权用户的UID
var uid: String?
/// 过期时间
var expires_date: NSDate?
/// 友好显示名称
var name: String?
/// 用户头像地址(大图),180×180像素
var avatar_large: String?
// KVC 字典转模型
init(dict: [String: AnyObject]) {
super.init()
// 将字典里面的每一个key的值赋值给对应的模型属性
setValuesForKeysWithDictionary(dict)
}
// 当字典里面的key在模型里面没有对应的属性
override func setValue(value: AnyObject?, forUndefinedKey key: String) {}
override var description: String {
return "access_token:\(access_token), expires_in:\(expires_in), uid:\(uid): expires_date:\(expires_date), name:\(name), avatar_large:\(avatar_large)"
}
// MARK: - 加载用户信息
// 控制调用这个方法,不管成功还是失败,都需要告诉调用者
func loadUserInfo(finish: (error: NSError?) -> ()) {
CZNetworkTools.sharedInstance.loadUserInfo { (result, error) -> () in
if error != nil || result == nil {
finish(error: error)
return
}
// 加载成功
self.name = result!["name"] as? String
self.avatar_large = result!["avatar_large"] as? String
// 保存到沙盒
self.saveAccount()
// 同步到内存中,把当前对象赋值给内存中的 userAccount
CZUserAccount.userAccount = self
finish(error: nil)
}
}
// 类方法访问属性需要将属性定义成 static
// 对象方法访问static属性需要 类名.属性名称
static let accountPath = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last! + "/Account.plist"
// MARK: - 保存对象
func saveAccount() {
// account.plist
NSKeyedArchiver.archiveRootObject(self, toFile: CZUserAccount.accountPath)
}
// 类方法访问属性需要将属性定义成 static
private static var userAccount: CZUserAccount?
// 加载loadAccount 是用频繁,解档账号比较耗性能,只加载一次,保存到内存中,以后访问内存的中账号
class func loadAccount() -> CZUserAccount? {
// 判断内存有没有
if userAccount == nil {
// 内存中没有才来解档,并赋值给内存中的账号
userAccount = NSKeyedUnarchiver.unarchiveObjectWithFile(accountPath) as? CZUserAccount
}
// 判断如果有账号,还需要判断是否过期
// NSDate(): 表示当前时间 2015
// userAccount?.expires_date: 2020
// userAccount?.expires_date > NSDate(): 没有过期
// OrderedAscending (<) OrderedSame (=) OrderedDescending (>)
// 测试时间过期
// userAccount?.expires_date = NSDate(timeIntervalSinceNow: -100) // 比当前时间早100秒
// print(userAccount?.expires_date)
// print("当前时间:\(NSDate())")
if userAccount != nil && userAccount?.expires_date?.compare(NSDate()) == NSComparisonResult.OrderedDescending {
// print("账号有效")
return userAccount
}
return nil
}
// MARK: - 归档和解档
func encodeWithCoder(aCoder: NSCoder) {
aCoder.encodeObject(access_token, forKey: "access_token")
aCoder.encodeDouble(expires_in, forKey: "expires_in")
aCoder.encodeObject(uid, forKey: "uid")
aCoder.encodeObject(expires_date, forKey: "expires_date")
aCoder.encodeObject(name, forKey: "name")
aCoder.encodeObject(avatar_large, forKey: "avatar_large")
}
required init?(coder aDecoder: NSCoder) {
access_token = aDecoder.decodeObjectForKey("access_token") as? String
expires_in = aDecoder.decodeDoubleForKey("expires_in")
uid = aDecoder.decodeObjectForKey("uid") as? String
expires_date = aDecoder.decodeObjectForKey("expires_date") as? NSDate
name = aDecoder.decodeObjectForKey("name") as? String
avatar_large = aDecoder.decodeObjectForKey("avatar_large") as? String
}
}
| mit | 97e1f038955eb38830414841fa7f4f20 | 29.490196 | 175 | 0.593783 | 4.26807 | false | false | false | false |
evfemist/HysteriaPlayer | HysteriaPlayerSwiftExample/HysteriaPlayerSwiftExample/ViewController.swift | 3 | 2071 | //
// ViewController.swift
// HysteriaPlayerSwiftExample
//
// Created by Stan on 8/17/15.
// Copyright © 2015 saiday. All rights reserved.
//
import UIKit
import HysteriaPlayer
class ViewController: UIViewController, HysteriaPlayerDelegate, HysteriaPlayerDataSource{
lazy var hysteriaPlayer = HysteriaPlayer.sharedInstance()
override func viewDidLoad() {
super.viewDidLoad()
// This is a very simple project demonstrate how to use
// HysteriaPlayer in Swift, detailed instructions about
// HysteriaPlayer are included in another objc example project.
initHysteriaPlayer()
hysteriaPlayer.fetchAndPlayPlayerItem(0)
}
func initHysteriaPlayer() {
hysteriaPlayer.delegate = self;
hysteriaPlayer.datasource = self;
}
func hysteriaPlayerNumberOfItems() -> Int {
return 3
}
func hysteriaPlayerURLForItemAtIndex(index: Int, preBuffer: Bool) -> NSURL! {
var url: NSURL
switch index {
case 0:
url = NSURL(string: "http://a929.phobos.apple.com/us/r1000/143/Music3/v4/2c/4e/69/2c4e69d7-bd0f-8c76-30ca-75f6a2f51ef5/mzaf_1157339944153759874.plus.aac.p.m4a")!;
break
case 1:
url = NSURL(string: "http://a1136.phobos.apple.com/us/r1000/042/Music5/v4/85/34/8d/85348d57-5bf9-a4a3-9f54-0c3f1d8bc6af/mzaf_5184604190043403959.plus.aac.p.m4a")!;
break
case 2:
url = NSURL(string: "http://a345.phobos.apple.com/us/r1000/046/Music5/v4/52/53/4b/52534b36-620e-d7f3-c9a8-2f9661652ff5/mzaf_2360247732780989514.plus.aac.p.m4a")!;
break
default:
url = NSURL()
break
}
return url;
}
func hysteriaPlayerReadyToPlay(identifier: HysteriaPlayerReadyToPlay) {
switch(identifier) {
case .CurrentItem:
hysteriaPlayer.play()
break
default:
break
}
}
}
| mit | 0639387ec198dea7d6e7d2f6faa6b5d2 | 30.363636 | 179 | 0.611111 | 3.461538 | false | false | false | false |
wookay/AppConsole | Demo/Test/TestApp/TestApp/ViewController.swift | 1 | 1254 | //
// ViewController.swift
// TestApp
//
// Created by wookyoung on 4/3/16.
// Copyright © 2016 factorcat. All rights reserved.
//
import UIKit
class A {
var s = "a string"
var n = 5
var b = true
var t = (5,6)
func f() -> String {
Log.info("a.f")
return "b call"
}
func g(n: Int) -> Int {
Log.info("a.g")
return n+1
}
init() {
}
}
let a = A()
class B: NSObject {
var s = "b string"
var n = 5
var b = true
var t = (5,6)
func f() -> String {
Log.info("b.f")
return "b call"
}
func g(n: Int) -> Int {
Log.info("b.g")
return n+1
}
override init() {
}
}
let b = B()
class ViewController: UIViewController {
@IBOutlet var label: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
label.text = AppConsole(initial: self).run { app in
app.register("a", object: a)
app.register("b", object: b)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
} | mit | 2e2b801f700e2d7dce507da4c1d1d9bb | 16.178082 | 80 | 0.524342 | 3.509804 | false | false | false | false |
DTLivingstone/HypoTrack | HypoTrack/ConfirmationViewController.swift | 1 | 1175 | //
// ConfirmationViewController.swift
// HypoTrack
//
// Created by David Livingstone on 7/1/16.
// Copyright © 2016 David Livingstone. All rights reserved.
//
import UIKit
class ConfirmationViewController: UIViewController, Setup {
@IBOutlet weak var confirmationHeader: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
setupAppearance()
setup()
}
func setupAppearance() {
}
func setup() {
self.navigationItem.title = "Confirmation"
let formatter = NSDateFormatter()
formatter.dateStyle = .MediumStyle
formatter.timeStyle = .NoStyle
formatter.locale = NSLocale(localeIdentifier: "en_US")
let formattedDate = formatter.stringFromDate(thisInjection.date!)
print(thisInjection.date!)
print(formattedDate)
confirmationHeader.text = "\(thisInjection.med), \(thisInjection.dose!), \n \(thisInjection.location!) on \(formattedDate)"
}
@IBAction func confirm(sender: UIButton) {
print("confirm")
injections.append(thisInjection)
print(injections)
}
}
| unlicense | 3251b5835b48ac9b23ab41dc7ce967d9 | 25.088889 | 131 | 0.632879 | 4.85124 | false | false | false | false |
RocketChat/Rocket.Chat.iOS | Rocket.Chat/Models/Attachment/Attachment.swift | 1 | 3525 | //
// Attachment.swift
// Rocket.Chat
//
// Created by Rafael K. Streit on 01/10/16.
// Copyright © 2016 Rocket.Chat. All rights reserved.
//
import Foundation
import SwiftyJSON
import RealmSwift
class AttachmentField: Object {
@objc dynamic var short: Bool = false
@objc dynamic var title: String = ""
@objc dynamic var value: String = ""
}
class Attachment: BaseModel {
var type: MessageType {
guard let validatedAttachment = validated() else {
// FA NOTE: Returning the default MessageType for an invalidated object since there's no invalid MessageType
return .textAttachment
}
if !(validatedAttachment.audioURL?.isEmpty ?? true) {
return .audio
}
if !(validatedAttachment.videoURL?.isEmpty ?? true) {
return .video
}
if !(validatedAttachment.imageURL?.isEmpty ?? true) {
return .image
}
return .textAttachment
}
var isFile: Bool {
return titleLinkDownload && !titleLink.isEmpty
}
@objc dynamic var collapsed: Bool = false
@objc dynamic var text: String?
@objc dynamic var descriptionText: String?
@objc dynamic var thumbURL: String?
@objc dynamic var color: String?
@objc dynamic var title = ""
@objc dynamic var titleLink = ""
@objc dynamic var titleLinkDownload = true
@objc dynamic var imageURL: String?
@objc dynamic var imageType: String?
@objc dynamic var imageSize = 0
@objc dynamic var audioURL: String?
@objc dynamic var audioType: String?
@objc dynamic var audioSize = 0
@objc dynamic var videoURL: String?
@objc dynamic var videoType: String?
@objc dynamic var videoSize = 0
var videoThumbPath: URL? {
let path = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
let documents = path[0]
let thumbName = videoURL?.replacingOccurrences(of: "/", with: "\\") ?? "temp"
return documents.appendingPathComponent("\(thumbName).png")
}
var fields = List<AttachmentField>()
override class func ignoredProperties() -> [String] {
return ["videoThumb"]
}
}
extension Attachment {
fileprivate static func fullURLWith(_ path: String?, auth: Auth? = nil) -> URL? {
guard let path = path else { return nil }
if path.contains("http://") || path.contains("https://") {
return URL(string: path)
}
let pathClean = path.replacingOccurrences(of: "//", with: "/")
guard
let pathPercentEncoded = NSString(string: pathClean).addingPercentEncoding(withAllowedCharacters: .urlPathAllowed),
let auth = auth ?? AuthManager.isAuthenticated(),
let userId = auth.userId,
let token = auth.token,
let baseURL = auth.baseURL()
else {
return nil
}
let urlString = "\(baseURL)\(pathPercentEncoded)?rc_uid=\(userId)&rc_token=\(token)"
return URL(string: urlString)
}
func fullFileURL(auth: Auth? = nil) -> URL? {
return Attachment.fullURLWith(titleLink, auth: auth)
}
func fullVideoURL(auth: Auth? = nil) -> URL? {
return Attachment.fullURLWith(videoURL, auth: auth)
}
func fullImageURL(auth: Auth? = nil) -> URL? {
return Attachment.fullURLWith(imageURL, auth: auth)
}
func fullAudioURL(auth: Auth? = nil) -> URL? {
return Attachment.fullURLWith(audioURL, auth: auth)
}
}
| mit | 93174e57a738231671c3d5a67a98cf9e | 28.123967 | 127 | 0.624291 | 4.523748 | false | false | false | false |
ben-ng/swift | test/Constraints/operator.swift | 1 | 2228 | // RUN: %target-typecheck-verify-swift
// Use operators defined within a type.
struct S0 {
static func +(lhs: S0, rhs: S0) -> S0 { return lhs }
}
func useS0(lhs: S0, rhs: S0) {
_ = lhs + rhs
}
// Use operators defined within a generic type.
struct S0b<T> {
static func + <U>(lhs: S0b<T>, rhs: U) -> S0b<U> { return S0b<U>() }
}
func useS0b(s1i: S0b<Int>, s: String) {
var s1s = s1i + s
s1s = S0b<String>()
_ = s1s
}
// Use operators defined within a protocol extension.
infix operator %%%
infix operator %%%%
protocol P1 {
static func %%%(lhs: Self, rhs: Self) -> Bool
}
extension P1 {
static func %%%%(lhs: Self, rhs: Self) -> Bool {
return !(lhs %%% rhs)
}
}
func useP1Directly<T : P1>(lhs: T, rhs: T) {
_ = lhs %%% rhs
_ = lhs %%%% rhs
}
struct S1 : P1 {
static func %%%(lhs: S1, rhs: S1) -> Bool { return false }
}
func useP1Model(lhs: S1, rhs: S1) {
_ = lhs %%% rhs
_ = lhs %%%% rhs
}
struct S1b<T> : P1 {
static func %%%(lhs: S1b<T>, rhs: S1b<T>) -> Bool { return false }
}
func useP1ModelB(lhs: S1b<Int>, rhs: S1b<Int>) {
_ = lhs %%% rhs
_ = lhs %%%% rhs
}
func useP1ModelBGeneric<T>(lhs: S1b<T>, rhs: S1b<T>) {
_ = lhs %%% rhs
_ = lhs %%%% rhs
}
// Use operators defined within a protocol extension to satisfy a requirement.
protocol P2 {
static func %%%(lhs: Self, rhs: Self) -> Bool
static func %%%%(lhs: Self, rhs: Self) -> Bool
}
extension P2 {
static func %%%%(lhs: Self, rhs: Self) -> Bool {
return !(lhs %%% rhs)
}
}
func useP2Directly<T : P2>(lhs: T, rhs: T) {
_ = lhs %%% rhs
_ = lhs %%%% rhs
}
struct S2 : P2 {
static func %%%(lhs: S2, rhs: S2) -> Bool { return false }
}
func useP2Model(lhs: S2, rhs: S2) {
_ = lhs %%% rhs
_ = lhs %%%% rhs
}
struct S2b<T> : P2 {
static func %%%(lhs: S2b<T>, rhs: S2b<T>) -> Bool { return false }
}
func useP2Model2(lhs: S2b<Int>, rhs: S2b<Int>) {
_ = lhs %%% rhs
_ = lhs %%%% rhs
}
func useP2Model2Generic<T>(lhs: S2b<T>, rhs: S2b<T>) {
_ = lhs %%% rhs
_ = lhs %%%% rhs
}
// Using an extension of one protocol to satisfy another conformance.
protocol P3 { }
extension P3 {
static func ==(lhs: Self, rhs: Self) -> Bool {
return true
}
}
struct S3 : P3, Equatable { }
| apache-2.0 | 4c032f5da4c286b0cc1bd809e6973823 | 18.54386 | 78 | 0.566427 | 2.658711 | false | false | false | false |
brandons/Swifter | Swifter/SwifterOAuthClient.swift | 1 | 8182 | //
// SwifterOAuthClient.swift
// Swifter
//
// Copyright (c) 2014 Matt Donnelly.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
#if os(iOS) || os(OSX)
import Accounts
#endif
internal class SwifterOAuthClient: SwifterClientProtocol {
struct OAuth {
static let version = "1.0"
static let signatureMethod = "HMAC-SHA1"
}
var consumerKey: String
var consumerSecret: String
var credential: SwifterCredential?
var dataEncoding: NSStringEncoding
init(consumerKey: String, consumerSecret: String) {
self.consumerKey = consumerKey
self.consumerSecret = consumerSecret
self.dataEncoding = NSUTF8StringEncoding
}
init(consumerKey: String, consumerSecret: String, accessToken: String, accessTokenSecret: String) {
self.consumerKey = consumerKey
self.consumerSecret = consumerSecret
let credentialAccessToken = SwifterCredential.OAuthAccessToken(key: accessToken, secret: accessTokenSecret)
self.credential = SwifterCredential(accessToken: credentialAccessToken)
self.dataEncoding = NSUTF8StringEncoding
}
func get(path: String, baseURL: NSURL, parameters: Dictionary<String, Any>, uploadProgress: SwifterHTTPRequest.UploadProgressHandler?, downloadProgress: SwifterHTTPRequest.DownloadProgressHandler?, success: SwifterHTTPRequest.SuccessHandler?, failure: SwifterHTTPRequest.FailureHandler?) -> SwifterHTTPRequest {
let url = NSURL(string: path, relativeToURL: baseURL)!
let method = "GET"
let request = SwifterHTTPRequest(URL: url, method: method, parameters: parameters)
request.headers = ["Authorization": self.authorizationHeaderForMethod(method, url: url, parameters: parameters, isMediaUpload: false)]
request.downloadProgressHandler = downloadProgress
request.successHandler = success
request.failureHandler = failure
request.dataEncoding = self.dataEncoding
request.start()
return request
}
func post(path: String, baseURL: NSURL, var parameters: Dictionary<String, Any>, uploadProgress: SwifterHTTPRequest.UploadProgressHandler?, downloadProgress: SwifterHTTPRequest.DownloadProgressHandler?, success: SwifterHTTPRequest.SuccessHandler?, failure: SwifterHTTPRequest.FailureHandler?) -> SwifterHTTPRequest {
let url = NSURL(string: path, relativeToURL: baseURL)!
let method = "POST"
var postData: NSData?
var postDataKey: String?
if let key: Any = parameters[Swifter.DataParameters.dataKey] {
if let keyString = key as? String {
postDataKey = keyString
postData = parameters[postDataKey!] as? NSData
parameters.removeValueForKey(Swifter.DataParameters.dataKey)
parameters.removeValueForKey(postDataKey!)
}
}
var postDataFileName: String?
if let fileName: Any = parameters[Swifter.DataParameters.fileNameKey] {
if let fileNameString = fileName as? String {
postDataFileName = fileNameString
parameters.removeValueForKey(fileNameString)
}
}
let request = SwifterHTTPRequest(URL: url, method: method, parameters: parameters)
request.headers = ["Authorization": self.authorizationHeaderForMethod(method, url: url, parameters: parameters, isMediaUpload: postData != nil)]
request.downloadProgressHandler = downloadProgress
request.successHandler = success
request.failureHandler = failure
request.dataEncoding = self.dataEncoding
request.encodeParameters = postData == nil
if postData != nil {
let fileName = postDataFileName ?? "media.jpg"
request.addMultipartData(postData!, parameterName: postDataKey!, mimeType: "application/octet-stream", fileName: fileName)
}
request.start()
return request
}
func authorizationHeaderForMethod(method: String, url: NSURL, parameters: Dictionary<String, Any>, isMediaUpload: Bool) -> String {
var authorizationParameters = Dictionary<String, Any>()
authorizationParameters["oauth_version"] = OAuth.version
authorizationParameters["oauth_signature_method"] = OAuth.signatureMethod
authorizationParameters["oauth_consumer_key"] = self.consumerKey
authorizationParameters["oauth_timestamp"] = String(Int(NSDate().timeIntervalSince1970))
authorizationParameters["oauth_nonce"] = NSUUID().UUIDString
if self.credential?.accessToken != nil {
authorizationParameters["oauth_token"] = self.credential!.accessToken!.key
}
for (key, value): (String, Any) in parameters {
if key.hasPrefix("oauth_") {
authorizationParameters.updateValue(value, forKey: key)
}
}
let combinedParameters = authorizationParameters +| parameters
let finalParameters = isMediaUpload ? authorizationParameters : combinedParameters
authorizationParameters["oauth_signature"] = self.oauthSignatureForMethod(method, url: url, parameters: finalParameters, accessToken: self.credential?.accessToken)
var authorizationParameterComponents = authorizationParameters.urlEncodedQueryStringWithEncoding(self.dataEncoding).componentsSeparatedByString("&") as [String]
authorizationParameterComponents.sortInPlace { $0 < $1 }
var headerComponents = [String]()
for component in authorizationParameterComponents {
let subcomponent = component.componentsSeparatedByString("=") as [String]
if subcomponent.count == 2 {
headerComponents.append("\(subcomponent[0])=\"\(subcomponent[1])\"")
}
}
return "OAuth " + headerComponents.joinWithSeparator(", ")
}
func oauthSignatureForMethod(method: String, url: NSURL, parameters: Dictionary<String, Any>, accessToken token: SwifterCredential.OAuthAccessToken?) -> String {
var tokenSecret: NSString = ""
if token != nil {
tokenSecret = token!.secret.urlEncodedStringWithEncoding(self.dataEncoding)
}
let encodedConsumerSecret = self.consumerSecret.urlEncodedStringWithEncoding(self.dataEncoding)
let signingKey = "\(encodedConsumerSecret)&\(tokenSecret)"
var parameterComponents = parameters.urlEncodedQueryStringWithEncoding(self.dataEncoding).componentsSeparatedByString("&") as [String]
parameterComponents.sortInPlace { $0 < $1 }
let parameterString = parameterComponents.joinWithSeparator("&")
let encodedParameterString = parameterString.urlEncodedStringWithEncoding(self.dataEncoding)
let encodedURL = url.absoluteString.urlEncodedStringWithEncoding(self.dataEncoding)
let signatureBaseString = "\(method)&\(encodedURL)&\(encodedParameterString)"
let signature = signatureBaseString.SHA1DigestWithKey(signingKey)
return signatureBaseString.SHA1DigestWithKey(signingKey).base64EncodedStringWithOptions([])
}
}
| mit | 62ad2dc07e90480431c07fcd5778882e | 44.20442 | 320 | 0.709118 | 5.607951 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.