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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
aschwaighofer/swift | test/expr/closure/inference.swift | 2 | 1891 | // RUN: %target-typecheck-verify-swift
func takeIntToInt(_ f: (Int) -> Int) { }
func takeIntIntToInt(_ f: (Int, Int) -> Int) { }
// Anonymous arguments with inference
func myMap<T, U>(_ array: [T], _ f: (T) -> U) -> [U] {}
func testMap(_ array: [Int]) {
var farray = myMap(array, { Float($0) })
var _ : Float = farray[0]
let farray2 = myMap(array, { x in Float(x) })
farray = farray2
_ = farray
}
// Infer result type.
func testResultType() {
takeIntToInt({x in
return x + 1
})
takeIntIntToInt({x, y in
return 2 + 3
})
}
// Closures with unnamed parameters
func unnamed() {
takeIntToInt({_ in return 1})
takeIntIntToInt({_, _ in return 1})
}
// Regression tests.
var nestedClosuresWithBrokenInference = { f: Int in {} }
// expected-error@-1 {{closure expression is unused}} expected-note@-1 {{did you mean to use a 'do' statement?}} {{53-53=do }}
// expected-error@-2 {{consecutive statements on a line must be separated by ';'}} {{44-44=;}}
// expected-error@-3 {{expected expression}}
// expected-error@-4 {{cannot find 'f' in scope}}
// SR-11540
func SR11540<R>(action: () -> R) -> Void {}
func SR11540<T, R>(action: (T) -> R) -> Void {}
func SR11540_1<T, R>(action: (T) -> R) -> Void {}
SR11540(action: { return }) // Ok SR11540<R>(action: () -> R) was the selected overload.
// In case that's the only possible overload, it's acceptable
SR11540_1(action: { return }) // OK
// SR-8563
func SR8563<A,Z>(_ f: @escaping (A) -> Z) -> (A) -> Z {
return f
}
func SR8563<A,B,Z>(_ f: @escaping (A, B) -> Z) -> (A, B) -> Z {
return f
}
let aa = SR8563 { (a: Int) in }
let bb = SR8563 { (a1: Int, a2: String) in } // expected-note {{'bb' declared here}}
aa(1) // Ok
bb(1, "2") // Ok
bb(1) // expected-error {{missing argument for parameter #2 in call}}
// Tuple
let cc = SR8563 { (_: (Int)) in }
cc((1)) // Ok
cc(1) // Ok
| apache-2.0 | 5b62c8edc09dfdd06a485c00df0c0b1a | 24.213333 | 130 | 0.59175 | 2.96395 | false | false | false | false |
drmohundro/SWXMLHash | Source/XMLElement.swift | 1 | 5729 | //
// XMLElement.swift
// SWXMLHash
//
// Copyright (c) 2022 David Mohundro
//
// 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
/// Models an XML element, including name, text and attributes
public class XMLElement: XMLContent {
/// The name of the element
public let name: String
/// Whether the element is case insensitive or not
public var caseInsensitive: Bool {
options.caseInsensitive
}
var userInfo: [CodingUserInfoKey: Any] {
options.userInfo
}
/// All attributes
public var allAttributes = [String: XMLAttribute]()
/// Find an attribute by name
public func attribute(by name: String) -> XMLAttribute? {
if caseInsensitive {
return allAttributes.first(where: { $0.key.compare(name, true) })?.value
}
return allAttributes[name]
}
/// The inner text of the element, if it exists
public var text: String {
children.reduce("", {
if let element = $1 as? TextElement {
return $0 + element.text
}
return $0
})
}
/// The inner text of the element and its children
public var recursiveText: String {
children.reduce("", {
if let textElement = $1 as? TextElement {
return $0 + textElement.text
} else if let xmlElement = $1 as? XMLElement {
return $0 + xmlElement.recursiveText
} else {
return $0
}
})
}
public var innerXML: String {
children.reduce("", {
$0.description + $1.description
})
}
/// All child elements (text or XML)
public var children = [XMLContent]()
var count: Int = 0
var index: Int
let options: XMLHashOptions
var xmlChildren: [XMLElement] {
children.compactMap { $0 as? XMLElement }
}
/**
Initialize an XMLElement instance
- parameters:
- name: The name of the element to be initialized
- index: The index of the element to be initialized
- options: The XMLHash options
*/
init(name: String, index: Int = 0, options: XMLHashOptions) {
self.name = name
self.index = index
self.options = options
}
/**
Adds a new XMLElement underneath this instance of XMLElement
- parameters:
- name: The name of the new element to be added
- withAttributes: The attributes dictionary for the element being added
- returns: The XMLElement that has now been added
*/
func addElement(_ name: String, withAttributes attributes: [String: String], caseInsensitive: Bool) -> XMLElement {
let element = XMLElement(name: name, index: count, options: options)
count += 1
children.append(element)
for (key, value) in attributes {
element.allAttributes[key] = XMLAttribute(name: key, text: value)
}
return element
}
func addText(_ text: String) {
let elem = TextElement(text: text)
children.append(elem)
}
}
extension XMLElement: CustomStringConvertible {
/// The tag, attributes and content for a `XMLElement` instance (<elem id="foo">content</elem>)
public var description: String {
let attributesString = allAttributes.reduce("", { $0 + " " + $1.1.description })
if !children.isEmpty {
var xmlReturn = [String]()
xmlReturn.append("<\(name)\(attributesString)>")
for child in children {
xmlReturn.append(child.description)
}
xmlReturn.append("</\(name)>")
return xmlReturn.joined()
}
return "<\(name)\(attributesString)>\(text)</\(name)>"
}
}
/*: Provides XMLIndexer Serialization/Deserialization using String backed RawRepresentables
Added by [PeeJWeeJ](https://github.com/PeeJWeeJ) */
extension XMLElement {
/**
Find an attribute by name using a String backed RawRepresentable (E.g. `String` backed `enum` cases)
- Note:
Convenience for self[String]
*/
public func attribute<N: RawRepresentable>(by name: N) -> XMLAttribute? where N.RawValue == String {
attribute(by: name.rawValue)
}
}
// Workaround for "'XMLElement' is ambiguous for type lookup in this context" error on macOS.
//
// On macOS, `XMLElement` is defined in Foundation.
// So, the code referencing `XMLElement` generates above error.
// Following code allow to using `SWXMLHash.XMLElement` in client codes.
extension XMLHash {
public typealias XMLElement = XMLHashXMLElement
}
public typealias XMLHashXMLElement = XMLElement
| mit | 68205d10d552c1b36f1b647a729faac1 | 31.005587 | 119 | 0.641648 | 4.65394 | false | false | false | false |
dongishan/SayIt-iOS-Machine-Learning-App | Carthage/Checkouts/ios-sdk/Source/RestKit/MultipartFormData.swift | 1 | 3539 | //
// MultipartFormData.swift
// WatsonDeveloperCloud
//
// Created by Glenn Fisher on 10/31/16.
// Copyright © 2016 Glenn R. Fisher. All rights reserved.
//
import Foundation
public class MultipartFormData {
public var contentType: String { return "multipart/form-data; boundary=\(boundary)" }
// add contentLength?
private let boundary: String
private var bodyParts = [BodyPart]()
private var initialBoundary: Data {
let boundary = "--\(self.boundary)\r\n"
return boundary.data(using: .utf8, allowLossyConversion: false)!
}
private var encapsulatedBoundary: Data {
let boundary = "\r\n--\(self.boundary)\r\n"
return boundary.data(using: .utf8, allowLossyConversion: false)!
}
private var finalBoundary: Data {
let boundary = "\r\n--\(self.boundary)--\r\n"
return boundary.data(using: .utf8, allowLossyConversion: false)!
}
public init() {
self.boundary = "watson-apis.boundary.bd0b4c6e3b9c2126"
}
public func append(_ data: Data, withName: String, mimeType: String? = nil, fileName: String? = nil) {
let bodyPart = BodyPart(key: withName, data: data, mimeType: mimeType, fileName: fileName)
bodyParts.append(bodyPart)
}
public func append(_ fileURL: URL, withName: String, mimeType: String? = nil) {
if let data = try? Data.init(contentsOf: fileURL) {
let bodyPart = BodyPart(key: withName, data: data, mimeType: mimeType, fileName: fileURL.lastPathComponent)
bodyParts.append(bodyPart)
}
}
public func toData() throws -> Data {
var data = Data()
for (index, bodyPart) in bodyParts.enumerated() {
let bodyBoundary: Data
if index == 0 {
bodyBoundary = initialBoundary
} else if index != 0 {
bodyBoundary = encapsulatedBoundary
} else {
throw RestError.encodingError
}
data.append(bodyBoundary)
data.append(try bodyPart.content())
}
data.append(finalBoundary)
return data
}
}
public struct BodyPart {
private(set) var key: String
private(set) var data: Data
private(set) var mimeType: String?
private(set) var fileName: String?
public init?(key: String, value: Any) {
let string = String(describing: value)
guard let data = string.data(using: .utf8) else {
return nil
}
self.key = key
self.data = data
}
public init(key: String, data: Data, mimeType: String? = nil, fileName: String? = nil) {
self.key = key
self.data = data
self.mimeType = mimeType
self.fileName = fileName
}
private var header: String {
var header = "Content-Disposition: form-data; name=\"\(key)\""
if let fileName = fileName {
header += "; filename=\"\(fileName)\""
}
if let mimeType = mimeType {
header += "\r\nContent-Type: \(mimeType)"
}
header += "\r\n\r\n"
return header
}
public func content() throws -> Data {
var result = Data()
let headerString = header
guard let header = headerString.data(using: .utf8) else {
throw RestError.encodingError
}
result.append(header)
result.append(data)
return result
}
}
| gpl-3.0 | 2cab74a1f29322c19bef3c70a50707ee | 28.731092 | 119 | 0.576597 | 4.450314 | false | false | false | false |
jpsim/SourceKitten | Source/SourceKittenFramework/Exec.swift | 1 | 4010 | import Foundation
/// Namespace for utilities to execute a child process.
enum Exec {
/// How to handle stderr output from the child process.
enum Stderr {
/// Treat stderr same as parent process.
case inherit
/// Send stderr to /dev/null.
case discard
/// Merge stderr with stdout.
case merge
}
/// The result of running the child process.
struct Results {
/// The process's exit status.
let terminationStatus: Int32
/// The data from stdout and optionally stderr.
let data: Data
/// The `data` reinterpreted as a string with whitespace trimmed; `nil` for the empty string.
var string: String? {
let encoded = String(data: data, encoding: .utf8) ?? ""
let trimmed = encoded.trimmingCharacters(in: .whitespacesAndNewlines)
return trimmed.isEmpty ? nil : trimmed
}
}
/**
Run a command with arguments and return its output and exit status.
- parameter command: Absolute path of the command to run.
- parameter arguments: Arguments to pass to the command.
- parameter currentDirectory: Current directory for the command. By default
the parent process's current directory.
- parameter stderr: What to do with stderr output from the command. By default
whatever the parent process does.
*/
static func run(_ command: String,
_ arguments: String...,
currentDirectory: String = FileManager.default.currentDirectoryPath,
stderr: Stderr = .inherit) -> Results {
return run(command, arguments, currentDirectory: currentDirectory, stderr: stderr)
}
/**
Run a command with arguments and return its output and exit status.
- parameter command: Absolute path of the command to run.
- parameter arguments: Arguments to pass to the command.
- parameter currentDirectory: Current directory for the command. By default
the parent process's current directory.
- parameter stderr: What to do with stderr output from the command. By default
whatever the parent process does.
*/
static func run(_ command: String,
_ arguments: [String] = [],
currentDirectory: String = FileManager.default.currentDirectoryPath,
stderr: Stderr = .inherit) -> Results {
let process = Process()
process.arguments = arguments
let pipe = Pipe()
process.standardOutput = pipe
switch stderr {
case .discard:
// FileHandle.nullDevice does not work here, as it consists of an invalid file descriptor,
// causing process.launch() to abort with an EBADF.
process.standardError = FileHandle(forWritingAtPath: "/dev/null")!
case .merge:
process.standardError = pipe
case .inherit:
break
}
do {
#if canImport(Darwin)
if #available(macOS 10.13, *) {
process.executableURL = URL(fileURLWithPath: command)
process.currentDirectoryURL = URL(fileURLWithPath: currentDirectory)
try process.run()
} else {
process.launchPath = command
process.currentDirectoryPath = currentDirectory
process.launch()
}
#else
process.executableURL = URL(fileURLWithPath: command)
process.currentDirectoryURL = URL(fileURLWithPath: currentDirectory)
try process.run()
#endif
} catch {
return Results(terminationStatus: -1, data: Data())
}
let file = pipe.fileHandleForReading
let data = file.readDataToEndOfFile()
process.waitUntilExit()
return Results(terminationStatus: process.terminationStatus, data: data)
}
}
| mit | c42975bc224e0cf6831a626ebaa685b0 | 38.313725 | 102 | 0.60399 | 5.508242 | false | false | false | false |
wibosco/ASOS-Consumer | ASOSConsumer/Networking/CategoryProducts/CategoryProductsAPIManager.swift | 1 | 1091 | //
// CategoryProductsAPIManager.swift
// ASOSConsumer
//
// Created by William Boles on 02/03/2016.
// Copyright © 2016 Boles. All rights reserved.
//
import UIKit
class CategoryProductsAPIManager: APIManager {
//MARK: - Retrieval
class func retrieveCategoryProducts(category: Category, completion:((category: Category, categoryProducts: Array<CategoryProduct>?) -> Void)?) {
let stringURL = "\(kASOSBaseURL)/anycat_products.json?catid=\(category.categoryID!)"
let url = NSURL(string: stringURL)!
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithURL(url) { (data: NSData?, response: NSURLResponse?, error: NSError?) -> Void in
dispatch_async(dispatch_get_main_queue(), { () -> Void in
let operation = CategoryProductsRetrievalOperation.init(category: category, data: data!, completion: completion)
QueueManager.sharedInstance.queue.addOperation(operation)
})
}
task.resume()
}
}
| mit | 74fed54ee9a5528bb827ea95849860fc | 33.0625 | 148 | 0.633945 | 4.866071 | false | false | false | false |
EZ-NET/SwiftKeychain | SwiftKeychain/ViewController.swift | 1 | 2110 | //
// ViewController.swift
// SwiftKeychain
//
// Created by Yanko Dimitrov on 11/11/14.
// Copyright (c) 2014 Yanko Dimitrov. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
let keychain = Keychain()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
performGenericKeyDemo()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
///////////////////////////////////////////////////////
// MARK: - Keychain Demo
///////////////////////////////////////////////////////
private func printGenericKey(key: GenericKey) {
if let passcode = keychain.get(key).item?.value {
println("\(key.name) value: [\(passcode)]")
} else {
println("can't find the [\(key.name)] key in the keychain")
}
}
private func performGenericKeyDemo() {
let keyName = "passcode"
let key = GenericKey(keyName: keyName, value: "1234")
let updateKey = GenericKey(keyName: keyName, value: "5678")
printGenericKey(key)
if let error = keychain.add(key) {
println("error adding the passcode key")
} else {
println(">> added the passcode key")
}
printGenericKey(key)
if let error = keychain.update(updateKey) {
println("error updating the passcode key")
} else {
println(">> updated the passcode key")
}
printGenericKey(updateKey)
if let error = keychain.remove(key) {
println("error deleting the passcode key")
} else {
println(">> removed the passcode key from the keychain")
}
}
}
| mit | eebc19e4592a403b86af6d742615e147 | 24.421687 | 80 | 0.492417 | 5.641711 | false | false | false | false |
Shopify/mobile-buy-sdk-ios | Buy/Generated/Storefront/MetafieldParentResource.swift | 1 | 5809 | //
// MetafieldParentResource.swift
// Buy
//
// Created by Shopify.
// Copyright (c) 2017 Shopify Inc. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
/// A resource that the metafield belongs to.
public protocol MetafieldParentResource {
}
extension Storefront {
/// A resource that the metafield belongs to.
open class MetafieldParentResourceQuery: GraphQL.AbstractQuery, GraphQLQuery {
public typealias Response = MetafieldParentResource
override init() {
super.init()
addField(field: "__typename")
}
/// A resource that the metafield belongs to.
@discardableResult
open func onArticle(subfields: (ArticleQuery) -> Void) -> MetafieldParentResourceQuery {
let subquery = ArticleQuery()
subfields(subquery)
addInlineFragment(on: "Article", subfields: subquery)
return self
}
/// A resource that the metafield belongs to.
@discardableResult
open func onBlog(subfields: (BlogQuery) -> Void) -> MetafieldParentResourceQuery {
let subquery = BlogQuery()
subfields(subquery)
addInlineFragment(on: "Blog", subfields: subquery)
return self
}
/// A resource that the metafield belongs to.
@discardableResult
open func onCollection(subfields: (CollectionQuery) -> Void) -> MetafieldParentResourceQuery {
let subquery = CollectionQuery()
subfields(subquery)
addInlineFragment(on: "Collection", subfields: subquery)
return self
}
/// A resource that the metafield belongs to.
@discardableResult
open func onCustomer(subfields: (CustomerQuery) -> Void) -> MetafieldParentResourceQuery {
let subquery = CustomerQuery()
subfields(subquery)
addInlineFragment(on: "Customer", subfields: subquery)
return self
}
/// A resource that the metafield belongs to.
@discardableResult
open func onOrder(subfields: (OrderQuery) -> Void) -> MetafieldParentResourceQuery {
let subquery = OrderQuery()
subfields(subquery)
addInlineFragment(on: "Order", subfields: subquery)
return self
}
/// A resource that the metafield belongs to.
@discardableResult
open func onPage(subfields: (PageQuery) -> Void) -> MetafieldParentResourceQuery {
let subquery = PageQuery()
subfields(subquery)
addInlineFragment(on: "Page", subfields: subquery)
return self
}
/// A resource that the metafield belongs to.
@discardableResult
open func onProduct(subfields: (ProductQuery) -> Void) -> MetafieldParentResourceQuery {
let subquery = ProductQuery()
subfields(subquery)
addInlineFragment(on: "Product", subfields: subquery)
return self
}
/// A resource that the metafield belongs to.
@discardableResult
open func onProductVariant(subfields: (ProductVariantQuery) -> Void) -> MetafieldParentResourceQuery {
let subquery = ProductVariantQuery()
subfields(subquery)
addInlineFragment(on: "ProductVariant", subfields: subquery)
return self
}
/// A resource that the metafield belongs to.
@discardableResult
open func onShop(subfields: (ShopQuery) -> Void) -> MetafieldParentResourceQuery {
let subquery = ShopQuery()
subfields(subquery)
addInlineFragment(on: "Shop", subfields: subquery)
return self
}
}
/// A resource that the metafield belongs to.
open class UnknownMetafieldParentResource: GraphQL.AbstractResponse, GraphQLObject, MetafieldParentResource {
public typealias Query = MetafieldParentResourceQuery
internal override func deserializeValue(fieldName: String, value: Any) throws -> Any? {
let fieldValue = value
switch fieldName {
default:
throw SchemaViolationError(type: UnknownMetafieldParentResource.self, field: fieldName, value: fieldValue)
}
}
internal static func create(fields: [String: Any]) throws -> MetafieldParentResource {
guard let typeName = fields["__typename"] as? String else {
throw SchemaViolationError(type: UnknownMetafieldParentResource.self, field: "__typename", value: fields["__typename"] ?? NSNull())
}
switch typeName {
case "Article": return try Article.init(fields: fields)
case "Blog": return try Blog.init(fields: fields)
case "Collection": return try Collection.init(fields: fields)
case "Customer": return try Customer.init(fields: fields)
case "Order": return try Order.init(fields: fields)
case "Page": return try Page.init(fields: fields)
case "Product": return try Product.init(fields: fields)
case "ProductVariant": return try ProductVariant.init(fields: fields)
case "Shop": return try Shop.init(fields: fields)
default:
return try UnknownMetafieldParentResource.init(fields: fields)
}
}
internal override func childResponseObjectMap() -> [GraphQL.AbstractResponse] {
return []
}
}
}
| mit | 699cd7eb15041f9026ee2f3ba1183483 | 33.372781 | 135 | 0.733689 | 4.348054 | false | false | false | false |
mattwelborn/HSTracker | HSTracker/Importers/BaseNetImporter.swift | 1 | 1459 | //
// BaseNetImporter.swift
// HSTracker
//
// Created by Benjamin Michotte on 25/02/16.
// Copyright © 2016 Benjamin Michotte. All rights reserved.
//
import Foundation
import Alamofire
import CleanroomLogger
class BaseNetImporter {
func loadHtml(url: String, completion: String? -> Void) {
Log.info?.message("Fetching \(url)")
Alamofire.request(.GET, url)
.responseString(encoding: NSUTF8StringEncoding) { response in
if let html = response.result.value {
Log.info?.message("Fetching \(url) complete")
completion(html)
} else {
completion(nil)
}
}
}
func saveDeck(name: String?, playerClass: CardClass, cards: [String:Int],
isArena: Bool, completion: Deck? -> Void) {
let deck = Deck(playerClass: playerClass, name: name)
deck.isActive = true
deck.isArena = isArena
deck.playerClass = playerClass
for (cardId, count) in cards {
if let card = Cards.byId(cardId) {
card.count = count
deck.addCard(card)
}
}
Decks.instance.add(deck)
completion(deck)
}
func isCount(cards: [String:Int]) -> Bool {
let count = cards.map {$0.1}.reduce(0, combine: +)
Log.verbose?.message("counting \(count) cards")
return count == 30
}
}
| mit | 4bdb8044c871a94a7ef72186865c5158 | 27.588235 | 77 | 0.558985 | 4.339286 | false | false | false | false |
EZ-NET/CodePiece | ESTwitter/API/TweetMode.swift | 1 | 1403 | //
// TweetMode.swift
// ESTwitter
//
// Created by Tomohiro Kumagai on 2020/01/27.
// Copyright © 2020 Tomohiro Kumagai. All rights reserved.
//
import Swifter
internal typealias SwifterTweetMode = TweetMode
extension API {
public enum TweetMode {
case `default`
case extended
case compat
case other(String)
}
}
extension API.TweetMode : RawRepresentable {
public var rawValue: String {
switch self {
case .default:
return ""
case .extended:
return "extended"
case .compat:
return "compat"
case .other(let value):
return value
}
}
public init(rawValue value: String) {
switch value {
case "":
self = .default
case "extended":
self = .extended
case "compat":
self = .compat
default:
self = .other(value)
}
}
}
internal extension API.TweetMode {
init(_ rawMode: SwifterTweetMode) {
switch rawMode {
case .default:
self = .default
case .extended:
self = .extended
case .compat:
self = .compat
case .other(let value):
self = .other(value)
}
}
}
// MARK: - Swifter's TweetMode
extension SwifterTweetMode {
init(_ mode: API.TweetMode) {
switch mode {
case .default:
self = .default
case .extended:
self = .extended
case .compat:
self = .compat
case .other(let value):
self = .other(value)
}
}
}
| gpl-3.0 | 5472f33abfe219d75f717e63b8eb2b9b | 12.352381 | 59 | 0.611983 | 3.314421 | false | false | false | false |
machelix/Lightbox | Source/LightboxDataSource.swift | 1 | 1329 | import UIKit
extension LightboxController: UICollectionViewDataSource {
public func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return images.count
}
public func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cellIdentifier = LightboxViewCell.reuseIdentifier
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(cellIdentifier,
forIndexPath: indexPath) as! LightboxViewCell
let image: AnyObject = images[indexPath.row]
let config = LightboxConfig.sharedInstance.config
cell.parentViewController = self
cell.setupTransitionManager()
if let imageString = image as? String {
if let imageURL = NSURL(string: imageString) where config.remoteImages {
config.loadImage(
imageView: cell.lightboxView.imageView, URL: imageURL) { error in
if error == nil { cell.lightboxView.updateViewLayout() }
}
} else {
cell.lightboxView.imageView.image = UIImage(named: imageString)
cell.lightboxView.updateViewLayout()
}
} else if let image = image as? UIImage {
cell.lightboxView.imageView.image = image
cell.lightboxView.updateViewLayout()
}
return cell
}
}
| mit | 2234a85edb0199ea2ef9f8a6454508f8 | 35.916667 | 135 | 0.728367 | 5.316 | false | true | false | false |
kickstarter/ios-oss | Library/ViewModels/ActivityUpdateViewModel.swift | 1 | 5004 | import KsApi
import Prelude
import ReactiveSwift
import UIKit
public protocol ActivityUpdateViewModelInputs {
/// Call to configure with the activity.
func configureWith(activity: Activity)
/// Call when the project image is tapped.
func tappedProjectImage()
}
public protocol ActivityUpdateViewModelOutputs {
/// Emits the update's body to be displayed.
var body: Signal<String, Never> { get }
/// Emits the cell's accessibility label to be read by VoiceOver.
var cellAccessibilityLabel: Signal<String, Never> { get }
/// Emits when we should notify the delegate that the project image button was tapped.
var notifyDelegateTappedProjectImage: Signal<Activity, Never> { get }
/// Emits the project button's accessibility label to be read by VoiceOver.
var projectButtonAccessibilityLabel: Signal<String, Never> { get }
/// Emits the project image URL to be displayed.
var projectImageURL: Signal<URL?, Never> { get }
/// Emits the project name to be displayed.
var projectName: Signal<String, Never> { get }
/// Emits an attributed string for the update sequence title.
var sequenceTitle: Signal<NSAttributedString, Never> { get }
/// Emits the update title to be displayed.
var title: Signal<String, Never> { get }
}
public protocol ActivityUpdateViewModelType {
var inputs: ActivityUpdateViewModelInputs { get }
var outputs: ActivityUpdateViewModelOutputs { get }
}
public final class ActivityUpdateViewModel: ActivityUpdateViewModelType, ActivityUpdateViewModelInputs,
ActivityUpdateViewModelOutputs {
public init() {
let activity = self.activityProperty.signal.skipNil()
let project = activity.map { $0.project }.skipNil()
let update = activity.map { $0.update }.skipNil()
self.body = update
.map { $0.body?.htmlStripped()?.truncated(maxLength: 300) ?? "" }
self.projectImageURL = project.map { $0.photo.med }.map(URL.init(string:))
self.projectName = project.map { $0.name }
self.projectButtonAccessibilityLabel = self.projectName
self.title = update.map { $0.title }
self.sequenceTitle = activity.map(updatePostedString(forActivity:))
self.notifyDelegateTappedProjectImage = activity
.takeWhen(self.tappedProjectImageProperty.signal)
self.cellAccessibilityLabel = Signal.combineLatest(project, self.sequenceTitle)
.map { project, postedText in "\(project.name) \(postedText.string)" }
}
fileprivate let activityProperty = MutableProperty<Activity?>(nil)
public func configureWith(activity: Activity) {
self.activityProperty.value = activity
}
fileprivate let tappedProjectImageProperty = MutableProperty(())
public func tappedProjectImage() {
self.tappedProjectImageProperty.value = ()
}
public let body: Signal<String, Never>
public let cellAccessibilityLabel: Signal<String, Never>
public let notifyDelegateTappedProjectImage: Signal<Activity, Never>
public let projectButtonAccessibilityLabel: Signal<String, Never>
public let projectImageURL: Signal<URL?, Never>
public let projectName: Signal<String, Never>
public let sequenceTitle: Signal<NSAttributedString, Never>
public let title: Signal<String, Never>
public var inputs: ActivityUpdateViewModelInputs { return self }
public var outputs: ActivityUpdateViewModelOutputs { return self }
}
private let decimalCharacterSet = NSCharacterSet.decimalDigits.inverted
private func updatePostedString(forActivity activity: Activity) -> NSAttributedString {
let updateNum = Format.wholeNumber(activity.update?.sequence ?? 1)
let time = Format.relative(secondsInUTC: activity.createdAt)
let fullString = Strings.dashboard_activity_update_number_posted_time_count_days_ago(
space: " ",
update_number: updateNum,
time_count_days_ago: time
)
let attributedString = fullString.simpleHtmlAttributedString(
base: [
NSAttributedString.Key.font: UIFont.ksr_footnote(),
NSAttributedString.Key.foregroundColor: UIColor.ksr_support_700
],
bold: [
NSAttributedString.Key.font: UIFont.ksr_headline(size: 13.0),
NSAttributedString.Key.foregroundColor: UIColor.ksr_support_700
]
) ?? .init(string: "")
let mutableString = NSMutableAttributedString(attributedString: attributedString)
let timeNumber = time.components(separatedBy: decimalCharacterSet).first
if let timeRange = mutableString.string.range(of: time), let timeNumber = timeNumber {
let timeStartIndex = mutableString.string
.distance(from: mutableString.string.startIndex, to: timeRange.lowerBound)
let timeNumberStartIndex = mutableString.string
.distance(from: time.startIndex, to: timeNumber.startIndex)
mutableString.addAttributes(
[
NSAttributedString.Key.font: UIFont.ksr_headline(size: 13.0),
NSAttributedString.Key.foregroundColor: UIColor.ksr_support_700
],
range: NSRange(location: timeStartIndex + timeNumberStartIndex, length: timeNumber.count)
)
}
return mutableString
}
| apache-2.0 | b6bc744c545110c2b720edb771b1c056 | 35.794118 | 103 | 0.749001 | 4.637627 | false | false | false | false |
ewhitley/CDAKit | CDAKit/health-data-standards/lib/import/c32/c32_patient_importer.swift | 1 | 11794 | //
// patient_importer.swift
// CDAKit
//
// Created by Eric Whitley on 1/11/16.
// Copyright © 2016 Eric Whitley. All rights reserved.
//
import Foundation
import Fuzi
/**
This class is the central location for taking a HITSP C32 XML document and converting it into the processed form we store in MongoDB. The class does this by running each measure independently on the XML document
Creates a new PatientImporter with the following XPath expressions used to find content in a HITSP C32:
* CDAKEncounter entries
* //cda:section[cda:templateId/@root='2.16.840.1.113883.3.88.11.83.127']/cda:entry/cda:encounter
* Procedure entries
* //cda:procedure[cda:templateId/@root='2.16.840.1.113883.10.20.1.29']
* Result entries - There seems to be some confusion around the correct templateId, so the code checks for both
* //cda:observation[cda:templateId/@root='2.16.840.1.113883.3.88.11.83.15.1'] | //cda:observation[cda:templateId/@root='2.16.840.1.113883.3.88.11.83.15']
* Vital sign entries
* //cda:observation[cda:templateId/@root='2.16.840.1.113883.3.88.11.83.14']
* Medication entries
* //cda:section[cda:templateId/@root='2.16.840.1.113883.3.88.11.83.112']/cda:entry/cda:substanceAdministration
* Codes for medications are found in the substanceAdministration with the following relative XPath
* ./cda:consumable/cda:manufacturedProduct/cda:manufacturedMaterial/cda:code
* Condition entries
* //cda:section[cda:templateId/@root='2.16.840.1.113883.3.88.11.83.103']/cda:entry/cda:act/cda:entryRelationship/cda:observation
Codes for conditions are determined by examining the value child element as opposed to the code child element
* Social History entries (non-C32 section, specified in the HL7 CCD)
* //cda:observation[cda:templateId/@root='2.16.840.1.113883.3.88.11.83.19']
* Care Goal entries(non-C32 section, specified in the HL7 CCD)
* //cda:observation[cda:templateId/@root='2.16.840.1.113883.10.20.1.25']
* CDAKAllergy entries
* //cda:observation[cda:templateId/@root='2.16.840.1.113883.10.20.1.18']
* CDAKImmunization entries
* //cda:substanceAdministration[cda:templateId/@root='2.16.840.1.113883.10.20.1.24']
* Codes for immunizations are found in the substanceAdministration with the following relative XPath
* ./cda:consumable/cda:manufacturedProduct/cda:manufacturedMaterial/cda:code
*/
class CDAKImport_C32_PatientImporter {
// Original Ruby: This class is a Singleton. It should be accessed by calling PatientImporter.instance
var section_importers: [String:CDAKImport_CDA_SectionImporter] = [:]
init(check_usable: Bool = true) {
section_importers["encounters"] = CDAKImport_CDA_EncounterImporter()
section_importers["procedures"] = CDAKImport_CDA_ProcedureImporter()
section_importers["results"] = CDAKImport_CDA_ResultImporter()
section_importers["vital_signs"] = CDAKImport_CDA_VitalSignImporter()
section_importers["medications"] = CDAKImport_CDA_MedicationImporter()
section_importers["conditions"] = CDAKImport_C32_ConditionImporter()
//section_importers["social_history"] = CDAKImport_CDA_SectionImporter(entry_finder: CDAKImport_CDA_EntryFinder(entry_xpath: "//cda:observation[cda:templateId/root='2.16.840.1.113883.3.88.11.83.19']"))
section_importers["social_history"] = CDAKImport_CDA_SocialHistoryImporter()
section_importers["care_goals"] = CDAKImport_C32_CareGoalImporter()
section_importers["medical_equipment"] = CDAKImport_CDA_MedicalEquipmentImporter()
section_importers["allergies"] = CDAKImport_CDA_AllergyImporter()
section_importers["immunizations"] = CDAKImport_C32_ImmunizationImporter()
section_importers["insurance_providers"] = CDAKImport_C32_InsuranceProviderImporter()
}
/**
- parameter check_usable_entries: value for check_usable_entries...importer uses true, stats uses false
*/
func check_usable(check_usable_entries: Bool) {
for (_, importer) in section_importers {
importer.check_for_usable = check_usable_entries
}
}
/**
Parses a HITSP C32 document and returns a Hash of of the patient.
- parameter doc: It is expected that the root node of this document
will have the "cda" namespace registered to "urn:hl7-org:v3"
- returns: a Mongoid model representing the patient
*/
func parse_c32(doc: XMLDocument) -> CDAKRecord {
let c32_patient = CDAKRecord()
get_demographics(c32_patient, doc: doc)
if let patient_role_element = doc.xpath("/cda:ClinicalDocument/cda:recordTarget/cda:patientRole").first {
c32_patient.identifiers = get_ids(patient_role_element)
}
create_c32_hash(c32_patient, doc: doc)
check_for_cause_of_death(c32_patient)
c32_patient.provider_performances = CDAKImport_CDA_ProviderImporter.extract_providers(doc)
return c32_patient
}
/**
Checks the conditions to see if any of them have a cause of death set. If they do, it will set the expired field on the CDAKRecord. This is done here rather than replacing the expried method on CDAKRecord because other formats may actully tell you whether
a patient is dead or not.
- parameter c32_patient: to check the conditions on and set the expired property if applicable
*/
func check_for_cause_of_death(c32_patient: CDAKRecord) {
if let cause_of_death = c32_patient.conditions.filter({$0.cause_of_death == true}).first {
c32_patient.expired = true
c32_patient.deathdate = cause_of_death.time_of_death
}
}
/**
Create a simple representation of the patient from a HITSP C32
- parameter record: Mongoid model to append the CDAKEntry objects to
- parameter doc: It is expected that the root node of this document
will have the "cda" namespace registered to "urn:hl7-org:v3"
- returns:a representation of the patient with symbols as keys for each section
Attention: Changed original Ruby
*/
func create_c32_hash(record: CDAKRecord, doc: XMLDocument) {
// original Ruby was using "send" - which we can't really do. So I'm not doing that...
// I'm going to inspect the section type and then just manually say "oh, you're a Condition" etc.
// and set things that way. Not super elegant, but - at least I'll know what's going on
let nrh = CDAKImport_CDA_NarrativeReferenceHandler()
nrh.build_id_map(doc)
for (section, importer) in section_importers {
let sections = importer.create_entries(doc, nrh: nrh)
switch section {
case "encounters": if let sections = sections as? [CDAKEncounter] { record.encounters = sections }
case "procedures": if let sections = sections as? [CDAKProcedure] { record.procedures = sections }
case "results": if let sections = sections as? [CDAKLabResult] { record.results = sections }
case "vital_signs": if let sections = sections as? [CDAKVitalSign] { record.vital_signs = sections }
case "medications": if let sections = sections as? [CDAKMedication] { record.medications = sections }
case "conditions": if let sections = sections as? [CDAKCondition] { record.conditions = sections }
case "social_history": if let sections = sections as? [CDAKSocialHistory] { record.social_history = sections }
case "care_goals": if let sections = sections as? [CDAKEntry] { record.care_goals = sections } //these are CDAKEntry records
case "medical_equipment": if let sections = sections as? [CDAKMedicalEquipment] { record.medical_equipment = sections }
case "allergies": if let sections = sections as? [CDAKAllergy] { record.allergies = sections }
case "immunizations": if let sections = sections as? [CDAKImmunization] { record.immunizations = sections }
case "insurance_providers": if let sections = sections as? [CDAKInsuranceProvider] { record.insurance_providers = sections }
default: break
}
}
}
func get_ids (elem: XMLElement) -> [CDAKCDAIdentifier] {
return elem.xpath("./cda:id").map({id_entry in CDAKCDAIdentifier(root: id_entry["root"], extension_id: id_entry["extension"])})
}
/**
Inspects a C32 document and populates the patient Hash with first name, last name, birth date, gender and the effectiveTime.
- parameter patient: A hash that is used to represent the patient
- parameter doc: The C32 document parsed by Nokogiri
*/
func get_demographics(patient: CDAKRecord, doc: XMLDocument) {
let effective_date = doc.xpath("/cda:ClinicalDocument/cda:effectiveTime").first?["value"]
patient.effective_time = CDAKHL7Helper.timestamp_to_integer(effective_date)
guard let patient_role_element = doc.xpath("/cda:ClinicalDocument/cda:recordTarget/cda:patientRole").first else {
return
}
guard let patient_element = patient_role_element.xpath("./cda:patient").first else {
return
}
patient.prefix = patient_element.xpath("cda:name/cda:prefix").first?.stringValue
patient.first = patient_element.xpath("cda:name/cda:given").first?.stringValue
patient.last = patient_element.xpath("cda:name/cda:family").first?.stringValue
patient.suffix = patient_element.xpath("cda:name/cda:suffix").first?.stringValue
if let birthdate_in_hl7ts_node = patient_element.xpath("cda:birthTime").first, birthdate_in_hl7ts = birthdate_in_hl7ts_node["value"] {
patient.birthdate = CDAKHL7Helper.timestamp_to_integer(birthdate_in_hl7ts)
}
if let gender_node = patient_element.xpath("cda:administrativeGenderCode").first {
patient.gender = gender_node["code"]
}
if let id_node = patient_role_element.xpath("./cda:id").first {
patient.medical_record_number = id_node["extension"]
}
//# parse race, ethnicity, and spoken language
// NOTE: changing this from original CDAK Ruby to support multiple races, ethnicities, and languages
for race_node in patient_element.xpath("cda:raceCode") {
if let an_entry = CDAKImport_CDA_SectionImporter.extract_code(race_node, code_xpath: ".", code_system: "CDC Race") {
patient.race.addCodes(an_entry)
}
}
for ethnicity_node in patient_element.xpath("cda:ethnicGroupCode") {
if let an_entry = CDAKImport_CDA_SectionImporter.extract_code(ethnicity_node, code_xpath: ".", code_system: "CDC Race") {
patient.ethnicity.addCodes(an_entry)
}
}
if let marital_status_node = patient_element.xpath("./cda:maritalStatusCode").first, code = marital_status_node["code"] {
patient.marital_status = CDAKCodedEntries(codeSystem: "HL7 Marital Status", code: code)
}
if let ra_node = patient_element.xpath("./cda:religiousAffiliationCode").first, code = ra_node["code"] {
patient.religious_affiliation = CDAKCodedEntries(codeSystem: "Religious Affiliation", code: code)
}
// USHIK info on language CDA https://ushik.ahrq.gov/ViewItemDetails?system=mdr&itemKey=83131002
// Name Language Value Set -> http://www.ietf.org/rfc/rfc4646.txt
for lc in patient_element.xpath("//cda:languageCommunication") {
if let code = lc.xpath("cda:languageCode").first?["code"] {
//NOTE - I'm making up the code system here...
// I'm also throwing in displayName
let displayName = lc.xpath("cda:languageCode").first?["displayName"]
let lang = CDAKCodedEntry(codeSystem: "RFC_4646", code: code, displayName: displayName)
var entries = CDAKCodedEntries()
entries.addCodes(lang)
patient.languages.append(entries)
}
}
patient.addresses = patient_role_element.xpath("./cda:addr").flatMap({addr in CDAKImport_CDA_LocatableImportUtils.import_address(addr)})
patient.telecoms = patient_role_element.xpath("./cda:telecom").flatMap({telecom in CDAKImport_CDA_LocatableImportUtils.import_telecom(telecom)})
}
}
| mit | c5c425a6c2440b15336b1b9531f89c5f | 48.970339 | 258 | 0.715594 | 3.783446 | false | false | false | false |
kjantzer/FolioReaderKit | Source/EPUBCore/FRResources.swift | 1 | 3093 | //
// FRResources.swift
// FolioReaderKit
//
// Created by Heberti Almeida on 29/04/15.
// Copyright (c) 2015 Folio Reader. All rights reserved.
//
import UIKit
class FRResources: NSObject {
var resources = [String: FRResource]()
/**
Adds a resource to the resources.
*/
func add(resource: FRResource) {
self.resources[resource.href] = resource
}
// MARK: Find
/**
Gets the first resource (random order) with the give mediatype.
Useful for looking up the table of contents as it's supposed to be the only resource with NCX mediatype.
*/
func findByMediaType(mediaType: MediaType) -> FRResource? {
for resource in resources.values {
if resource.mediaType != nil && resource.mediaType == mediaType {
return resource
}
}
return nil
}
/**
Gets the first resource (random order) with the give extension.
Useful for looking up the table of contents as it's supposed to be the only resource with NCX extension.
*/
func findByExtension(ext: String) -> FRResource? {
for resource in resources.values {
if resource.mediaType != nil && resource.mediaType.defaultExtension == ext {
return resource
}
}
return nil
}
/**
Gets the first resource (random order) with the give properties.
- parameter properties: ePub 3 properties. e.g. `cover-image`, `nav`
- returns: The Resource.
*/
func findByProperties(properties: String) -> FRResource? {
for resource in resources.values {
if resource.properties == properties {
return resource
}
}
return nil
}
/**
Gets the resource with the given href.
*/
func findByHref(href: String) -> FRResource? {
guard !href.isEmpty else { return nil }
// This clean is neede because may the toc.ncx is not located in the root directory
let cleanHref = href.stringByReplacingOccurrencesOfString("../", withString: "")
return resources[cleanHref]
}
/**
Gets the resource with the given href.
*/
func findById(id: String?) -> FRResource? {
guard let id = id else { return nil }
for resource in resources.values {
if resource.id == id {
return resource
}
}
return nil
}
/**
Whether there exists a resource with the given href.
*/
func containsByHref(href: String) -> Bool {
guard !href.isEmpty else { return false }
return resources.keys.contains(href)
}
/**
Whether there exists a resource with the given id.
*/
func containsById(id: String?) -> Bool {
guard let id = id else { return false }
for resource in resources.values {
if resource.id == id {
return true
}
}
return false
}
}
| bsd-3-clause | a6415da2468e61e74ddc5b5317bb9144 | 26.371681 | 109 | 0.569027 | 4.909524 | false | false | false | false |
czechboy0/swift-package-crawler | Sources/PackageSearcherLib/GitHubHTMLPackageSearcher.swift | 1 | 6080 | //
// PackageSearcher.swift
// swift-package-crawler
//
// Created by Honza Dvorsky on 5/9/16.
//
//
import XML
import HTTPSClient
import Redbird
import Utils
import Foundation
public protocol Searcher { }
extension Searcher {
public func insertIntoDb(db: Redbird, newlyFetched: [String]) throws -> (added: Int, total: Int) {
let setName = "github_names"
let params = [setName] + newlyFetched
let resp = try db
.pipeline()
.enqueue("SADD", params: params)
.enqueue("SCARD", params: [setName])
.execute()
let added = try resp[0].toInt()
let total = try resp[1].toInt()
return (added, total)
}
}
public struct GitHubHTMLPackageSearcher: Searcher {
public init() { }
private func makePath(query: String, page: Int) -> String {
//https://github.com/search?l=swift&o=desc&p=1&q=Package.swift+language%3ASwift+in%3Apath+path%3A%2F&ref=searchresults&s=indexed&type=Code&utf8=true
let path = "/search?l=swift&o=desc&p=\(page)&q=\(query)&ref=searchresults&s=indexed&type=Code&utf8=%E2%9C%93"
return path
}
private func fetchPage(client: Client, query: String, page: Int) throws -> [String] {
let path = makePath(query: query, page: page)
print("[\(NSDate())] Fetching page \(page)", terminator: " ... ")
var headers: Headers = headersWithGzip()
headers["User-Agent"] = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/603.1.3 (KHTML, like Gecko) Version/9.1.2 Safari/601.7.7"
headers["Accept"] = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"
headers["DNT"] = "1"
func _fetch() throws -> Response {
do {
let response = try client.get(path, headers: headers)
return response
} catch {
//one retry
let response = try client.get(path, headers: headers)
return response
}
}
var response = try _fetch()
let status = response.status.statusCode
print(status, terminator: " -> ")
switch status {
case 200: break
case 429: throw CrawlError.got429
case 404: throw CrawlError.got404
default: throw Error("\(response.status)")
}
let data = try decodeResponseData(response: response)
guard let doc = XMLDocument(htmlData: data) else { throw Error("Incorrect") }
func classSelector(_ className: String) -> String {
return "//*[contains(concat(' ', @class, ' '), ' \(className) ')]"
}
guard let list = doc.xPath(classSelector("code-list-item")) else { throw Error("Incorrect") }
let repos = list.flatMap { (el: XMLNode) -> String? in
guard let titleDiv = el.xPath("./*[contains(concat(' ', @class, ' '), ' title ')]").first else { return nil }
guard let name = titleDiv.xPath("a").first?.attributes["href"] else { return nil }
return name
}
return repos
}
public func oneTimeInjectListOfNames(db: Redbird, names: [String]) throws {
print("One time injecting \(names.count) names")
//verify that all names have a slash prefix
let correctNames = names.map { (name: String) -> String in
if name.hasPrefix("/") { return name }
return "/\(name)"
}
let (added, total) = try insertIntoDb(db: db, newlyFetched: correctNames)
print("Added \(added) new ones, total \(total) names")
}
//crawl github for repositories which have a Package.swift at their root
//and are written in swift
public func crawlRepoNames(db: Redbird) throws {
let uri = URI(scheme: "https", host: "github.com", port: 443)
let config = ClientConfiguration(connectionTimeout: 30.seconds, keepAlive: true)
let client = try Client(uri: uri, configuration: config)
let query = "Package.swift+language%3ASwift+in%3Apath+path%3A%2F"
var page = 1
let max = Int.max
var repos: Set<String> = []
var noNewResultsPages = 0
let noNewResultThreshold = 200
while page <= max {
if noNewResultsPages >= noNewResultThreshold {
//stop searching, we're probably up to date
print("Stopping, no new results in the last \(noNewResultThreshold) pages")
break
}
do {
func _fetch() throws {
let fetched = try fetchPage(client: client, query: query, page: page)
if !fetched.isEmpty {
let counts = try insertIntoDb(db: db, newlyFetched: fetched)
print("New added: \(counts.added), Total Count: \(counts.total)")
repos = repos.union(fetched)
if counts.added > 0 {
noNewResultsPages = 0
} else {
noNewResultsPages += 1
}
}
page += 1
// sleep(1)
}
do {
try _fetch()
} catch SystemError.operationTimedOut {
print("Timed out, retrying")
try _fetch()
}
} catch CrawlError.got429 {
let sleepDuration: UInt32 = 10
print("Stopping for \(sleepDuration) seconds")
sleep(sleepDuration)
print("Continuing")
continue
} catch CrawlError.got404 {
print("End of search results, finishing")
break
}
}
let sorted = Array(repos).sorted()
print("Fetched \(sorted.count) repos")
}
}
| mit | 364685c34d920ca71c922ea809a82eea | 35.190476 | 156 | 0.531908 | 4.431487 | false | false | false | false |
ali-rantakari/Punos | Sources/KeyValueLists.swift | 1 | 2435 | //
// KeyValueLists.swift
// Punos
//
// Created by Ali Rantakari on 23/06/2016.
// Copyright © 2016 Ali Rantakari. All rights reserved.
//
import Foundation
/// A list of string key-value pairs.
///
public protocol KeyValueList {
var pairs: [(String,String)] { get }
init(pairs: [(String,String)])
init(arrayLiteral elements: (String,String)...)
}
public extension KeyValueList {
// ------------------------------
// MARK: Literal convertibles
public init(arrayLiteral elements: (String,String)...) {
self.init(pairs: elements)
}
public init(dictionaryLiteral elements: (String,String)...) {
self.init(pairs: elements)
}
public init(_ name: String, _ value: String) {
self.init(pairs: [(name, value)])
}
public init(_ dictionary: [String:String]) {
var p = [(String,String)]()
for (k,v) in dictionary {
p.append((k,v))
}
self.init(pairs: p)
}
// ------------------------------
// MARK: Utilities
subscript(index: String) -> String? {
get {
for (k,v) in pairs {
if k == index {
return v
}
}
return nil
}
}
public var dictionary: [String:String] {
var dict = [String:String]()
for (k,v) in pairs {
dict[k] = v
}
return dict
}
func contains(name: String) -> Bool {
return pairs.map { $0.0.lowercased() }.contains(name.lowercased())
}
func merged(_ other: KeyValueList?) -> Self {
var p = pairs
if let o = other {
p.append(contentsOf: o.pairs)
}
return Self(pairs: p)
}
var keys: [String] {
return pairs.map { $0.0 }
}
var count: Int {
return pairs.count
}
}
/// A list of HTTP headers
///
public struct HTTPHeaders: KeyValueList, ExpressibleByDictionaryLiteral, ExpressibleByArrayLiteral {
public let pairs: [(String,String)]
public init(pairs: [(String,String)]) {
self.pairs = pairs
}
}
/// A list of URL query parameters
///
public struct URLQueryParameters: KeyValueList, ExpressibleByDictionaryLiteral, ExpressibleByArrayLiteral {
public let pairs: [(String,String)]
public init(pairs: [(String,String)]) {
self.pairs = pairs
}
}
| mit | 2ca18b27dd4aad20e2a379cc61a0976b | 21.747664 | 107 | 0.536565 | 4.240418 | false | false | false | false |
acevest/acecode | learn/AcePlay/AcePlay.playground/Pages/Enumerations.xcplaygroundpage/Contents.swift | 1 | 2943 | //: [Previous](@previous)
import UIKit
enum CompassPoint {
case north // 也可以写在一行上用逗号隔开 north, east, south, west
case east
case south
case west
}
var directionToHead = CompassPoint.north // 自动推断类型
directionToHead = .east // 一旦类型确定,再次赋值时可以省略枚举类型名
switch directionToHead {
case .north: print("Losts of Plantes Have a North")
case .east : print("Where the Sun Rises")
case .south: print("Watch Out for Penguins")
case .west : print("Where the Skies are Blue")
}
// Associated Values
printLine("Enumeration Associated Values")
enum BarCode {
case upca(Int, Int, Int, Int)
case qrCode(String)
}
var productBarCode = BarCode.upca(8, 88488, 66366, 2)
productBarCode = .qrCode("QRCode-123456")
switch productBarCode {
case let .upca(numberSystem, manufacturer, product, check) :
print("UPC-A: \(numberSystem), \(manufacturer), \(product), \(check)")
case let .qrCode(productCode) :
print("QR Code: \(productBarCode)")
}
printLine("RawValues")
// Raw Values
enum ASCIIControlCharacter: Character {
case tab = "\t"
case lineFeed = "\n"
case carriageReturn = "\r"
}
// Implicitly Assigned Raw Values
// 整型从0开始自增1,每个项的rawValue不能相同
enum Planet: Int {
case mercury // 从0开始,后续自增1,也可以指定值 如 mercury=1
case venus
case earth
case mars
case jupiter
case saturn
case uranus
case netpune
}
print(Planet.mercury, Planet.mercury.rawValue)
print(Planet.mars, Planet.mars.rawValue)
// 使用原始值初始化枚举实例
let possiblePlanet: Planet? = Planet(rawValue: 7) // 注意是可选类型 Planet?
print(possiblePlanet!, possiblePlanet!.rawValue)
print(Planet(rawValue: 5)!, Planet(rawValue: 5)!.rawValue)
// String型,每项默认为枚举项的字符串值
enum CompassPointString: String {
case North // String原始值默认与枚举成员名相同
case East
case Sourth
case West = "WEAST"
}
print(CompassPointString.North, CompassPointString.North.rawValue)
print(CompassPointString.East, CompassPointString.East.rawValue)
print(CompassPointString.Sourth,CompassPointString.Sourth.rawValue)
print(CompassPointString.West, CompassPointString.West.rawValue)
// 递归枚举
printLine("Resursive Enumerations")
// 不能忘记 indirect
indirect enum Exp {
case number(Int)
case add(Exp, Exp) // indirect 也可以放在case语句之前
case mul(Exp, Exp)
}
let exp = Exp.mul(Exp.add(Exp.number(2), Exp.number(5)), Exp.number(7))
func evaluateExp(_ exp: Exp) -> Int {
switch exp {
case let .number(n):
return n
case let .add(a, b) :
return evaluateExp(a) + evaluateExp(b)
case let .mul(a, b):
return evaluateExp(a) * evaluateExp(b)
}
}
print(evaluateExp(exp))
| gpl-2.0 | a6c06555deb2824ade7477086356cdc7 | 23.063063 | 74 | 0.684762 | 3.477865 | false | false | false | false |
Shopify/unity-buy-sdk | PluginDependencies/iOSPlugin/UnityBuySDKPluginTests/Mocks/MockPaymentToken.swift | 1 | 2323 | //
// MockToken.swift
// UnityBuySDK
//
// Created by Shopify.
// Copyright (c) 2017 Shopify Inc. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
import PassKit
class MockPaymentToken: PKPaymentToken {
override var paymentMethod: PKPaymentMethod {
return self._paymentMethod
}
override var transactionIdentifier: String {
return self._transactionIdentifier
}
override var paymentData: Data {
return self._paymentData
}
private let _paymentMethod: MockPaymentMethod
private let _transactionIdentifier = UUID().uuidString
private let _paymentData: Data
// ----------------------------------
// MARK: - Init -
//
// If forSimulator is true then paymentData will be set to a non serialzable string resulting in nil paymentData when
// we serialize and send to Unity
init(paymentMethod: MockPaymentMethod, forSimulator: Bool = false) {
self._paymentMethod = paymentMethod
if !forSimulator {
self._paymentData = try! JSONSerialization.data(withJSONObject: [String: Any]())
} else {
self._paymentData = "{non_serializable_string".data(using: .utf8)!
}
}
}
| mit | fba6efe21e8f07f905994253e26f9d42 | 35.873016 | 121 | 0.690056 | 4.711968 | false | false | false | false |
mohamede1945/quran-ios | Quran/GappedAudioPlayer.swift | 2 | 4006 | //
// GappedAudioPlayer.swift
// Quran
//
// Created by Mohamed Afifi on 5/16/16.
//
// Quran for iOS is a Quran reading application for iOS.
// Copyright (C) 2017 Quran.com
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
import AVFoundation
import Foundation
import MediaPlayer
import QueuePlayer
import UIKit
private class GappedPlayerItem: AVPlayerItem {
let ayah: AyahNumber
init(URL: URL, ayah: AyahNumber) {
self.ayah = ayah
super.init(asset: AVAsset(url: URL), automaticallyLoadedAssetKeys: nil)
}
fileprivate override var description: String {
return super.description + " ayah: \(ayah)"
}
}
class GappedAudioPlayer: DefaultAudioPlayer {
let numberFormatter = NumberFormatter()
weak var delegate: AudioPlayerDelegate?
let player = QueuePlayer()
func play(qari: Qari, startAyah: AyahNumber, endAyah: AyahNumber) {
let (items, info) = playerItemsForQari(qari, startAyah: startAyah, endAyah: endAyah)
var times: [AVPlayerItem: [Double]] = [:]
for item in items {
times[item] = [0]
}
player.onPlaybackEnded = onPlaybackEnded()
player.onPlaybackRateChanged = onPlaybackRateChanged()
player.onPlaybackStartingTimeFrame = { [weak self] (item: AVPlayerItem, _) in
guard let item = item as? GappedPlayerItem else { return }
self?.delegate?.playingAyah(item.ayah)
}
player.play(startTimeInSeconds: 0, items: items, info: info, boundaries: times)
}
}
extension GappedAudioPlayer {
fileprivate func playerItemsForQari(_ qari: Qari, startAyah: AyahNumber, endAyah: AyahNumber) -> ([GappedPlayerItem], [PlayerItemInfo]) {
let files = filesToPlay(qari: qari, startAyah: startAyah, endAyah: endAyah)
let items = files.map { GappedPlayerItem(URL: $0, ayah: $1) }
let info: [PlayerItemInfo] = files.map { (_, ayah) in
return PlayerItemInfo(
title: ayah.localizedName,
artist: qari.name,
artwork: UIImage(named: qari.imageName)
.flatMap { MPMediaItemArtwork(image: $0) })
}
return (items, info)
}
fileprivate func filesToPlay(qari: Qari, startAyah: AyahNumber, endAyah: AyahNumber) -> [(URL, AyahNumber)] {
guard case AudioType.gapped = qari.audioType else {
fatalError("Unsupported qari type gapless. Only gapless qaris can be downloaded here.")
}
var files: [(URL, AyahNumber)] = []
for sura in startAyah.sura...endAyah.sura {
let startAyahNumber = sura == startAyah.sura ? startAyah.ayah : 1
let endAyahNumber = sura == endAyah.sura ? endAyah.ayah : Quran.numberOfAyahsForSura(sura)
// add besm Allah for all except Al-Fatihah and At-Tawbah
if startAyahNumber == 1 && (sura != 1 && sura != 9) {
files.append((createRequestInfo(qari: qari, sura: 1, ayah: 1), AyahNumber(sura: sura, ayah: 1)))
}
for ayah in startAyahNumber...endAyahNumber {
files.append((createRequestInfo(qari: qari, sura: sura, ayah: ayah), AyahNumber(sura: sura, ayah: ayah)))
}
}
return files
}
fileprivate func createRequestInfo(qari: Qari, sura: Int, ayah: Int) -> URL {
let fileName = sura.as3DigitString() + ayah.as3DigitString()
return qari.localFolder().appendingPathComponent(fileName).appendingPathExtension(Files.audioExtension)
}
}
| gpl-3.0 | f8c74430bd5cad6125602e701b7f96b2 | 35.418182 | 141 | 0.651772 | 4.397366 | false | false | false | false |
xedin/swift | stdlib/public/Darwin/Accelerate/vDSP_SingleVectorOperations.swift | 2 | 37077 | //===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
//===----------------------------------------------------------------------===//
//
// vDSP Extrema
//
//===----------------------------------------------------------------------===//
extension vDSP {
// MARK: Elementwise minimum
/// Returns an array containing the lesser of the corresponding values in `vectorA` and `vectorB`, single-precision.
///
/// - Parameter vectorA: the `a` in `c[i] = a[i] < b[i] ? a[i] : b[i]`
/// - Parameter vectorB: the `b` in `c[i] = a[i] < b[i] ? a[i] : b[i]`
/// - Returns: the `c` in `c[i] = a[i] < b[i] ? a[i] : b[i]`
@inlinable
@available(iOS 9999, macOS 9999, tvOS 9999, watchOS 9999, *)
public static func minimum<U>(_ vectorA: U,
_ vectorB: U) -> [Float]
where
U: AccelerateBuffer,
U.Element == Float {
precondition(vectorA.count == vectorB.count)
let result = Array<Float>(unsafeUninitializedCapacity: vectorA.count) {
buffer, initializedCount in
minimum(vectorA,
vectorB,
result: &buffer)
initializedCount = vectorA.count
}
return result
}
/// Populates `result` with the lesser of the corresponding values in `vectorA` and `vectorB`, single-precision.
///
/// - Parameter vectorA: the `a` in `c[i] = a[i] < b[i] ? a[i] : b[i]`
/// - Parameter vectorB: the `b` in `c[i] = a[i] < b[i] ? a[i] : b[i]`
/// - Parameter result: the `c` in `c[i] = a[i] < b[i] ? a[i] : b[i]`
@inlinable
@available(iOS 9999, macOS 9999, tvOS 9999, watchOS 9999, *)
public static func minimum<U, V>(_ vectorA: U,
_ vectorB: U,
result: inout V)
where
U: AccelerateBuffer,
V: AccelerateMutableBuffer,
U.Element == Float, V.Element == Float {
let n = vDSP_Length(min(vectorA.count,
vectorB.count,
result.count))
result.withUnsafeMutableBufferPointer { r in
vectorA.withUnsafeBufferPointer { a in
vectorB.withUnsafeBufferPointer { b in
vDSP_vmin(a.baseAddress!, 1,
b.baseAddress!, 1,
r.baseAddress!, 1,
n)
}
}
}
}
/// Returns an array containing the lesser of the corresponding values in `vectorA` and `vectorB`, double-precision.
///
/// - Parameter vectorA: the `a` in `c[i] = a[i] < b[i] ? a[i] : b[i]`
/// - Parameter vectorB: the `b` in `c[i] = a[i] < b[i] ? a[i] : b[i]`
/// - Returns: the `c` in `c[i] = a[i] < b[i] ? a[i] : b[i]`
@inlinable
@available(iOS 9999, macOS 9999, tvOS 9999, watchOS 9999, *)
public static func minimum<U>(_ vectorA: U,
_ vectorB: U) -> [Double]
where
U: AccelerateBuffer,
U.Element == Double {
precondition(vectorA.count == vectorB.count)
let result = Array<Double>(unsafeUninitializedCapacity: vectorA.count) {
buffer, initializedCount in
minimum(vectorA,
vectorB,
result: &buffer)
initializedCount = vectorA.count
}
return result
}
/// Populates `result` with the lesser of the corresponding values in `vectorA` and `vectorB`, double-precision.
///
/// - Parameter vectorA: the `a` in `c[i] = a[i] < b[i] ? a[i] : b[i]`
/// - Parameter vectorB: the `b` in `c[i] = a[i] < b[i] ? a[i] : b[i]`
/// - Parameter result: the `c` in `c[i] = a[i] < b[i] ? a[i] : b[i]`
@inlinable
@available(iOS 9999, macOS 9999, tvOS 9999, watchOS 9999, *)
public static func minimum<U, V>(_ vectorA: U,
_ vectorB: U,
result: inout V)
where
U: AccelerateBuffer,
V: AccelerateMutableBuffer,
U.Element == Double, V.Element == Double {
let n = vDSP_Length(min(vectorA.count,
vectorB.count,
result.count))
result.withUnsafeMutableBufferPointer { r in
vectorA.withUnsafeBufferPointer { a in
vectorB.withUnsafeBufferPointer { b in
vDSP_vminD(a.baseAddress!, 1,
b.baseAddress!, 1,
r.baseAddress!, 1,
n)
}
}
}
}
// MARK: Elementwise maximum
/// Returns an array containing the greater of the corresponding values in `vectorA` and `vectorB`, single-precision.
///
/// - Parameter vectorA: the `a` in `c[i] = a[i] > b[i] ? a[i] : b[i]`
/// - Parameter vectorB: the `b` in `c[i] = a[i] > b[i] ? a[i] : b[i]`
/// - Returns: the `c` in `c[i] = a[i] > b[i] ? a[i] : b[i]`
@inlinable
@available(iOS 9999, macOS 9999, tvOS 9999, watchOS 9999, *)
public static func maximum<U>(_ vectorA: U,
_ vectorB: U) -> [Float]
where
U: AccelerateBuffer,
U.Element == Float {
precondition(vectorA.count == vectorB.count)
let result = Array<Float>(unsafeUninitializedCapacity: vectorA.count) {
buffer, initializedCount in
maximum(vectorA,
vectorB,
result: &buffer)
initializedCount = vectorA.count
}
return result
}
/// Populates `result` with the greater of the corresponding values in `vectorA` and `vectorB`, single-precision.
///
/// - Parameter vectorA: the `a` in `c[i] = a[i] > b[i] ? a[i] : b[i]`
/// - Parameter vectorB: the `b` in `c[i] = a[i] > b[i] ? a[i] : b[i]`
/// - Parameter result: the `c` in `c[i] = a[i] > b[i] ? a[i] : b[i]`
@inlinable
@available(iOS 9999, macOS 9999, tvOS 9999, watchOS 9999, *)
public static func maximum<U, V>(_ vectorA: U,
_ vectorB: U,
result: inout V)
where
U: AccelerateBuffer,
V: AccelerateMutableBuffer,
U.Element == Float, V.Element == Float {
let n = vDSP_Length(min(vectorA.count,
vectorB.count,
result.count))
result.withUnsafeMutableBufferPointer { r in
vectorA.withUnsafeBufferPointer { a in
vectorB.withUnsafeBufferPointer { b in
vDSP_vmax(a.baseAddress!, 1,
b.baseAddress!, 1,
r.baseAddress!, 1,
n)
}
}
}
}
/// Returns an array containing the greater of the corresponding values in `vectorA` and `vectorB`, double-precision.
///
/// - Parameter vectorA: the `a` in `c[i] = a[i] > b[i] ? a[i] : b[i]`
/// - Parameter vectorB: the `b` in `c[i] = a[i] > b[i] ? a[i] : b[i]`
/// - Returns: the `c` in `c[i] = `c[i] = a[i] > b[i] ? a[i] : b[i]`
@inlinable
@available(iOS 9999, macOS 9999, tvOS 9999, watchOS 9999, *)
public static func maximum<U>(_ vectorA: U,
_ vectorB: U) -> [Double]
where
U: AccelerateBuffer,
U.Element == Double {
precondition(vectorA.count == vectorB.count)
let result = Array<Double>(unsafeUninitializedCapacity: vectorA.count) {
buffer, initializedCount in
maximum(vectorA,
vectorB,
result: &buffer)
initializedCount = vectorA.count
}
return result
}
/// Populates `result` with the greater of the corresponding values in `vectorA` and `vectorB`, double-precision.
///
/// - Parameter vectorA: the `a` in `c[i] = a[i] > b[i] ? a[i] : b[i]`
/// - Parameter vectorB: the `b` in `c[i] = a[i] > b[i] ? a[i] : b[i]`
/// - Parameter result: the `c` in `c[i] = a[i] > b[i] ? a[i] : b[i]`
@inlinable
@available(iOS 9999, macOS 9999, tvOS 9999, watchOS 9999, *)
public static func maximum<U, V>(_ vectorA: U,
_ vectorB: U,
result: inout V)
where
U: AccelerateBuffer,
V: AccelerateMutableBuffer,
U.Element == Double, V.Element == Double {
let n = vDSP_Length(min(vectorA.count,
vectorB.count,
result.count))
result.withUnsafeMutableBufferPointer { r in
vectorA.withUnsafeBufferPointer { a in
vectorB.withUnsafeBufferPointer { b in
vDSP_vmaxD(a.baseAddress!, 1,
b.baseAddress!, 1,
r.baseAddress!, 1,
n)
}
}
}
}
}
//===----------------------------------------------------------------------===//
//
// vDSP Absolute and Negation
//
//===----------------------------------------------------------------------===//
extension vDSP {
/// Returns an array containing the absolute values of `vector`,
/// single-precision.
///
/// - Parameter vector: The input vector.
/// - Parameter result: The output vector.
@inlinable
@available(iOS 9999, macOS 9999, tvOS 9999, watchOS 9999, *)
public static func absolute<U>(_ vector: U) -> [Float]
where
U: AccelerateBuffer,
U.Element == Float {
let result = Array<Float>(unsafeUninitializedCapacity: vector.count) {
buffer, initializedCount in
absolute(vector,
result: &buffer)
initializedCount = vector.count
}
return result
}
/// Populates `result` with the absolute values of `vector`,
/// single-precision.
///
/// - Parameter vector: The input vector.
/// - Parameter result: The output vector.
@inlinable
@available(iOS 9999, macOS 9999, tvOS 9999, watchOS 9999, *)
public static func absolute<U, V>(_ vector: U,
result: inout V)
where
U: AccelerateBuffer,
V: AccelerateMutableBuffer,
U.Element == Float, V.Element == Float {
let n = result.count
precondition(vector.count == n)
result.withUnsafeMutableBufferPointer { r in
vector.withUnsafeBufferPointer { v in
vDSP_vabs(v.baseAddress!, 1,
r.baseAddress!, 1,
vDSP_Length(n))
}
}
}
/// Returns an array containing the absolute values of `vector`,
/// double-precision.
///
/// - Parameter vector: The input vector.
/// - Parameter result: The output vector.
@inlinable
@available(iOS 9999, macOS 9999, tvOS 9999, watchOS 9999, *)
public static func absolute<U>(_ vector: U) -> [Double]
where
U: AccelerateBuffer,
U.Element == Double {
let result = Array<Double>(unsafeUninitializedCapacity: vector.count) {
buffer, initializedCount in
absolute(vector,
result: &buffer)
initializedCount = vector.count
}
return result
}
/// Populates `result` with the absolute values of `vector`,
/// double-precision.
///
/// - Parameter vector: The input vector.
/// - Parameter result: The output vector.
@inlinable
@available(iOS 9999, macOS 9999, tvOS 9999, watchOS 9999, *)
public static func absolute<U, V>(_ vector: U,
result: inout V)
where
U: AccelerateBuffer,
V: AccelerateMutableBuffer,
U.Element == Double, V.Element == Double {
let n = result.count
precondition(vector.count == n)
result.withUnsafeMutableBufferPointer { r in
vector.withUnsafeBufferPointer { v in
vDSP_vabsD(v.baseAddress!, 1,
r.baseAddress!, 1,
vDSP_Length(n))
}
}
}
/// Returns an array containing the negative absolute values of `vector`,
/// single-precision.
///
/// - Parameter vector: The input vector.
/// - Parameter result: The output vector.
@inlinable
@available(iOS 9999, macOS 9999, tvOS 9999, watchOS 9999, *)
public static func negativeAbsolute<U>(_ vector: U) -> [Float]
where
U: AccelerateBuffer,
U.Element == Float {
let result = Array<Float>(unsafeUninitializedCapacity: vector.count) {
buffer, initializedCount in
negativeAbsolute(vector,
result: &buffer)
initializedCount = vector.count
}
return result
}
/// Populates `result` with the negative absolute values of `vector`,
/// single-precision.
///
/// - Parameter vector: The input vector.
/// - Parameter result: The output vector.
@inlinable
@available(iOS 9999, macOS 9999, tvOS 9999, watchOS 9999, *)
public static func negativeAbsolute<U, V>(_ vector: U,
result: inout V)
where
U: AccelerateBuffer,
V: AccelerateMutableBuffer,
U.Element == Float, V.Element == Float {
let n = result.count
precondition(vector.count == n)
result.withUnsafeMutableBufferPointer { r in
vector.withUnsafeBufferPointer { v in
vDSP_vnabs(v.baseAddress!, 1,
r.baseAddress!, 1,
vDSP_Length(n))
}
}
}
/// Returns an array containing the negative absolute values of `vector`,
/// double-precision.
///
/// - Parameter vector: The input vector.
/// - Parameter result: The output vector.
@inlinable
@available(iOS 9999, macOS 9999, tvOS 9999, watchOS 9999, *)
public static func negativeAbsolute<U>(_ vector: U) -> [Double]
where
U: AccelerateBuffer,
U.Element == Double {
let result = Array<Double>(unsafeUninitializedCapacity: vector.count) {
buffer, initializedCount in
negativeAbsolute(vector,
result: &buffer)
initializedCount = vector.count
}
return result
}
/// Populates `result` with the negative absolute values of `vector`,
/// double-precision.
///
/// - Parameter vector: The input vector.
/// - Parameter result: The output vector.
@inlinable
@available(iOS 9999, macOS 9999, tvOS 9999, watchOS 9999, *)
public static func negativeAbsolute<U, V>(_ vector: U,
result: inout V)
where
U: AccelerateBuffer,
V: AccelerateMutableBuffer,
U.Element == Double, V.Element == Double {
let n = result.count
precondition(vector.count == n)
result.withUnsafeMutableBufferPointer { r in
vector.withUnsafeBufferPointer { v in
vDSP_vnabsD(v.baseAddress!, 1,
r.baseAddress!, 1,
vDSP_Length(n))
}
}
}
/// Returns an array containing the negative values of `vector`,
/// single-precision.
///
/// - Parameter vector: The input vector.
/// - Parameter result: The output vector.
@inlinable
@available(iOS 9999, macOS 9999, tvOS 9999, watchOS 9999, *)
public static func negative<U>(_ vector: U) -> [Float]
where
U: AccelerateBuffer,
U.Element == Float {
let result = Array<Float>(unsafeUninitializedCapacity: vector.count) {
buffer, initializedCount in
negative(vector,
result: &buffer)
initializedCount = vector.count
}
return result
}
/// Populates `result` with the negative values of `vector`,
/// single-precision.
///
/// - Parameter vector: The input vector.
/// - Parameter result: The output vector.
@inlinable
@available(iOS 9999, macOS 9999, tvOS 9999, watchOS 9999, *)
public static func negative<U, V>(_ vector: U,
result: inout V)
where
U: AccelerateBuffer,
V: AccelerateMutableBuffer,
U.Element == Float, V.Element == Float {
let n = result.count
precondition(vector.count == n)
result.withUnsafeMutableBufferPointer { r in
vector.withUnsafeBufferPointer { v in
vDSP_vneg(v.baseAddress!, 1,
r.baseAddress!, 1,
vDSP_Length(n))
}
}
}
/// Returns an array containing the negative values of `vector`,
/// double-precision.
///
/// - Parameter vector: The input vector.
/// - Parameter result: The output vector.
@inlinable
@available(iOS 9999, macOS 9999, tvOS 9999, watchOS 9999, *)
public static func negative<U>(_ vector: U) -> [Double]
where
U: AccelerateBuffer,
U.Element == Double {
let result = Array<Double>(unsafeUninitializedCapacity: vector.count) {
buffer, initializedCount in
negative(vector,
result: &buffer)
initializedCount = vector.count
}
return result
}
/// Populates `result` with the negative values of `vector`,
/// double-precision.
///
/// - Parameter vector: The input vector.
/// - Parameter result: The output vector.
@inlinable
@available(iOS 9999, macOS 9999, tvOS 9999, watchOS 9999, *)
public static func negative<U, V>(_ vector: U,
result: inout V)
where
U: AccelerateBuffer,
V: AccelerateMutableBuffer,
U.Element == Double, V.Element == Double {
let n = result.count
precondition(vector.count == n)
result.withUnsafeMutableBufferPointer { r in
vector.withUnsafeBufferPointer { v in
vDSP_vnegD(v.baseAddress!, 1,
r.baseAddress!, 1,
vDSP_Length(n))
}
}
}
}
//===----------------------------------------------------------------------===//
//
// vDSP In-place reversing and sorting
//
//===----------------------------------------------------------------------===//
extension vDSP {
// MARK: Reversing
/// Reverses an array of single-precision values in-place.
///
/// - Parameter vector: The array to reverse.
@inlinable
@available(iOS 9999, macOS 9999, tvOS 9999, watchOS 9999, *)
public static func reverse<V>(_ vector: inout V)
where
V: AccelerateMutableBuffer,
V.Element == Float {
let n = vDSP_Length(vector.count)
vector.withUnsafeMutableBufferPointer { v in
vDSP_vrvrs(v.baseAddress!, 1,
n)
}
}
/// Reverses an array of double-precision values in-place.
///
/// - Parameter vector: The array to reverse.
@inlinable
@available(iOS 9999, macOS 9999, tvOS 9999, watchOS 9999, *)
public static func reverse<V>(_ vector: inout V)
where
V: AccelerateMutableBuffer,
V.Element == Double {
let n = vDSP_Length(vector.count)
vector.withUnsafeMutableBufferPointer { v in
vDSP_vrvrsD(v.baseAddress!, 1,
n)
}
}
// MARK: Sorting
@available(iOS 9999, macOS 9999, tvOS 9999, watchOS 9999, *)
public enum SortOrder: Int32 {
case ascending = 1
case descending = -1
}
/// Sorts an array of single-precision values in-place.
///
/// - Parameter vector: The array to sort.
/// - Parameter sortOrder: The sort direction.
@inlinable
@available(iOS 9999, macOS 9999, tvOS 9999, watchOS 9999, *)
public static func sort<V>(_ vector: inout V,
sortOrder: SortOrder)
where
V: AccelerateMutableBuffer,
V.Element == Float {
let n = vDSP_Length(vector.count)
vector.withUnsafeMutableBufferPointer { v in
vDSP_vsort(v.baseAddress!,
n,
sortOrder.rawValue)
}
}
/// Sorts an array of double-precision values in-place.
///
/// - Parameter vector: The array to sort.
/// - Parameter sortOrder: The sort direction.
@inlinable
@available(iOS 9999, macOS 9999, tvOS 9999, watchOS 9999, *)
public static func sort<V>(_ vector: inout V,
sortOrder: SortOrder)
where
V: AccelerateMutableBuffer,
V.Element == Double {
let n = vDSP_Length(vector.count)
vector.withUnsafeMutableBufferPointer { v in
vDSP_vsortD(v.baseAddress!,
n,
sortOrder.rawValue)
}
}
}
//===----------------------------------------------------------------------===//
//
// vDSP Single vector arithmetic
//
//===----------------------------------------------------------------------===//
extension vDSP {
// MARK: Square
/// Returns an array containing the square of each element in `vector`, single-precision.
///
/// - Parameter vectorA: the `a` in `c[i] = a[i] < b[i] ? a[i] : b[i]`
/// - Parameter vectorB: the `b` in `c[i] = a[i] < b[i] ? a[i] : b[i]`
/// - Returns: the `c` in `c[i] = a[i] < b[i] ? a[i] : b[i]`
@inlinable
@available(iOS 9999, macOS 9999, tvOS 9999, watchOS 9999, *)
public static func square<U>(_ vector: U) -> [Float]
where
U: AccelerateBuffer,
U.Element == Float {
let result = Array<Float>(unsafeUninitializedCapacity: vector.count) {
buffer, initializedCount in
square(vector,
result: &buffer)
initializedCount = vector.count
}
return result
}
/// Calculates the square of each element in `vector`, writing the result to `result`; single-precision.
///
/// - Parameter _ vector: Input values.
/// - Parameter result: Output values.
@inlinable
@available(iOS 9999, macOS 9999, tvOS 9999, watchOS 9999, *)
public static func square<U, V>(_ vector: U,
result: inout V)
where
U : AccelerateBuffer,
V : AccelerateMutableBuffer,
U.Element == Float, V.Element == Float {
precondition(vector.count == result.count)
let n = vDSP_Length(vector.count)
result.withUnsafeMutableBufferPointer { dest in
vector.withUnsafeBufferPointer { src in
vDSP_vsq(src.baseAddress!, 1,
dest.baseAddress!, 1,
n)
}
}
}
/// Returns an array containing the square of each element in `vector`, double-precision.
///
/// - Parameter vectorA: the `a` in `c[i] = a[i] < b[i] ? a[i] : b[i]`
/// - Parameter vectorB: the `b` in `c[i] = a[i] < b[i] ? a[i] : b[i]`
/// - Returns: the `c` in `c[i] = a[i] < b[i] ? a[i] : b[i]`
@inlinable
@available(iOS 9999, macOS 9999, tvOS 9999, watchOS 9999, *)
public static func square<U>(_ vector: U) -> [Double]
where
U: AccelerateBuffer,
U.Element == Double {
let result = Array<Double>(unsafeUninitializedCapacity: vector.count) {
buffer, initializedCount in
square(vector,
result: &buffer)
initializedCount = vector.count
}
return result
}
/// Calculates the square of each element in `vector`, writing the result to `result`; double-precision.
///
/// - Parameter _ vector: Input values.
/// - Parameter result: Output values.
@inlinable
@available(iOS 9999, macOS 9999, tvOS 9999, watchOS 9999, *)
public static func square<U, V>(_ vector: U,
result: inout V)
where
U : AccelerateBuffer,
V : AccelerateMutableBuffer,
U.Element == Double, V.Element == Double {
precondition(vector.count == result.count)
let n = vDSP_Length(vector.count)
result.withUnsafeMutableBufferPointer { dest in
vector.withUnsafeBufferPointer { src in
vDSP_vsqD(src.baseAddress!, 1,
dest.baseAddress!, 1,
n)
}
}
}
// MARK: Signed Square
/// Returns an array containing the signed square of each element in `vector`, single-precision.
///
/// - Parameter vectorA: the `a` in `c[i] = a[i] < b[i] ? a[i] : b[i]`
/// - Parameter vectorB: the `b` in `c[i] = a[i] < b[i] ? a[i] : b[i]`
/// - Returns: the `c` in `c[i] = a[i] < b[i] ? a[i] : b[i]`
@inlinable
@available(iOS 9999, macOS 9999, tvOS 9999, watchOS 9999, *)
public static func signedSquare<U>(_ vector: U) -> [Float]
where
U: AccelerateBuffer,
U.Element == Float {
let result = Array<Float>(unsafeUninitializedCapacity: vector.count) {
buffer, initializedCount in
signedSquare(vector,
result: &buffer)
initializedCount = vector.count
}
return result
}
/// Calculates the signed square of each element in `vector`, writing the result to `result`; single-precision.
///
/// - Parameter _ vector: Input values.
/// - Parameter result: Output values.
@inlinable
@available(iOS 9999, macOS 9999, tvOS 9999, watchOS 9999, *)
public static func signedSquare<U, V>(_ vector: U,
result: inout V)
where
U : AccelerateBuffer,
V : AccelerateMutableBuffer,
U.Element == Float, V.Element == Float {
precondition(vector.count == result.count)
let n = vDSP_Length(vector.count)
result.withUnsafeMutableBufferPointer { dest in
vector.withUnsafeBufferPointer { src in
vDSP_vssq(src.baseAddress!, 1,
dest.baseAddress!, 1,
n)
}
}
}
/// Returns an array containing the signed square of each element in `vector`, double-precision.
///
/// - Parameter vectorA: the `a` in `c[i] = a[i] < b[i] ? a[i] : b[i]`
/// - Parameter vectorB: the `b` in `c[i] = a[i] < b[i] ? a[i] : b[i]`
/// - Returns: the `c` in `c[i] = a[i] < b[i] ? a[i] : b[i]`
@inlinable
@available(iOS 9999, macOS 9999, tvOS 9999, watchOS 9999, *)
public static func signedSquare<U>(_ vector: U) -> [Double]
where
U: AccelerateBuffer,
U.Element == Double {
let result = Array<Double>(unsafeUninitializedCapacity: vector.count) {
buffer, initializedCount in
signedSquare(vector,
result: &buffer)
initializedCount = vector.count
}
return result
}
/// Calculates the signed square of each element in `vector`, writing the result to `result`; double-precision.
///
/// - Parameter _ vector: Input values.
/// - Parameter result: Output values.
@inlinable
@available(iOS 9999, macOS 9999, tvOS 9999, watchOS 9999, *)
public static func signedSquare<U, V>(_ vector: U,
result: inout V)
where
U : AccelerateBuffer,
V : AccelerateMutableBuffer,
U.Element == Double, V.Element == Double {
precondition(vector.count == result.count)
let n = vDSP_Length(vector.count)
result.withUnsafeMutableBufferPointer { dest in
vector.withUnsafeBufferPointer { src in
vDSP_vssqD(src.baseAddress!, 1,
dest.baseAddress!, 1,
n)
}
}
}
// MARK: Truncate to Fraction
/// Returns an array containing each element in `vector` truncated to fraction, single-precision.
///
/// - Parameter vectorA: the `a` in `c[i] = a[i] < b[i] ? a[i] : b[i]`
/// - Parameter vectorB: the `b` in `c[i] = a[i] < b[i] ? a[i] : b[i]`
/// - Returns: the `c` in `c[i] = a[i] < b[i] ? a[i] : b[i]`
@inlinable
@available(iOS 9999, macOS 9999, tvOS 9999, watchOS 9999, *)
public static func trunc<U>(_ vector: U) -> [Float]
where
U: AccelerateBuffer,
U.Element == Float {
let result = Array<Float>(unsafeUninitializedCapacity: vector.count) {
buffer, initializedCount in
trunc(vector,
result: &buffer)
initializedCount = vector.count
}
return result
}
/// Truncates to fraction each element in `vector`, writing the result to `result`; single-precision.
///
/// - Parameter _ vector: Input values.
/// - Parameter result: Output values.
@inlinable
@available(iOS 9999, macOS 9999, tvOS 9999, watchOS 9999, *)
public static func trunc<U, V>(_ vector: U,
result: inout V)
where
U : AccelerateBuffer,
V : AccelerateMutableBuffer,
U.Element == Float, V.Element == Float {
precondition(vector.count == result.count)
let n = vDSP_Length(vector.count)
result.withUnsafeMutableBufferPointer { dest in
vector.withUnsafeBufferPointer { src in
vDSP_vfrac(src.baseAddress!, 1,
dest.baseAddress!, 1,
n)
}
}
}
/// Returns an array containing each element in `vector` truncated to fraction, double-precision.
///
/// - Parameter vectorA: the `a` in `c[i] = a[i] < b[i] ? a[i] : b[i]`
/// - Parameter vectorB: the `b` in `c[i] = a[i] < b[i] ? a[i] : b[i]`
/// - Returns: the `c` in `c[i] = a[i] < b[i] ? a[i] : b[i]`
@inlinable
@available(iOS 9999, macOS 9999, tvOS 9999, watchOS 9999, *)
public static func trunc<U>(_ vector: U) -> [Double]
where
U: AccelerateBuffer,
U.Element == Double {
let result = Array<Double>(unsafeUninitializedCapacity: vector.count) {
buffer, initializedCount in
trunc(vector,
result: &buffer)
initializedCount = vector.count
}
return result
}
/// Truncates to fraction each element in `vector`, writing the result to `result`; double-precision.
///
/// - Parameter _ vector: Input values.
/// - Parameter result: Output values.
@inlinable
@available(iOS 9999, macOS 9999, tvOS 9999, watchOS 9999, *)
public static func trunc<U, V>(_ vector: U,
result: inout V)
where
U : AccelerateBuffer,
V : AccelerateMutableBuffer,
U.Element == Double, V.Element == Double {
precondition(vector.count == result.count)
let n = vDSP_Length(vector.count)
result.withUnsafeMutableBufferPointer { dest in
vector.withUnsafeBufferPointer { src in
vDSP_vfracD(src.baseAddress!, 1,
dest.baseAddress!, 1,
n)
}
}
}
// Zero crossing
/// Returns the number of zero crossings in `vector`; single-precision.
///
/// - Parameter _ vector: Input values.
/// - Returns: The total number of transitions from positive to negative values and from negative to positive values.
@inlinable
@available(iOS 9999, macOS 9999, tvOS 9999, watchOS 9999, *)
public static func countZeroCrossings<U>(_ vector: U) -> UInt
where
U : AccelerateBuffer,
U.Element == Float {
let n = vDSP_Length(vector.count)
var crossingCount: vDSP_Length = 0
var lastCrossingIndex: vDSP_Length = 0
vector.withUnsafeBufferPointer { src in
vDSP_nzcros(src.baseAddress!, 1,
n,
&lastCrossingIndex,
&crossingCount,
n)
}
return crossingCount
}
/// Returns the number of zero crossings in `vector`; double-precision.
///
/// - Parameter _ vector: Input values.
/// - Returns: The total number of transitions from positive to negative values and from negative to positive values.
@inlinable
@available(iOS 9999, macOS 9999, tvOS 9999, watchOS 9999, *)
public static func countZeroCrossings<U>(_ vector: U) -> UInt
where
U : AccelerateBuffer,
U.Element == Double {
let n = vDSP_Length(vector.count)
var crossingCount: vDSP_Length = 0
var lastCrossingIndex: vDSP_Length = 0
vector.withUnsafeBufferPointer { src in
vDSP_nzcrosD(src.baseAddress!, 1,
n,
&lastCrossingIndex,
&crossingCount,
n)
}
return crossingCount
}
}
| apache-2.0 | fc3e2d837701e8a1dfa2e39e67c49b11 | 35.172683 | 121 | 0.480433 | 4.955493 | false | false | false | false |
poetmountain/MotionMachine | Tests/Tests/ValueAssistants/UIKitStructAssistantTests.swift | 1 | 10220 | //
// UIKitStructAssistantTests.swift
// MotionMachineTests
//
// Created by Brett Walker on 5/30/16.
// Copyright © 2016 Poet & Mountain, LLC. All rights reserved.
//
import XCTest
class UIKitStructAssistantTests: XCTestCase {
// MARK: generateProperties
func test_generateProperties_UIEdgeInsets() {
let assistant = UIKitStructAssistant()
let tester = Tester()
let insets = UIEdgeInsets(top: 10.0, left: 0.0, bottom: 20.0, right: 0.0)
let path = "insets"
if let val = UIKitStructAssistant.valueForStruct(insets), let target = tester.value(forKeyPath: path) {
let states = PropertyStates(path: path, end: val)
let props = try! assistant.generateProperties(targetObject: target as AnyObject, propertyStates: states)
// should only have 2 props because left and right are unchanged from original insets
XCTAssertEqual(props.count, 2)
if (props.count == 2) {
let top_prop = props[0]
let bottom_prop = props[1]
// should test that ending property states were captured and start states are set to existing inset values
XCTAssertEqual(top_prop.path, "insets.top")
XCTAssertEqual(top_prop.start, 0.0)
XCTAssertEqual(top_prop.end, 10.0)
XCTAssertEqual(bottom_prop.path, "insets.bottom")
XCTAssertEqual(bottom_prop.start, 0.0)
XCTAssertEqual(bottom_prop.end, 20.0)
}
}
}
func test_generateProperties_UIEdgeInsets_start_state() {
let assistant = UIKitStructAssistant()
let tester = Tester()
let start_insets = UIEdgeInsets(top: 5.0, left: 5.0, bottom: 10.0, right: 0.0)
let insets = UIEdgeInsets(top: 10.0, left: 0.0, bottom: 20.0, right: 0.0)
let path = "insets"
if let start_val = UIKitStructAssistant.valueForStruct(start_insets), let val = UIKitStructAssistant.valueForStruct(insets), let target = tester.value(forKeyPath: path) {
let states = PropertyStates(path: path, start: start_val, end: val)
let props = try! assistant.generateProperties(targetObject: target as AnyObject, propertyStates: states)
// should only have 3 props because right is unchanged from original insets
XCTAssertEqual(props.count, 3)
if (props.count == 3) {
let top_prop = props[0]
let left_prop = props[1]
let bottom_prop = props[2]
// should test that both the starting and ending property states were captured
// the left prop is included by MotionMachine because even though the ending value is equal to the original inset value,
// a different starting value was specified
XCTAssertEqual(top_prop.path, "insets.top")
XCTAssertEqual(top_prop.start, 5.0)
XCTAssertEqual(top_prop.end, 10.0)
XCTAssertEqual(left_prop.path, "insets.left")
XCTAssertEqual(left_prop.start, 5.0)
XCTAssertEqual(left_prop.end, 0.0)
XCTAssertEqual(bottom_prop.path, "insets.bottom")
XCTAssertEqual(bottom_prop.start, 10.0)
XCTAssertEqual(bottom_prop.end, 20.0)
}
}
}
func test_generateProperties_UIOffset() {
let assistant = UIKitStructAssistant()
let tester = Tester()
let offset = UIOffset(horizontal: 10.0, vertical: 20.0)
let path = "offset"
if let val = UIKitStructAssistant.valueForStruct(offset), let target = tester.value(forKeyPath: path) {
let states = PropertyStates(path: path, end: val)
let props = try! assistant.generateProperties(targetObject: target as AnyObject, propertyStates: states)
// should have 2 props both offset values are changed from original
XCTAssertEqual(props.count, 2)
if (props.count == 2) {
let h_prop = props[0]
let v_prop = props[1]
// should test that ending property states were captured and start states are set to original offset values
XCTAssertEqual(h_prop.path, "offset.horizontal")
XCTAssertEqual(h_prop.start, 0.0)
XCTAssertEqual(h_prop.end, 10.0)
XCTAssertEqual(v_prop.path, "offset.vertical")
XCTAssertEqual(v_prop.start, 0.0)
XCTAssertEqual(v_prop.end, 20.0)
}
}
}
func test_generateProperties_UIOffset_start_state() {
let assistant = UIKitStructAssistant()
let tester = Tester()
let start_offset = UIOffset(horizontal: 5.0, vertical: 10.0)
let offset = UIOffset(horizontal: 10.0, vertical: 20.0)
let path = "offset"
if let start_val = UIKitStructAssistant.valueForStruct(start_offset), let val = UIKitStructAssistant.valueForStruct(offset), let target = tester.value(forKeyPath: path) {
let states = PropertyStates(path: path, start: start_val, end: val)
let props = try! assistant.generateProperties(targetObject: target as AnyObject, propertyStates: states)
// should have 2 props both offset values are changed from original
XCTAssertEqual(props.count, 2)
if (props.count == 2) {
let h_prop = props[0]
let v_prop = props[1]
// should test that both the starting and ending property states were captured
XCTAssertEqual(h_prop.path, "offset.horizontal")
XCTAssertEqual(h_prop.start, 5.0)
XCTAssertEqual(h_prop.end, 10.0)
XCTAssertEqual(v_prop.path, "offset.vertical")
XCTAssertEqual(v_prop.start, 10.0)
XCTAssertEqual(v_prop.end, 20.0)
}
}
}
func test_generateProperties_error() {
let assistant = UIKitStructAssistant()
let tester = Tester()
let path = "insets"
if let target = tester.value(forKeyPath: path) {
do {
// method needs an NSValue but we pass in a Tester, so this should throw an error
let states = PropertyStates(path: path, end: tester)
try _ = assistant.generateProperties(targetObject: target as AnyObject, propertyStates: states)
} catch ValueAssistantError.typeRequirement(let valueType) {
ValueAssistantError.typeRequirement(valueType).printError(fromFunction: #function)
XCTAssertEqual(valueType, "NSValue")
} catch {
}
}
}
// MARK: updateValue
func test_updateValue_UIEdgeOffsets() {
let assistant = UIKitStructAssistant()
var old_value = NSValue.init(uiEdgeInsets: UIEdgeInsets(top: 10.0, left: 0.0, bottom: 20.0, right: 0.0))
var new_value: NSValue
new_value = assistant.updateValue(inObject: old_value, newValues: ["top" : 10.0]) as! NSValue
XCTAssertEqual(new_value.uiEdgeInsetsValue.top, 10.0)
XCTAssertEqual(new_value.uiEdgeInsetsValue.bottom, old_value.uiEdgeInsetsValue.bottom)
// additive
assistant.additive = true
old_value = NSValue.init(uiEdgeInsets: UIEdgeInsets(top: 1.0, left: 0.0, bottom: 20.0, right: 0.0))
new_value = assistant.updateValue(inObject: old_value, newValues: ["top" : 10.0]) as! NSValue
XCTAssertEqual(new_value.uiEdgeInsetsValue.top, 11.0)
XCTAssertEqual(new_value.uiEdgeInsetsValue.bottom, old_value.uiEdgeInsetsValue.bottom)
}
func test_updateValue_UIOffset() {
let assistant = UIKitStructAssistant()
var old_value = NSValue.init(uiOffset: UIOffset(horizontal: 10.0, vertical: 20.0))
var new_value: NSValue
new_value = assistant.updateValue(inObject: old_value, newValues: ["horizontal" : 10.0]) as! NSValue
XCTAssertEqual(new_value.uiOffsetValue.horizontal, 10.0)
XCTAssertEqual(new_value.uiOffsetValue.vertical, old_value.uiOffsetValue.vertical)
// additive
assistant.additive = true
old_value = NSValue.init(uiOffset: UIOffset(horizontal: 1.0, vertical: 20.0))
new_value = assistant.updateValue(inObject: old_value, newValues: ["horizontal" : 10.0]) as! NSValue
XCTAssertEqual(new_value.uiOffsetValue.horizontal, 11.0)
XCTAssertEqual(new_value.uiOffsetValue.vertical, old_value.uiOffsetValue.vertical)
}
// MARK: retrieveValue
func test_retrieveValue_UIEdgeInsets() {
let assistant = UIKitStructAssistant()
let object = NSValue.init(uiEdgeInsets: UIEdgeInsets(top: 10.0, left: 0.0, bottom: 20.0, right: 0.0))
let value = try! assistant.retrieveValue(inObject: object, keyPath: "top")
XCTAssertEqual(value, 10.0)
}
func test_retrieveValue_UIOffset() {
let assistant = UIKitStructAssistant()
let object = NSValue.init(uiOffset: UIOffset(horizontal: 10.0, vertical: 20.0))
let value = try! assistant.retrieveValue(inObject: object, keyPath: "horizontal")
XCTAssertEqual(value, 10.0)
}
func test_retrieveValue_error() {
let assistant = UIKitStructAssistant()
let tester = Tester()
do {
// method needs an NSValue but we pass in a Tester, so this should throw an error
try _ = assistant.retrieveValue(inObject: tester, keyPath: "top")
} catch ValueAssistantError.typeRequirement(let valueType) {
ValueAssistantError.typeRequirement(valueType).printError(fromFunction: #function)
XCTAssertEqual(valueType, "NSValue")
} catch {
}
}
}
| mit | e4de5d9bac9b81b02251192ec12b4113 | 43.430435 | 178 | 0.602212 | 4.709217 | false | true | false | false |
koutalou/iOS-CleanArchitecture | iOSCleanArchitectureTwitterSample/Domain/Model/RegisteredAccountsModel.swift | 1 | 585 | //
// LoginUserModel.swift
// iOSCleanArchitectureTwitterSample
//
// Created by koutalou on 2015/12/21.
// Copyright © 2015年 koutalou. All rights reserved.
//
import Foundation
import Accounts
struct RegisteredAccountsModel {
var accounts: [RegisteredAccountModel] = []
}
struct RegisteredAccountModel {
let name: String
let identifier: String
let id: Int
var isSelected: Bool = false
init(account: ACAccount, index: Int) {
name = account.username
identifier = account.identifier as String? ?? ""
id = index
}
}
| mit | d0efed41cd82f9bccb934565585eaa56 | 19.785714 | 56 | 0.668385 | 3.986301 | false | false | false | false |
february29/Learning | swift/ReactiveCocoaDemo/Pods/RxSwift/RxSwift/Observables/Debounce.swift | 132 | 3523 | //
// Debounce.swift
// RxSwift
//
// Created by Krunoslav Zaher on 9/11/16.
// Copyright © 2016 Krunoslav Zaher. All rights reserved.
//
extension ObservableType {
/**
Ignores elements from an observable sequence which are followed by another element within a specified relative time duration, using the specified scheduler to run throttling timers.
- seealso: [debounce operator on reactivex.io](http://reactivex.io/documentation/operators/debounce.html)
- parameter dueTime: Throttling duration for each element.
- parameter scheduler: Scheduler to run the throttle timers on.
- returns: The throttled sequence.
*/
public func debounce(_ dueTime: RxTimeInterval, scheduler: SchedulerType)
-> Observable<E> {
return Debounce(source: self.asObservable(), dueTime: dueTime, scheduler: scheduler)
}
}
final fileprivate class DebounceSink<O: ObserverType>
: Sink<O>
, ObserverType
, LockOwnerType
, SynchronizedOnType {
typealias Element = O.E
typealias ParentType = Debounce<Element>
private let _parent: ParentType
let _lock = RecursiveLock()
// state
private var _id = 0 as UInt64
private var _value: Element? = nil
let cancellable = SerialDisposable()
init(parent: ParentType, observer: O, cancel: Cancelable) {
_parent = parent
super.init(observer: observer, cancel: cancel)
}
func run() -> Disposable {
let subscription = _parent._source.subscribe(self)
return Disposables.create(subscription, cancellable)
}
func on(_ event: Event<Element>) {
synchronizedOn(event)
}
func _synchronized_on(_ event: Event<Element>) {
switch event {
case .next(let element):
_id = _id &+ 1
let currentId = _id
_value = element
let scheduler = _parent._scheduler
let dueTime = _parent._dueTime
let d = SingleAssignmentDisposable()
self.cancellable.disposable = d
d.setDisposable(scheduler.scheduleRelative(currentId, dueTime: dueTime, action: self.propagate))
case .error:
_value = nil
forwardOn(event)
dispose()
case .completed:
if let value = _value {
_value = nil
forwardOn(.next(value))
}
forwardOn(.completed)
dispose()
}
}
func propagate(_ currentId: UInt64) -> Disposable {
_lock.lock(); defer { _lock.unlock() } // {
let originalValue = _value
if let value = originalValue, _id == currentId {
_value = nil
forwardOn(.next(value))
}
// }
return Disposables.create()
}
}
final fileprivate class Debounce<Element> : Producer<Element> {
fileprivate let _source: Observable<Element>
fileprivate let _dueTime: RxTimeInterval
fileprivate let _scheduler: SchedulerType
init(source: Observable<Element>, dueTime: RxTimeInterval, scheduler: SchedulerType) {
_source = source
_dueTime = dueTime
_scheduler = scheduler
}
override func run<O: ObserverType>(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == Element {
let sink = DebounceSink(parent: self, observer: observer, cancel: cancel)
let subscription = sink.run()
return (sink: sink, subscription: subscription)
}
}
| mit | 7a3f0ed1a6e0db0f1acb2e26fd7221f9 | 28.596639 | 186 | 0.62209 | 4.837912 | false | false | false | false |
nuclearace/VaporTest | Sources/App/Models/User.swift | 1 | 1801 | //
// Created by Erik Little on 5/21/17.
//
import Foundation
import FluentProvider
import CryptoSwift
public final class User : Model {
public let email: String
public let username: String
let pw: String
public let storage = Storage()
public required init(row: Row) throws {
email = try row.get("email")
pw = try row.get("pw")
username = try row.get("username")
}
init(username: String, email: String, password: String) {
self.username = username
self.email = email
self.pw = User.createSaltedPassword(password: password)
}
public func makeRow() throws -> Row {
var row = Row()
try row.set("email", email)
try row.set("pw", pw)
try row.set("username", username)
return row
}
func makeJSON() throws -> JSON {
return JSON(["email": .string(email),
"username": .string(username)])
}
static func createSaltedPassword(password: String) -> String {
let salt = UUID().uuidString.sha256()
return salt + "$" + createSaltedHash(salt: salt, password: password)
}
static func createSaltedHash(salt: String, password: String) -> String {
return (salt + password).sha3(.sha512)
}
}
extension User : Preparation {
public class func prepare(_ database: Database) throws {
try database.create(User.self) {builder in
builder.id()
builder.string("email", length: 256, unique: true)
builder.string("pw", length: 512)
builder.string("username", length: 30, unique: true)
}
}
public class func revert(_ database: Database) throws { }
}
extension User {
var posts: Children<User, Post> {
return children()
}
}
| mit | 12a60c92fe7f927e6571ef5d4cdefc9c | 24.013889 | 76 | 0.598556 | 4.2277 | false | false | false | false |
Piwigo/Piwigo-Mobile | piwigo/Settings/Information/AboutViewController.swift | 1 | 11998 | //
// AboutViewController.swift
// piwigo
//
// Created by Spencer Baker on 2/19/15.
// Copyright (c) 2015 bakercrew. All rights reserved.
//
// Converted to Swift 5 by Eddy Lelièvre-Berna on 28/03/2020
//
import UIKit
import piwigoKit
class AboutViewController: UIViewController, UITextViewDelegate {
@IBOutlet private weak var piwigoTitle: UILabel!
@IBOutlet private weak var authorsLabel: UILabel!
@IBOutlet private weak var versionLabel: UILabel!
@IBOutlet private weak var textView: UITextView!
private var fixTextPositionAfterLoadingViewOnPad: Bool!
private var doneBarButton: UIBarButtonItem?
// MARK: - View Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
title = NSLocalizedString("settings_acknowledgements", comment: "Acknowledgements")
// Button for returning to albums/images
doneBarButton = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(quitSettings))
doneBarButton?.accessibilityIdentifier = "Done"
}
@objc
func applyColorPalette() {
// Background color of the view
view.backgroundColor = .piwigoColorBackground()
// Navigation bar
let attributes = [
NSAttributedString.Key.foregroundColor: UIColor.piwigoColorWhiteCream(),
NSAttributedString.Key.font: UIFont.piwigoFontNormal()
]
navigationController?.navigationBar.titleTextAttributes = attributes as [NSAttributedString.Key : Any]
if #available(iOS 11.0, *) {
navigationController?.navigationBar.prefersLargeTitles = false
}
navigationController?.navigationBar.barStyle = AppVars.shared.isDarkPaletteActive ? .black : .default
navigationController?.navigationBar.tintColor = .piwigoColorOrange()
navigationController?.navigationBar.barTintColor = .piwigoColorBackground()
navigationController?.navigationBar.backgroundColor = .piwigoColorBackground()
if #available(iOS 15.0, *) {
/// In iOS 15, UIKit has extended the usage of the scrollEdgeAppearance,
/// which by default produces a transparent background, to all navigation bars.
let barAppearance = UINavigationBarAppearance()
barAppearance.configureWithOpaqueBackground()
barAppearance.backgroundColor = .piwigoColorBackground()
navigationController?.navigationBar.standardAppearance = barAppearance
navigationController?.navigationBar.scrollEdgeAppearance = navigationController?.navigationBar.standardAppearance
}
// Text color depdending on background color
authorsLabel.textColor = .piwigoColorText()
versionLabel.textColor = .piwigoColorText()
textView.textColor = .piwigoColorText()
textView.backgroundColor = .piwigoColorBackground()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
// Piwigo app
piwigoTitle.text = NSLocalizedString("settings_appName", comment: "Piwigo Mobile")
// Piwigo authors
updateAuthorsLabel()
// Piwigo app version
let appVersionString = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String
let appBuildString = Bundle.main.object(forInfoDictionaryKey: "CFBundleVersion") as? String
versionLabel.text = "— \(NSLocalizedString("version", tableName: "About", bundle: Bundle.main, value: "", comment: "Version:")) \(appVersionString ?? "") (\(appBuildString ?? "")) —"
// Thanks and licenses
fixTextPositionAfterLoadingViewOnPad = true
textView.attributedText = aboutAttributedString()
textView.scrollsToTop = true
if #available(iOS 11.0, *) {
textView.contentInsetAdjustmentBehavior = .never
} else {
// Fallback on earlier versions
automaticallyAdjustsScrollViewInsets = false
}
// Set colors, fonts, etc.
applyColorPalette()
// Set navigation buttons
navigationItem.setRightBarButtonItems([doneBarButton].compactMap { $0 }, animated: true)
// Register palette changes
NotificationCenter.default.addObserver(self, selector: #selector(applyColorPalette),
name: .pwgPaletteChanged, object: nil)
}
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransition(to: size, with: coordinator)
// Update Piwigo authors label
coordinator.animate(alongsideTransition: { (context) in
// Piwigo authors
self.updateAuthorsLabel()
}, completion: nil)
}
override func viewDidLayoutSubviews() {
if (fixTextPositionAfterLoadingViewOnPad) {
// Scroll text to where it is expected to be after loading view
fixTextPositionAfterLoadingViewOnPad = false
textView.setContentOffset(.zero, animated: false)
}
}
func updateAuthorsLabel () {
// Piwigo authors
let authors1 = NSLocalizedString("authors1", tableName: "About", bundle: Bundle.main, value: "", comment: "By Spencer Baker, Olaf Greck,")
let authors2 = NSLocalizedString("authors2", tableName: "About", bundle: Bundle.main, value: "", comment: "and Eddy Lelièvre-Berna")
// Change label according to orientation
var orientation = UIInterfaceOrientation.portrait
if #available(iOS 13.0, *) {
orientation = UIApplication.shared.windows.first?.windowScene?.interfaceOrientation ?? .portrait
} else {
orientation = UIApplication.shared.statusBarOrientation
}
if (UIDevice.current.userInterfaceIdiom == .phone) && orientation.isPortrait {
// iPhone in portrait mode
authorsLabel.text = "\(authors1)\r\(authors2)"
}
else {
// iPhone in landscape mode, iPad in any orientation
authorsLabel.text = "\(authors1) \(authors2)"
}
}
@objc func quitSettings() {
// Close Settings view
dismiss(animated: true)
}
deinit {
// Unregister palette changes
NotificationCenter.default.removeObserver(self, name: .pwgPaletteChanged, object: nil)
}
// MARK: - Acknowledgements
func aboutAttributedString() -> NSMutableAttributedString? {
// Release notes attributed string
let aboutAttributedString = NSMutableAttributedString(string: "")
let spacerAttributedString = NSMutableAttributedString(string: "\n\n\n")
let spacerRange = NSRange(location: 0, length: spacerAttributedString.length)
spacerAttributedString.addAttribute(.font, value: UIFont.piwigoFontSmall(), range: spacerRange)
// Translators — Bundle string
let translatorsString = NSLocalizedString("translators_text", tableName: "About", bundle: Bundle.main, value: "", comment: "Translators text")
let translatorsAttributedString = NSMutableAttributedString(string: translatorsString)
let translatorsRange = NSRange(location: 0, length: translatorsString.count)
translatorsAttributedString.addAttribute(.font, value: UIFont.piwigoFontSmall(), range: translatorsRange)
aboutAttributedString.append(translatorsAttributedString)
aboutAttributedString.append(spacerAttributedString)
// Introduction string — Bundle string
let introString = NSLocalizedString("about_text", tableName: "About", bundle: Bundle.main, value: "", comment: "Introduction text")
let introAttributedString = NSMutableAttributedString(string: introString)
let introRange = NSRange(location: 0, length: introString.count)
introAttributedString.addAttribute(.font, value: UIFont.piwigoFontSmall(), range: introRange)
aboutAttributedString.append(introAttributedString)
// AFNetworking Licence — Bundle string
let afnString = NSLocalizedString("licenceAFN_text", tableName: "About", bundle: Bundle.main, value: "", comment: "AFNetworking licence text")
let afnAttributedString = NSMutableAttributedString(string: afnString)
var afnTitleRange = NSRange(location: 0, length: afnString.count)
afnAttributedString.addAttribute(.font, value: UIFont.piwigoFontSmall(), range: afnTitleRange)
afnTitleRange = NSRange(location: 0, length: (afnString as NSString).range(of: "\n").location)
afnAttributedString.addAttribute(.font, value: UIFont.piwigoFontBold(), range: afnTitleRange)
aboutAttributedString.append(afnAttributedString)
aboutAttributedString.append(spacerAttributedString)
// IQKeyboardManager Licence — Bundle string
let iqkmString = NSLocalizedString("licenceIQkeyboard_text", tableName: "About", bundle: Bundle.main, value: "", comment: "IQKeyboardManager licence text")
let iqkmAttributedString = NSMutableAttributedString(string: iqkmString)
var iqkmTitleRange = NSRange(location: 0, length: iqkmString.count)
iqkmAttributedString.addAttribute(.font, value: UIFont.piwigoFontSmall(), range: iqkmTitleRange)
iqkmTitleRange = NSRange(location: 0, length: (iqkmString as NSString).range(of: "\n").location)
iqkmAttributedString.addAttribute(.font, value: UIFont.piwigoFontBold(), range: iqkmTitleRange)
aboutAttributedString.append(iqkmAttributedString)
aboutAttributedString.append(spacerAttributedString)
// MBProgressHUD Licence — Bundle string
let mbpHudString = NSLocalizedString("licenceMBProgHUD_text", tableName: "About", bundle: Bundle.main, value: "", comment: "MBProgressHUD licence text")
let mbpHudAttributedString = NSMutableAttributedString(string: mbpHudString)
var mbpHudRange = NSRange(location: 0, length: mbpHudString.count)
mbpHudAttributedString.addAttribute(.font, value: UIFont.piwigoFontSmall(), range: mbpHudRange)
mbpHudRange = NSRange(location: 0, length: (mbpHudString as NSString).range(of: "\n").location)
mbpHudAttributedString.addAttribute(.font, value: UIFont.piwigoFontBold(), range: mbpHudRange)
aboutAttributedString.append(mbpHudAttributedString)
aboutAttributedString.append(spacerAttributedString)
// MGSwipeTableCell Licence — Bundle string
let mgstcString = NSLocalizedString("licenceMGSTC_text", tableName: "About", bundle: Bundle.main, value: "", comment: "MGSwipeTableCell licence text")
let mgstcAttributedString = NSMutableAttributedString(string: mgstcString)
var mgstcRange = NSRange(location: 0, length: mgstcString.count)
mgstcAttributedString.addAttribute(.font, value: UIFont.piwigoFontSmall(), range: mgstcRange)
mgstcRange = NSRange(location: 0, length: (mgstcString as NSString).range(of: "\n").location)
mgstcAttributedString.addAttribute(.font, value: UIFont.piwigoFontBold(), range: mgstcRange)
aboutAttributedString.append(mgstcAttributedString)
aboutAttributedString.append(spacerAttributedString)
// MIT Licence — Bundle string
let mitString = NSLocalizedString("licenceMIT_text", tableName: "About", bundle: Bundle.main, value: "", comment: "AFNetworking licence text")
let mitAttributedString = NSMutableAttributedString(string: mitString)
var mitTitleRange = NSRange(location: 0, length: mitString.count)
mitAttributedString.addAttribute(.font, value: UIFont.piwigoFontSmall(), range: mitTitleRange)
mitTitleRange = NSRange(location: 0, length: (mitString as NSString).range(of: "\n").location)
mitAttributedString.addAttribute(.font, value: UIFont.piwigoFontBold(), range: mitTitleRange)
aboutAttributedString.append(mitAttributedString)
return aboutAttributedString
}
}
| mit | 3aa6493730a6cc2a5d9812a4b540321e | 50.188034 | 190 | 0.701202 | 5.454463 | false | false | false | false |
mohitathwani/swift-corelibs-foundation | Foundation/NSDecimalNumber.swift | 1 | 16988 | // 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
//
/*************** Exceptions ***********/
public struct NSExceptionName : RawRepresentable, Equatable, Hashable, Comparable {
public private(set) var rawValue: String
public init(_ rawValue: String) {
self.rawValue = rawValue
}
public init(rawValue: String) {
self.rawValue = rawValue
}
public var hashValue: Int {
return self.rawValue.hashValue
}
public static func ==(_ lhs: NSExceptionName, _ rhs: NSExceptionName) -> Bool {
return lhs.rawValue == rhs.rawValue
}
public static func <(_ lhs: NSExceptionName, _ rhs: NSExceptionName) -> Bool {
return lhs.rawValue < rhs.rawValue
}
}
extension NSExceptionName {
public static let decimalNumberExactnessException = NSExceptionName(rawValue: "NSDecimalNumberExactnessException")
public static let decimalNumberOverflowException = NSExceptionName(rawValue: "NSDecimalNumberOverflowException")
public static let decimalNumberUnderflowException = NSExceptionName(rawValue: "NSDecimalNumberUnderflowException")
public static let decimalNumberDivideByZeroException = NSExceptionName(rawValue: "NSDecimalNumberDivideByZeroException")
}
/*************** Rounding and Exception behavior ***********/
// Rounding policies :
// Original
// value 1.2 1.21 1.25 1.35 1.27
// Plain 1.2 1.2 1.3 1.4 1.3
// Down 1.2 1.2 1.2 1.3 1.2
// Up 1.2 1.3 1.3 1.4 1.3
// Bankers 1.2 1.2 1.2 1.4 1.3
/*************** Type definitions ***********/
extension NSDecimalNumber {
public enum RoundingMode : UInt {
case plain // Round up on a tie
case down // Always down == truncate
case up // Always up
case bankers // on a tie round so last digit is even
}
public enum CalculationError : UInt {
case noError
case lossOfPrecision // Result lost precision
case underflow // Result became 0
case overflow // Result exceeds possible representation
case divideByZero
}
}
public protocol NSDecimalNumberBehaviors {
func roundingMode() -> NSDecimalNumber.RoundingMode
func scale() -> Int16
}
// Receiver can raise, return a new value, or return nil to ignore the exception.
fileprivate func handle(_ error: NSDecimalNumber.CalculationError, _ handler: NSDecimalNumberBehaviors) {
// handle the error condition, such as throwing an error for over/underflow
}
/*************** NSDecimalNumber: the class ***********/
open class NSDecimalNumber : NSNumber {
fileprivate let decimal: Decimal
public convenience init(mantissa: UInt64, exponent: Int16, isNegative: Bool) {
var d = Decimal()
d._exponent = Int32(exponent)
d._isNegative = isNegative ? 1 : 0
var man = mantissa
d._mantissa.0 = UInt16(man & 0xffff)
man >>= 4
d._mantissa.1 = UInt16(man & 0xffff)
man >>= 4
d._mantissa.2 = UInt16(man & 0xffff)
man >>= 4
d._mantissa.3 = UInt16(man & 0xffff)
d._length = 4
d.trimTrailingZeros()
// TODO more parts of the mantissa...
self.init(decimal: d)
}
public init(decimal dcm: Decimal) {
self.decimal = dcm
super.init()
}
public convenience init(string numberValue: String?) {
self.init(decimal: Decimal(string: numberValue ?? "") ?? Decimal.nan)
}
public convenience init(string numberValue: String?, locale: Any?) {
self.init(decimal: Decimal(string: numberValue ?? "", locale: locale as? Locale) ?? Decimal.nan)
}
public required init?(coder: NSCoder) {
guard coder.allowsKeyedCoding else {
preconditionFailure("Unkeyed coding is unsupported.")
}
let exponent:Int32 = coder.decodeInt32(forKey: "NS.exponent")
let length:UInt32 = UInt32(coder.decodeInt32(forKey: "NS.length"))
let isNegative:UInt32 = UInt32(coder.decodeBool(forKey: "NS.negative") ? 1 : 0)
let isCompact:UInt32 = UInt32(coder.decodeBool(forKey: "NS.compact") ? 1 : 0)
// let byteOrder:UInt32 = UInt32(coder.decodeInt32(forKey: "NS.bo"))
guard let mantissaData: Data = coder.decodeObject(forKey: "NS.mantissa") as? Data else {
return nil // raise "Critical NSDecimalNumber archived data is missing"
}
guard mantissaData.count == Int(NSDecimalMaxSize * 2) else {
return nil // raise "Critical NSDecimalNumber archived data is wrong size"
}
// Byte order?
let mantissa:(UInt16, UInt16, UInt16, UInt16, UInt16, UInt16, UInt16, UInt16) = (
UInt16(mantissaData[0]) << 8 & UInt16(mantissaData[1]),
UInt16(mantissaData[2]) << 8 & UInt16(mantissaData[3]),
UInt16(mantissaData[4]) << 8 & UInt16(mantissaData[5]),
UInt16(mantissaData[6]) << 8 & UInt16(mantissaData[7]),
UInt16(mantissaData[8]) << 8 & UInt16(mantissaData[9]),
UInt16(mantissaData[10]) << 8 & UInt16(mantissaData[11]),
UInt16(mantissaData[12]) << 8 & UInt16(mantissaData[13]),
UInt16(mantissaData[14]) << 8 & UInt16(mantissaData[15])
)
self.decimal = Decimal(_exponent: exponent, _length: length, _isNegative: isNegative, _isCompact: isCompact, _reserved: 0, _mantissa: mantissa)
super.init()
}
public required convenience init(floatLiteral value: Double) {
self.init(decimal:Decimal(value))
}
public required convenience init(booleanLiteral value: Bool) {
if value {
self.init(integerLiteral: 1)
} else {
self.init(integerLiteral: 0)
}
}
public required convenience init(integerLiteral value: Int) {
self.init(decimal:Decimal(value))
}
public required convenience init(bytes buffer: UnsafeRawPointer, objCType type: UnsafePointer<Int8>) {
NSRequiresConcreteImplementation()
}
open override func description(withLocale locale: Locale?) -> String {
guard locale == nil else {
fatalError("Locale not supported: \(locale!)")
}
return self.decimal.description
}
open class var zero: NSDecimalNumber {
return NSDecimalNumber(integerLiteral: 0)
}
open class var one: NSDecimalNumber {
return NSDecimalNumber(integerLiteral: 1)
}
open class var minimum: NSDecimalNumber {
return NSDecimalNumber(decimal:Decimal.leastFiniteMagnitude)
}
open class var maximum: NSDecimalNumber {
return NSDecimalNumber(decimal:Decimal.greatestFiniteMagnitude)
}
open class var notANumber: NSDecimalNumber {
return NSDecimalNumber(decimal: Decimal.nan)
}
open func adding(_ other: NSDecimalNumber) -> NSDecimalNumber {
return adding(other, withBehavior: nil)
}
open func adding(_ other: NSDecimalNumber, withBehavior b: NSDecimalNumberBehaviors?) -> NSDecimalNumber {
var result = Decimal()
var left = self.decimal
var right = other.decimal
let behavior = b ?? NSDecimalNumber.defaultBehavior
let roundingMode = behavior.roundingMode()
let error = NSDecimalAdd(&result, &left, &right, roundingMode)
handle(error,behavior)
return NSDecimalNumber(decimal: result)
}
open func subtracting(_ other: NSDecimalNumber) -> NSDecimalNumber {
return subtracting(other, withBehavior: nil)
}
open func subtracting(_ other: NSDecimalNumber, withBehavior b: NSDecimalNumberBehaviors?) -> NSDecimalNumber {
var result = Decimal()
var left = self.decimal
var right = other.decimal
let behavior = b ?? NSDecimalNumber.defaultBehavior
let roundingMode = behavior.roundingMode()
let error = NSDecimalSubtract(&result, &left, &right, roundingMode)
handle(error,behavior)
return NSDecimalNumber(decimal: result)
}
open func multiplying(by other: NSDecimalNumber) -> NSDecimalNumber {
return multiplying(by: other, withBehavior: nil)
}
open func multiplying(by other: NSDecimalNumber, withBehavior b: NSDecimalNumberBehaviors?) -> NSDecimalNumber {
var result = Decimal()
var left = self.decimal
var right = other.decimal
let behavior = b ?? NSDecimalNumber.defaultBehavior
let roundingMode = behavior.roundingMode()
let error = NSDecimalMultiply(&result, &left, &right, roundingMode)
handle(error,behavior)
return NSDecimalNumber(decimal: result)
}
open func dividing(by other: NSDecimalNumber) -> NSDecimalNumber {
return dividing(by: other, withBehavior: nil)
}
open func dividing(by other: NSDecimalNumber, withBehavior b: NSDecimalNumberBehaviors?) -> NSDecimalNumber {
var result = Decimal()
var left = self.decimal
var right = other.decimal
let behavior = b ?? NSDecimalNumber.defaultBehavior
let roundingMode = behavior.roundingMode()
let error = NSDecimalDivide(&result, &left, &right, roundingMode)
handle(error,behavior)
return NSDecimalNumber(decimal: result)
}
open func raising(toPower power: Int) -> NSDecimalNumber {
return raising(toPower:power, withBehavior: nil)
}
open func raising(toPower power: Int, withBehavior b: NSDecimalNumberBehaviors?) -> NSDecimalNumber {
var result = Decimal()
var input = self.decimal
let behavior = b ?? NSDecimalNumber.defaultBehavior
let roundingMode = behavior.roundingMode()
let error = NSDecimalPower(&result, &input, power, roundingMode)
handle(error,behavior)
return NSDecimalNumber(decimal: result)
}
open func multiplying(byPowerOf10 power: Int16) -> NSDecimalNumber {
return multiplying(byPowerOf10: power, withBehavior: nil)
}
open func multiplying(byPowerOf10 power: Int16, withBehavior b: NSDecimalNumberBehaviors?) -> NSDecimalNumber {
var result = Decimal()
var input = self.decimal
let behavior = b ?? NSDecimalNumber.defaultBehavior
let roundingMode = behavior.roundingMode()
let error = NSDecimalPower(&result, &input, Int(power), roundingMode)
handle(error,behavior)
return NSDecimalNumber(decimal: result)
}
// Round to the scale of the behavior.
open func rounding(accordingToBehavior b: NSDecimalNumberBehaviors?) -> NSDecimalNumber {
var result = Decimal()
var input = self.decimal
let behavior = b ?? NSDecimalNumber.defaultBehavior
let roundingMode = behavior.roundingMode()
let scale = behavior.scale()
NSDecimalRound(&result, &input, Int(scale), roundingMode)
return NSDecimalNumber(decimal: result)
}
// compare two NSDecimalNumbers
open override func compare(_ decimalNumber: NSNumber) -> ComparisonResult {
if let num = decimalNumber as? NSDecimalNumber {
return decimal.compare(to:num.decimal)
} else {
return decimal.compare(to:Decimal(decimalNumber.doubleValue))
}
}
open class var defaultBehavior: NSDecimalNumberBehaviors {
return NSDecimalNumberHandler.defaultBehavior
}
// One behavior per thread - The default behavior is
// rounding mode: NSRoundPlain
// scale: No defined scale (full precision)
// ignore exactnessException
// raise on overflow, underflow and divide by zero.
static let OBJC_TYPE = "d".utf8CString
open override var objCType: UnsafePointer<Int8> {
return NSDecimalNumber.OBJC_TYPE.withUnsafeBufferPointer{ $0.baseAddress! }
}
// return 'd' for double
open override var int8Value: Int8 {
return Int8(decimal.doubleValue)
}
open override var uint8Value: UInt8 {
return UInt8(decimal.doubleValue)
}
open override var int16Value: Int16 {
return Int16(decimal.doubleValue)
}
open override var uint16Value: UInt16 {
return UInt16(decimal.doubleValue)
}
open override var int32Value: Int32 {
return Int32(decimal.doubleValue)
}
open override var uint32Value: UInt32 {
return UInt32(decimal.doubleValue)
}
open override var int64Value: Int64 {
return Int64(decimal.doubleValue)
}
open override var uint64Value: UInt64 {
return UInt64(decimal.doubleValue)
}
open override var floatValue: Float {
return Float(decimal.doubleValue)
}
open override var doubleValue: Double {
return decimal.doubleValue
}
open override var boolValue: Bool {
return !decimal.isZero
}
open override var intValue: Int {
return Int(decimal.doubleValue)
}
open override var uintValue: UInt {
return UInt(decimal.doubleValue)
}
open override func isEqual(_ value: Any?) -> Bool {
guard let other = value as? NSDecimalNumber else { return false }
return self.decimal == other.decimal
}
}
// return an approximate double value
/*********** A class for defining common behaviors *******/
open class NSDecimalNumberHandler : NSObject, NSDecimalNumberBehaviors, NSCoding {
static let defaultBehavior = NSDecimalNumberHandler()
let _roundingMode: NSDecimalNumber.RoundingMode
let _scale:Int16
let _raiseOnExactness: Bool
let _raiseOnOverflow: Bool
let _raiseOnUnderflow: Bool
let _raiseOnDivideByZero: Bool
public override init() {
_roundingMode = .plain
_scale = Int16(NSDecimalNoScale)
_raiseOnExactness = false
_raiseOnOverflow = true
_raiseOnUnderflow = true
_raiseOnDivideByZero = true
}
public required init?(coder: NSCoder) {
guard coder.allowsKeyedCoding else {
preconditionFailure("Unkeyed coding is unsupported.")
}
_roundingMode = NSDecimalNumber.RoundingMode(rawValue: UInt(coder.decodeInteger(forKey: "NS.roundingMode")))!
if coder.containsValue(forKey: "NS.scale") {
_scale = Int16(coder.decodeInteger(forKey: "NS.scale"))
} else {
_scale = Int16(NSDecimalNoScale)
}
_raiseOnExactness = coder.decodeBool(forKey: "NS.raise.exactness")
_raiseOnOverflow = coder.decodeBool(forKey: "NS.raise.overflow")
_raiseOnUnderflow = coder.decodeBool(forKey: "NS.raise.underflow")
_raiseOnDivideByZero = coder.decodeBool(forKey: "NS.raise.dividebyzero")
}
open func encode(with coder: NSCoder) {
guard coder.allowsKeyedCoding else {
preconditionFailure("Unkeyed coding is unsupported.")
}
if _roundingMode != .plain {
coder.encode(Int(_roundingMode.rawValue), forKey: "NS.roundingmode")
}
if _scale != Int16(NSDecimalNoScale) {
coder.encode(_scale, forKey:"NS.scale")
}
if _raiseOnExactness {
coder.encode(_raiseOnExactness, forKey:"NS.raise.exactness")
}
if _raiseOnOverflow {
coder.encode(_raiseOnOverflow, forKey:"NS.raise.overflow")
}
if _raiseOnUnderflow {
coder.encode(_raiseOnUnderflow, forKey:"NS.raise.underflow")
}
if _raiseOnDivideByZero {
coder.encode(_raiseOnDivideByZero, forKey:"NS.raise.dividebyzero")
}
}
open class func `default`() -> NSDecimalNumberHandler {
return defaultBehavior
}
// rounding mode: NSRoundPlain
// scale: No defined scale (full precision)
// ignore exactnessException (return nil)
// raise on overflow, underflow and divide by zero.
public init(roundingMode: NSDecimalNumber.RoundingMode, scale: Int16, raiseOnExactness exact: Bool, raiseOnOverflow overflow: Bool, raiseOnUnderflow underflow: Bool, raiseOnDivideByZero divideByZero: Bool) {
_roundingMode = roundingMode
_scale = scale
_raiseOnExactness = exact
_raiseOnOverflow = overflow
_raiseOnUnderflow = underflow
_raiseOnDivideByZero = divideByZero
}
open func roundingMode() -> NSDecimalNumber.RoundingMode {
return _roundingMode
}
// The scale could return NoScale for no defined scale.
open func scale() -> Int16 {
return _scale
}
}
extension NSNumber {
public var decimalValue: Decimal {
if let d = self as? NSDecimalNumber {
return d.decimal
} else {
return Decimal(self.doubleValue)
}
}
}
| apache-2.0 | 353807ef01c9afec153851733e2c6277 | 36.501104 | 211 | 0.6504 | 4.79887 | false | false | false | false |
chinesemanbobo/PPDemo | Pods/Down/Source/AST/Styling/Attribute Collections/ParagraphStyleCollection.swift | 3 | 1730 | //
// ParagraphStyleCollection.swift
// Down
//
// Created by John Nguyen on 27.07.19.
// Copyright © 2016-2019 Down. All rights reserved.
//
#if !os(watchOS) && !os(Linux)
#if canImport(UIKit)
import UIKit
#elseif canImport(AppKit)
import AppKit
#endif
public protocol ParagraphStyleCollection {
var heading1: NSParagraphStyle { get }
var heading2: NSParagraphStyle { get }
var heading3: NSParagraphStyle { get }
var heading4: NSParagraphStyle { get }
var heading5: NSParagraphStyle { get }
var heading6: NSParagraphStyle { get }
var body: NSParagraphStyle { get }
var code: NSParagraphStyle { get }
}
public struct StaticParagraphStyleCollection: ParagraphStyleCollection {
public var heading1: NSParagraphStyle
public var heading2: NSParagraphStyle
public var heading3: NSParagraphStyle
public var heading4: NSParagraphStyle
public var heading5: NSParagraphStyle
public var heading6: NSParagraphStyle
public var body: NSParagraphStyle
public var code: NSParagraphStyle
public init() {
let headingStyle = NSMutableParagraphStyle()
headingStyle.paragraphSpacing = 8
let bodyStyle = NSMutableParagraphStyle()
bodyStyle.paragraphSpacingBefore = 8
bodyStyle.paragraphSpacing = 8
bodyStyle.lineSpacing = 8
let codeStyle = NSMutableParagraphStyle()
codeStyle.paragraphSpacingBefore = 8
codeStyle.paragraphSpacing = 8
heading1 = headingStyle
heading2 = headingStyle
heading3 = headingStyle
heading4 = headingStyle
heading5 = headingStyle
heading6 = headingStyle
body = bodyStyle
code = codeStyle
}
}
#endif
| mit | 1ef9711d7603d5c21daacd6bc31cad98 | 24.426471 | 72 | 0.69867 | 5.070381 | false | false | false | false |
iitjee/SteppinsSwift | Optionals.swift | 1 | 1732 | /*
*/
/* Optional Chaining as an alternative to Forced Unwrapping */
linkedListNode!.next() //here, if linkedListNode is nil, forced unwrapping triggers a runtime error
linkedListNode?.next() //here, if linkedListNode is nil, optional chaining fails gracefully and next() is simply not called
//NOTE: To reflect the fact that optional chaining can be called on a nil value, the result of an optional chaining call is always an optional value, **even if the property, method, or subscript you are querying returns a nonoptional value**.
//eg: A property that normally returns an Int will now return an Int? when accessed through optional chaining. (i.e Int is now wrapped in an optional)
class Person {
var residence: Residence?
}
class Residence {
var numberOfRooms = 1
}
let john = Person()
//Forced Unwrapping
let roomCount = john.residence!.numberOfRooms // this triggers a runtime error since residence is always nil
//Optional Chaining along with optional binding
if let roomCount = john.residence?.numberOfRooms {
print("John's residence has \(roomCount) room(s).")
} else {
print("Unable to retrieve the number of rooms.")
} // Prints "Unable to retrieve the number of rooms."
//Note again: The fact that numberOfRooms is queried through an optional chain means that the call to numberOfRooms will always return an Int? instead of an Int.
john.residence = Residence() //john.residence now contains an actual Residence instance, rather than nil.
if let roomCount = john.residence?.numberOfRooms {
print("John's residence has \(roomCount) room(s).")
} else {
print("Unable to retrieve the number of rooms.")
} // Prints "John's residence has 1 room(s)."
| apache-2.0 | b20014e985832a688f0c8164e3f44b0b | 23.742857 | 242 | 0.732679 | 4.475452 | false | false | false | false |
Yvent/YVImagePickerController | YVImagePickerController-Demo/YVImagePickerController-Demo/SingleSelectionVC.swift | 1 | 2200 | //
// SingleSelectionImageVC.swift
// Demo
//
// Created by 周逸文 on 2017/10/12.
// Copyright © 2017年 YV. All rights reserved.
//
import UIKit
import YVImagePickerController
class SingleSelectionImageVC: UIViewController, YVImagePickerControllerDelegate {
var showImageView: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor.white
addNavRightItem()
initUI()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func addNavRightItem() {
let btn = UIButton(type: .custom)
btn.frame = CGRect(x: 0, y: 0, width: 70, height: 35)
btn.setTitle("添加", for: .normal)
btn.setTitleColor(UIColor.black, for: .normal)
btn.addTarget(self, action: #selector(navRightItemClicked), for: .touchUpInside)
navigationItem.rightBarButtonItem = UIBarButtonItem(customView: btn)
}
func initUI() {
showImageView = UIImageView(frame: CGRect(x: 40, y: 80, width: ScreenWidth-80, height: ScreenHeight-100))
showImageView.backgroundColor = UIColor.gray
self.view.addSubview(showImageView)
}
@objc func navRightItemClicked() {
let pickerVC = YVImagePickerController()
pickerVC.yvmediaType = .image
pickerVC.yvcolumns = 5
pickerVC.yvIsMultiselect = false
pickerVC.yvdelegate = self
pickerVC.topViewColor = UIColor(red: 174/255, green: 153/255, blue: 90/255, alpha: 1)
self.present(pickerVC, animated: true, completion: nil)
}
func yvimagePickerController(_ picker: YVImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
picker.dismiss(animated: true, completion: nil)
if info["imagedata"] != nil{
let image = info["imagedata"] as! UIImage
self.showImageView.image = image
}
}
func yvimagePickerControllerDidCancel(_ picker: YVImagePickerController) {
picker.dismiss(animated: true, completion: nil)
}
}
| mit | 7d8399fc6417988c51df47606c402234 | 31.641791 | 121 | 0.64792 | 4.693133 | false | false | false | false |
dukemedicine/Duke-Medicine-Mobile-Companion | Classes/Controllers/MCWebViewController.swift | 1 | 2450 | //
// MCWebViewController.swift
// Maestro Care Mobile Companion
//
// Created by Ricky Bloomfield on 6/25/14.
// Copyright (c) 2014 Duke Medicine. All rights reserved.
//
import UIKit
class MCWebViewController: UIViewController, UIAlertViewDelegate {
/*var webViewController: SVWebViewController?
var barsTintColor: UIColor?
var viewTintColor: UIColor?
init(nibName nibNameOrNil: String!, bundle nibBundleOrNil: NSBundle!) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
}
init(address urlString: String!, andTintColor color: UIColor!) {
let url: NSURL = NSURL.URLWithString(urlString)
self.webViewController = SVWebViewController(URL: url)
super.init(rootViewController: self.webViewController)
let doneButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Done, target: self.webViewController, action: Selector("doneButtonClicked:"))
self.viewTintColor = color
// Make all UIBarButtonItems have bold text (so Haiku/Canto button matches the 'Done' button)
let barButtonAppearanceDict = [NSFontAttributeName : UIFont.boldSystemFontOfSize(17.0)]
UIBarButtonItem.appearance().setTitleTextAttributes(barButtonAppearanceDict, forState: UIControlState.Normal)
let title = "❮ \(HaikuOrCanto)"
var returnButton: UIBarButtonItem?
if IPAD() {
returnButton = UIBarButtonItem(title: title, style: UIBarButtonItemStyle.Plain, target: self, action: Selector("touchesBegan:withEvent:"))
} else {
returnButton = UIBarButtonItem(title: title, style: UIBarButtonItemStyle.Plain, target: self, action: Selector("returnToHaikuCanto"))
}
if IPAD() {
self.navigationItem.leftBarButtonItem = returnButton
} else {
self.navigationItem.rightBarButtonItem = doneButton
print("Done button added")
// Show the Haiku/Canto button on if one or both are installed
if self.HaikuOrCanto() != nil {
self.navigationItem.leftBarButtonItem = returnButton
}
}
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
//self.webViewController!.title = self.title;
self.navigationBar.tintColor = self.viewTintColor;
}*/
} | mit | 702c3ac781ba05b99dff18d3b9a823cd | 37.265625 | 161 | 0.664216 | 5.356674 | false | false | false | false |
AboutObjectsTraining/swift-ios-2015-07-kop | ReadingList/ReadingListModel/ReadingList.swift | 1 | 1346 | //
// Copyright (C) 2014 About Objects, Inc. All Rights Reserved.
// See LICENSE.txt for this example's licensing information.
//
import Foundation
let BooksKey = "books"
public class ReadingList: ModelObject
{
public var title = ""
public var books = [Book]()
public override var description: String {
var s = "Title: \(title)\nCount: \(books.count)\nBooks:\n------\n"
for (index, book: Book) in enumerate(books) {
s += "\(index + 1). \(book)\n"
}
return s
}
override class func keys() -> [String]
{
return [TitleKey, BooksKey]
}
public override func setValue(var value: AnyObject?, forKey key: String)
{
if (key == BooksKey && value is [[String: AnyObject]])
{
value = map(value as! [[String: AnyObject]], { Book.self(dictionary: $0) })
}
super.setValue(value, forKey: key)
}
public override func dictionaryRepresentation() -> [NSObject: AnyObject]
{
var dictionary: [String: AnyObject]! = super.dictionaryRepresentation() as? [String: AnyObject]
if let books = dictionary[BooksKey] as? [ModelObject]
{
dictionary[BooksKey] = map(books, { $0.dictionaryRepresentation() })
}
return dictionary
}
} | mit | 68cfc3ac1e17c084d7fa3bd8d2635907 | 27.0625 | 103 | 0.574294 | 4.327974 | false | false | false | false |
mathsandphysics/Steps | Steps/Steps/BaseCore/JLHBaseUI/JLHPopover/JLHPopoverPresentationController.swift | 1 | 1085 | //
// JLHPopoverPresentationController.swift
// Steps
//
// Created by mathsandphysics on 2016/12/21.
// Copyright © 2016年 Utopia. All rights reserved.
//
import UIKit
class JLHPopoverPresentationController: UIPresentationController {
var presentedFrame: CGRect = .zero
fileprivate lazy var coverView: UIView = UIView()
override func containerViewWillLayoutSubviews() {
super.containerViewWillLayoutSubviews()
presentedView?.frame = presentedFrame
setupCoverView()
}
}
extension JLHPopoverPresentationController {
func setupCoverView() {
containerView?.insertSubview(coverView, at: 0)
coverView.backgroundColor = UIColor(white: 0.8, alpha: 0.45)
coverView.frame = containerView!.bounds
let tap = UITapGestureRecognizer(target: self, action: #selector(JLHPopoverPresentationController.coverClick))
coverView.addGestureRecognizer(tap)
}
func coverClick(tap: UITapGestureRecognizer) {
presentedViewController.dismiss(animated: true, completion: nil)
}
}
| apache-2.0 | 60f8d5f0bf14412349963fe66b71f068 | 29.055556 | 118 | 0.713494 | 5.079812 | false | false | false | false |
chrisjmendez/swift-exercises | GUI/Cards/Cards/ViewController.swift | 1 | 1566 | //
// ViewController.swift
// Cards
//
// Created by Chris on 1/31/16.
// Copyright © 2016 Chris Mendez. All rights reserved.
//
import UIKit
import Alamofire
import SwiftyJSON
class ViewController: UIViewController {
let SEGUE_ON_LOAD = "onLoadSegue"
let REDDIT = "https://www.reddit.com/new.json?limit=10"
var json:JSON?
func getJSON(url:String){
Alamofire.request(.GET, url, parameters: nil).validate().responseJSON { response in
switch response.result {
case .Success:
let data = response.result.value as? NSDictionary
let json = JSON(data!)
self.parseJSON(json)
self.goToView(self.SEGUE_ON_LOAD)
case .Failure(let error):
print(error)
}
}
}
func parseJSON(json:JSON){
self.json = json["data"]["children"]
}
func goToView(identifier:String){
self.performSegueWithIdentifier(identifier, sender: self)
}
func onLoad(){
getJSON(REDDIT)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == SEGUE_ON_LOAD {
let vc = segue.destinationViewController as! CardsTableViewController
vc.json = self.json
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
onLoad()
}
}
| mit | 50878c837be6da570f7e86edeeec6500 | 25.083333 | 91 | 0.573163 | 4.616519 | false | false | false | false |
chrisjmendez/swift-exercises | Concurrency/Operational Queues/Resources/GUI/MyStyleKit.swift | 1 | 14664 | //
// MyStyleKit.swift
// Concurrency
//
// Created by Chris Mendez on 4/20/15.
// Copyright (c) 2015 . All rights reserved.
//
// Generated by PaintCode (www.paintcodeapp.com)
//
import UIKit
public class MyStyleKit : NSObject {
//// Drawing Methods
public class func drawCanvas2() {
//// Color Declarations
let fillColor2 = UIColor(red: 0.000, green: 0.000, blue: 0.000, alpha: 1.000)
//// Group 2
//// Bezier Drawing
var bezierPath = UIBezierPath()
bezierPath.moveToPoint(CGPointMake(74.72, 73.84))
bezierPath.addCurveToPoint(CGPointMake(81.85, 71.09), controlPoint1: CGPointMake(77.47, 73.84), controlPoint2: CGPointMake(79.96, 72.78))
bezierPath.addCurveToPoint(CGPointMake(88.98, 73.84), controlPoint1: CGPointMake(83.74, 72.78), controlPoint2: CGPointMake(86.23, 73.84))
bezierPath.addCurveToPoint(CGPointMake(99.67, 63.27), controlPoint1: CGPointMake(94.88, 73.84), controlPoint2: CGPointMake(99.67, 69.1))
bezierPath.addCurveToPoint(CGPointMake(88.98, 52.7), controlPoint1: CGPointMake(99.67, 57.43), controlPoint2: CGPointMake(94.88, 52.7))
bezierPath.addCurveToPoint(CGPointMake(81.85, 55.44), controlPoint1: CGPointMake(86.23, 52.7), controlPoint2: CGPointMake(83.74, 53.76))
bezierPath.addCurveToPoint(CGPointMake(74.72, 52.7), controlPoint1: CGPointMake(79.96, 53.76), controlPoint2: CGPointMake(77.47, 52.7))
bezierPath.addCurveToPoint(CGPointMake(64.03, 63.27), controlPoint1: CGPointMake(68.82, 52.7), controlPoint2: CGPointMake(64.03, 57.43))
bezierPath.addCurveToPoint(CGPointMake(74.72, 73.84), controlPoint1: CGPointMake(64.03, 69.1), controlPoint2: CGPointMake(68.82, 73.84))
bezierPath.closePath()
fillColor2.setFill()
bezierPath.fill()
//// Bezier 2 Drawing
var bezier2Path = UIBezierPath()
bezier2Path.moveToPoint(CGPointMake(106.8, 17.47))
bezier2Path.addLineToPoint(CGPointMake(21.25, 17.47))
bezier2Path.addCurveToPoint(CGPointMake(14.12, 24.51), controlPoint1: CGPointMake(17.31, 17.47), controlPoint2: CGPointMake(14.12, 20.62))
bezier2Path.addLineToPoint(CGPointMake(14.12, 45.65))
bezier2Path.addLineToPoint(CGPointMake(106.8, 45.65))
bezier2Path.addLineToPoint(CGPointMake(106.8, 80.88))
bezier2Path.addLineToPoint(CGPointMake(56.9, 80.88))
bezier2Path.addLineToPoint(CGPointMake(56.9, 87.93))
bezier2Path.addLineToPoint(CGPointMake(106.8, 87.93))
bezier2Path.addCurveToPoint(CGPointMake(113.93, 80.88), controlPoint1: CGPointMake(110.75, 87.93), controlPoint2: CGPointMake(113.93, 84.78))
bezier2Path.addLineToPoint(CGPointMake(113.93, 24.51))
bezier2Path.addCurveToPoint(CGPointMake(106.8, 17.47), controlPoint1: CGPointMake(113.93, 20.62), controlPoint2: CGPointMake(110.75, 17.47))
bezier2Path.closePath()
bezier2Path.moveToPoint(CGPointMake(21.25, 24.51))
bezier2Path.addLineToPoint(CGPointMake(106.8, 24.51))
bezier2Path.addLineToPoint(CGPointMake(106.8, 31.56))
bezier2Path.addLineToPoint(CGPointMake(21.25, 31.56))
bezier2Path.addLineToPoint(CGPointMake(21.25, 24.51))
bezier2Path.closePath()
fillColor2.setFill()
bezier2Path.fill()
//// Bezier 3 Drawing
var bezier3Path = UIBezierPath()
bezier3Path.moveToPoint(CGPointMake(24.81, 52.7))
bezier3Path.addCurveToPoint(CGPointMake(-0.14, 77.36), controlPoint1: CGPointMake(11.03, 52.7), controlPoint2: CGPointMake(-0.14, 63.74))
bezier3Path.addCurveToPoint(CGPointMake(24.81, 102.02), controlPoint1: CGPointMake(-0.14, 90.98), controlPoint2: CGPointMake(11.03, 102.02))
bezier3Path.addCurveToPoint(CGPointMake(49.77, 77.36), controlPoint1: CGPointMake(38.6, 102.02), controlPoint2: CGPointMake(49.77, 90.98))
bezier3Path.addCurveToPoint(CGPointMake(24.81, 52.7), controlPoint1: CGPointMake(49.77, 63.74), controlPoint2: CGPointMake(38.6, 52.7))
bezier3Path.closePath()
bezier3Path.moveToPoint(CGPointMake(39.94, 87.32))
bezier3Path.addLineToPoint(CGPointMake(34.9, 92.31))
bezier3Path.addLineToPoint(CGPointMake(24.81, 82.34))
bezier3Path.addLineToPoint(CGPointMake(14.73, 92.31))
bezier3Path.addLineToPoint(CGPointMake(9.69, 87.32))
bezier3Path.addLineToPoint(CGPointMake(19.77, 77.36))
bezier3Path.addLineToPoint(CGPointMake(9.69, 67.4))
bezier3Path.addLineToPoint(CGPointMake(14.73, 62.41))
bezier3Path.addLineToPoint(CGPointMake(24.81, 72.38))
bezier3Path.addLineToPoint(CGPointMake(34.9, 62.41))
bezier3Path.addLineToPoint(CGPointMake(39.94, 67.4))
bezier3Path.addLineToPoint(CGPointMake(29.85, 77.36))
bezier3Path.addLineToPoint(CGPointMake(39.94, 87.32))
bezier3Path.closePath()
fillColor2.setFill()
bezier3Path.fill()
}
public class func drawCanvas1() {
//// Color Declarations
let fillColor2 = UIColor(red: 0.000, green: 0.000, blue: 0.000, alpha: 1.000)
//// Group 2
//// Bezier Drawing
var bezierPath = UIBezierPath()
bezierPath.moveToPoint(CGPointMake(98.26, 58.76))
bezierPath.addLineToPoint(CGPointMake(98.26, 58.76))
bezierPath.addCurveToPoint(CGPointMake(58.57, 98.45), controlPoint1: CGPointMake(98.26, 80.65), controlPoint2: CGPointMake(80.45, 98.45))
bezierPath.addCurveToPoint(CGPointMake(26.84, 82.55), controlPoint1: CGPointMake(45.59, 98.45), controlPoint2: CGPointMake(34.08, 92.19))
bezierPath.addLineToPoint(CGPointMake(38.72, 70.66))
bezierPath.addLineToPoint(CGPointMake(3, 70.66))
bezierPath.addLineToPoint(CGPointMake(3, 106.39))
bezierPath.addLineToPoint(CGPointMake(15.51, 93.87))
bezierPath.addCurveToPoint(CGPointMake(58.57, 114.32), controlPoint1: CGPointMake(25.7, 106.35), controlPoint2: CGPointMake(41.2, 114.32))
bezierPath.addCurveToPoint(CGPointMake(114.13, 58.76), controlPoint1: CGPointMake(89.25, 114.32), controlPoint2: CGPointMake(114.13, 89.45))
bezierPath.addLineToPoint(CGPointMake(98.26, 58.76))
bezierPath.addLineToPoint(CGPointMake(98.26, 58.76))
bezierPath.closePath()
fillColor2.setFill()
bezierPath.fill()
//// Bezier 2 Drawing
var bezier2Path = UIBezierPath()
bezier2Path.moveToPoint(CGPointMake(101.61, 23.65))
bezier2Path.addCurveToPoint(CGPointMake(58.56, 3.19), controlPoint1: CGPointMake(91.43, 11.17), controlPoint2: CGPointMake(75.93, 3.19))
bezier2Path.addCurveToPoint(CGPointMake(3, 58.76), controlPoint1: CGPointMake(27.88, 3.19), controlPoint2: CGPointMake(3, 28.07))
bezier2Path.addLineToPoint(CGPointMake(18.87, 58.76))
bezier2Path.addCurveToPoint(CGPointMake(58.56, 19.07), controlPoint1: CGPointMake(18.87, 36.87), controlPoint2: CGPointMake(36.68, 19.07))
bezier2Path.addCurveToPoint(CGPointMake(90.3, 34.96), controlPoint1: CGPointMake(71.53, 19.07), controlPoint2: CGPointMake(83.05, 25.32))
bezier2Path.addLineToPoint(CGPointMake(78.41, 46.85))
bezier2Path.addLineToPoint(CGPointMake(114.13, 46.85))
bezier2Path.addLineToPoint(CGPointMake(114.13, 11.14))
bezier2Path.addLineToPoint(CGPointMake(101.61, 23.65))
bezier2Path.closePath()
fillColor2.setFill()
bezier2Path.fill()
}
public class func drawCanvas3() {
//// Color Declarations
let fillColor2 = UIColor(red: 0.000, green: 0.000, blue: 0.000, alpha: 1.000)
//// Group 2
//// Bezier Drawing
var bezierPath = UIBezierPath()
bezierPath.moveToPoint(CGPointMake(53.72, 84.61))
bezierPath.addCurveToPoint(CGPointMake(55.44, 90.43), controlPoint1: CGPointMake(54.8, 86.3), controlPoint2: CGPointMake(55.44, 88.29))
bezierPath.addCurveToPoint(CGPointMake(55.41, 91.12), controlPoint1: CGPointMake(55.44, 90.66), controlPoint2: CGPointMake(55.42, 90.89))
bezierPath.addLineToPoint(CGPointMake(64.96, 91.12))
bezierPath.addCurveToPoint(CGPointMake(64.92, 90.43), controlPoint1: CGPointMake(64.95, 90.89), controlPoint2: CGPointMake(64.92, 90.66))
bezierPath.addCurveToPoint(CGPointMake(66.64, 84.61), controlPoint1: CGPointMake(64.92, 88.29), controlPoint2: CGPointMake(65.56, 86.3))
bezierPath.addLineToPoint(CGPointMake(53.72, 84.61))
bezierPath.closePath()
fillColor2.setFill()
bezierPath.fill()
//// Bezier 2 Drawing
var bezier2Path = UIBezierPath()
bezier2Path.moveToPoint(CGPointMake(73.99, 38.31))
bezier2Path.addCurveToPoint(CGPointMake(74.01, 37.95), controlPoint1: CGPointMake(73.99, 38.19), controlPoint2: CGPointMake(74.01, 38.07))
bezier2Path.addLineToPoint(CGPointMake(32.5, 34.07))
bezier2Path.addLineToPoint(CGPointMake(30.07, 23.96))
bezier2Path.addCurveToPoint(CGPointMake(27, 20.64), controlPoint1: CGPointMake(29.7, 22.39), controlPoint2: CGPointMake(28.54, 21.13))
bezier2Path.addLineToPoint(CGPointMake(9.03, 14.85))
bezier2Path.addCurveToPoint(CGPointMake(6.38, 14.23), controlPoint1: CGPointMake(8.23, 14.46), controlPoint2: CGPointMake(7.34, 14.23))
bezier2Path.addCurveToPoint(CGPointMake(0.23, 20.35), controlPoint1: CGPointMake(2.99, 14.23), controlPoint2: CGPointMake(0.23, 16.96))
bezier2Path.addCurveToPoint(CGPointMake(6.38, 26.46), controlPoint1: CGPointMake(0.23, 23.72), controlPoint2: CGPointMake(2.99, 26.46))
bezier2Path.addCurveToPoint(CGPointMake(10.4, 24.95), controlPoint1: CGPointMake(7.93, 26.46), controlPoint2: CGPointMake(9.31, 25.87))
bezier2Path.addLineToPoint(CGPointMake(21.69, 28.58))
bezier2Path.addCurveToPoint(CGPointMake(32.08, 71.94), controlPoint1: CGPointMake(21.69, 28.58), controlPoint2: CGPointMake(30.52, 66.16))
bezier2Path.addCurveToPoint(CGPointMake(36.46, 83.18), controlPoint1: CGPointMake(32.87, 74.92), controlPoint2: CGPointMake(34.35, 79.34))
bezier2Path.addCurveToPoint(CGPointMake(42.24, 79.83), controlPoint1: CGPointMake(37.96, 81.52), controlPoint2: CGPointMake(39.96, 80.32))
bezier2Path.addCurveToPoint(CGPointMake(40.38, 75.48), controlPoint1: CGPointMake(41.38, 78.36), controlPoint2: CGPointMake(40.69, 76.79))
bezier2Path.addLineToPoint(CGPointMake(85.63, 75.48))
bezier2Path.addCurveToPoint(CGPointMake(90.07, 72.11), controlPoint1: CGPointMake(87.7, 75.48), controlPoint2: CGPointMake(89.52, 74.11))
bezier2Path.addLineToPoint(CGPointMake(92.56, 60.05))
bezier2Path.addCurveToPoint(CGPointMake(73.99, 38.31), controlPoint1: CGPointMake(82.05, 58.33), controlPoint2: CGPointMake(73.99, 49.25))
bezier2Path.closePath()
fillColor2.setFill()
bezier2Path.fill()
//// Oval Drawing
var ovalPath = UIBezierPath(ovalInRect: CGRectMake(38.45, 83.55, 12.4, 13.4))
fillColor2.setFill()
ovalPath.fill()
//// Oval 2 Drawing
var oval2Path = UIBezierPath(ovalInRect: CGRectMake(69, 83.6, 13.4, 13.3))
fillColor2.setFill()
oval2Path.fill()
//// Bezier 3 Drawing
var bezier3Path = UIBezierPath()
bezier3Path.moveToPoint(CGPointMake(96.16, 20.18))
bezier3Path.addCurveToPoint(CGPointMake(77.93, 38.31), controlPoint1: CGPointMake(86.11, 20.18), controlPoint2: CGPointMake(77.93, 28.32))
bezier3Path.addCurveToPoint(CGPointMake(93.36, 56.16), controlPoint1: CGPointMake(77.93, 47.36), controlPoint2: CGPointMake(84.64, 54.81))
bezier3Path.addCurveToPoint(CGPointMake(96.16, 56.45), controlPoint1: CGPointMake(94.28, 56.31), controlPoint2: CGPointMake(95.2, 56.45))
bezier3Path.addCurveToPoint(CGPointMake(114.39, 38.31), controlPoint1: CGPointMake(106.21, 56.45), controlPoint2: CGPointMake(114.39, 48.31))
bezier3Path.addCurveToPoint(CGPointMake(96.16, 20.18), controlPoint1: CGPointMake(114.39, 28.32), controlPoint2: CGPointMake(106.21, 20.18))
bezier3Path.closePath()
bezier3Path.moveToPoint(CGPointMake(108.61, 41.54))
bezier3Path.addLineToPoint(CGPointMake(99.5, 41.54))
bezier3Path.addLineToPoint(CGPointMake(99.5, 50.55))
bezier3Path.addCurveToPoint(CGPointMake(96.51, 52.33), controlPoint1: CGPointMake(99.5, 51.74), controlPoint2: CGPointMake(98.5, 52.33))
bezier3Path.addLineToPoint(CGPointMake(95.68, 52.33))
bezier3Path.addCurveToPoint(CGPointMake(94.18, 52.15), controlPoint1: CGPointMake(95.08, 52.33), controlPoint2: CGPointMake(94.6, 52.26))
bezier3Path.addCurveToPoint(CGPointMake(92.7, 50.55), controlPoint1: CGPointMake(93.22, 51.9), controlPoint2: CGPointMake(92.7, 51.38))
bezier3Path.addLineToPoint(CGPointMake(92.7, 41.54))
bezier3Path.addLineToPoint(CGPointMake(83.71, 41.54))
bezier3Path.addCurveToPoint(CGPointMake(81.93, 38.69), controlPoint1: CGPointMake(82.54, 41.54), controlPoint2: CGPointMake(81.96, 40.58))
bezier3Path.addCurveToPoint(CGPointMake(81.92, 38.58), controlPoint1: CGPointMake(81.93, 38.65), controlPoint2: CGPointMake(81.92, 38.62))
bezier3Path.addLineToPoint(CGPointMake(81.92, 38.17))
bezier3Path.addCurveToPoint(CGPointMake(83.71, 35.2), controlPoint1: CGPointMake(81.92, 36.19), controlPoint2: CGPointMake(82.52, 35.2))
bezier3Path.addLineToPoint(CGPointMake(92.7, 35.2))
bezier3Path.addLineToPoint(CGPointMake(92.7, 26.07))
bezier3Path.addCurveToPoint(CGPointMake(95.68, 24.29), controlPoint1: CGPointMake(92.7, 24.89), controlPoint2: CGPointMake(93.69, 24.29))
bezier3Path.addLineToPoint(CGPointMake(96.51, 24.29))
bezier3Path.addCurveToPoint(CGPointMake(99.5, 26.07), controlPoint1: CGPointMake(98.49, 24.29), controlPoint2: CGPointMake(99.5, 24.89))
bezier3Path.addLineToPoint(CGPointMake(99.5, 35.2))
bezier3Path.addLineToPoint(CGPointMake(108.61, 35.2))
bezier3Path.addCurveToPoint(CGPointMake(110.39, 38.17), controlPoint1: CGPointMake(109.8, 35.2), controlPoint2: CGPointMake(110.39, 36.19))
bezier3Path.addLineToPoint(CGPointMake(110.39, 38.58))
bezier3Path.addCurveToPoint(CGPointMake(108.61, 41.54), controlPoint1: CGPointMake(110.4, 40.56), controlPoint2: CGPointMake(109.8, 41.54))
bezier3Path.closePath()
fillColor2.setFill()
bezier3Path.fill()
}
}
@objc protocol StyleKitSettableImage {
func setImage(image: UIImage!)
}
@objc protocol StyleKitSettableSelectedImage {
func setSelectedImage(image: UIImage!)
}
| mit | c5894e66202dfd5771991e132413a781 | 61.666667 | 149 | 0.702946 | 3.659596 | false | false | false | false |
mirrorinf/Mathematicus | Mathematicus/Complex.swift | 1 | 3258 | // Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
import Foundation
public struct Complex {
public let real, imaginary: Double
public init(fromPolarAngle a: Double, polarDistance d: Double) {
self.real = d * cos(a)
self.imaginary = d * sin(a)
}
public init(fromOrthonormalReal r: Double, imaginary i: Double) {
self.real = r
self.imaginary = i
}
public init(realNumber r: Double) {
self.real = r
self.imaginary = 0
}
public init(pureImaginaryNumber i: Double) {
self.real = 0
self.imaginary = i
}
public var absolute: Double {
return sqrt(real * real + imaginary * imaginary)
}
}
public func +(lhs: Complex, rhs: Complex) -> Complex {
return Complex(fromOrthonormalReal: lhs.real + rhs.real, imaginary: lhs.imaginary + rhs.imaginary)
}
public func -(lhs: Complex, rhs: Complex) -> Complex {
return Complex(fromOrthonormalReal: lhs.real - rhs.real, imaginary: lhs.imaginary - rhs.imaginary)
}
public func *(lhs: Complex, rhs: Complex) -> Complex {
let r = lhs.real * rhs.real - lhs.imaginary * rhs.imaginary
let i = lhs.imaginary * rhs.real + lhs.real * rhs.imaginary
return Complex(fromOrthonormalReal: r, imaginary: i)
}
public func /(lhs: Complex, rhs: Complex) -> Complex {
let r = lhs.real * rhs.real + lhs.imaginary * rhs.imaginary
let i = lhs.imaginary * rhs.real - lhs.real * rhs.imaginary
let ns = rhs.absolute * rhs.absolute
return Complex(fromOrthonormalReal: r / ns, imaginary: i / ns)
}
public prefix func -(x: Complex) -> Complex {
return Complex(fromOrthonormalReal: -x.real, imaginary: -x.imaginary)
}
public func ==(lhs: Complex, rhs: Complex) -> Bool {
return lhs.real == rhs.real && lhs.imaginary == rhs.imaginary
}
extension Complex: Number {
public static let identity = Complex(realNumber: 1.0)
public static let zero = Complex(realNumber: 0.0)
public static func realNumber(_ d: Double) -> Complex {
return Complex(realNumber: d)
}
}
extension Complex: AlgebraicComplete {
}
extension Complex: NewtonMethodAppliable {
public static func randomElement() -> Complex {
let r = Double.randomElement()
let i = Double.randomElement()
return Complex(fromOrthonormalReal: r, imaginary: i)
}
}
extension Complex: Continuum {
public func scale(at x: Double) -> Complex {
return Complex(fromOrthonormalReal: self.real * x, imaginary: self.imaginary * x)
}
}
extension Complex: ComplexLikeSystem {
public var conjugate: Complex {
return Complex(fromOrthonormalReal: self.real, imaginary: -self.imaginary)
}
}
| apache-2.0 | af53a4f54eb3928c89307d0591c58cb4 | 29.166667 | 99 | 0.721915 | 3.603982 | false | false | false | false |
ABTSoftware/SciChartiOSTutorial | v2.x/Examples/SciChartDemo/ShareChartSwiftExample/ShareChartSwiftExample/DoubleSeries.swift | 1 | 1789 | //******************************************************************************
// SCICHART® Copyright SciChart Ltd. 2011-2018. All rights reserved.
//
// Web: http://www.scichart.com
// Support: [email protected]
// Sales: [email protected]
//
// DoubleSeries.swift is part of the SCICHART® Examples. Permission is hereby granted
// to modify, create derivative works, distribute and publish any part of this source
// code whether for commercial, private or personal use.
//
// The SCICHART® examples are distributed in the hope that they will be useful, but
// without any warranty. It is provided "AS IS" without warranty of any kind, either
// expressed or implied.
//******************************************************************************
import UIKit
import SciChart
class DoubleSeries: NSObject {
private var xArray: SCIArrayController
private var yArray: SCIArrayController
var xValues: SCIGenericType {
var arrayPointer = SCIGeneric(xArray.data())
arrayPointer.type = .doublePtr
return arrayPointer
}
var yValues: SCIGenericType {
var arrayPointer = SCIGeneric(yArray.data())
arrayPointer.type = .doublePtr
return arrayPointer
}
var size: Int32 {
return xArray.count()
}
override init() {
xArray = SCIArrayController(type: .double)
yArray = SCIArrayController(type: .double)
super.init()
}
init(capacity: Int32) {
xArray = SCIArrayController(type: .double, size: capacity)
yArray = SCIArrayController(type: .double, size: capacity)
super.init()
}
func addX(_ x: Double, y: Double) {
xArray.append(SCIGeneric(x))
yArray.append(SCIGeneric(y))
}
}
| mit | c60816d8010eb140a90212b34baaf277 | 30.333333 | 85 | 0.601344 | 4.853261 | false | false | false | false |
fbernardo/stripe-ios | Example/Stripe iOS Example (Simple)/AppDelegate.swift | 1 | 2111 | //
// AppDelegate.swift
// Stripe iOS Exampe (Simple)
//
// Created by Jack Flintermann on 1/15/15.
// Copyright (c) 2015 Stripe. All rights reserved.
//
import UIKit
import Stripe
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
let rootVC = BrowseProductsViewController()
let navigationController = UINavigationController(rootViewController: rootVC)
let window = UIWindow(frame: UIScreen.main.bounds)
window.rootViewController = navigationController;
window.makeKeyAndVisible()
self.window = window
return true
}
// This method is where you handle URL opens if you are using a native scheme URLs (eg "yourexampleapp://")
func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool {
let stripeHandled = Stripe.handleURLCallback(with: url)
if (stripeHandled) {
return true
}
else {
// This was not a stripe url, do whatever url handling your app
// normally does, if any.
}
return false
}
// This method is where you handle URL opens if you are using univeral link URLs (eg "https://example.com/stripe_ios_callback")
func application(_ application: UIApplication, continue userActivity: NSUserActivity, restorationHandler: @escaping ([Any]?) -> Void) -> Bool {
if userActivity.activityType == NSUserActivityTypeBrowsingWeb {
if let url = userActivity.webpageURL {
let stripeHandled = Stripe.handleURLCallback(with: url)
if (stripeHandled) {
return true
}
else {
// This was not a stripe url, do whatever url handling your app
// normally does, if any.
}
}
}
return false
}
}
| mit | bdc9c7b73bb3b65f8f2193465d3428fe | 34.779661 | 147 | 0.627665 | 5.251244 | false | false | false | false |
audiokit/AudioKit | Sources/AudioKit/Sequencing/Apple Sequencer/MIDIMetaEvent+allocate.swift | 3 | 1149 | // Copyright AudioKit. All Rights Reserved. Revision History at http://github.com/AudioKit/AudioKit/
import AVFoundation
import Foundation
extension MIDIMetaEvent {
/// `MIDIMetaEvent` is a variable length C structure. YOU MUST create one using this function
/// if the data is of length > 0.
/// - Parameters:
/// - metaEventType: type of event
/// - data: event data
/// - Returns: pointer to allocated event.
static func allocate(metaEventType: MIDIByte, data: [MIDIByte]) -> UnsafeMutablePointer<MIDIMetaEvent> {
let size = MemoryLayout<MIDIMetaEvent>.size + data.count
let mem = UnsafeMutableRawPointer.allocate(byteCount: size,
alignment: MemoryLayout<Int8>.alignment)
let ptr = mem.bindMemory(to: MIDIMetaEvent.self, capacity: 1)
ptr.pointee.metaEventType = metaEventType
ptr.pointee.dataLength = UInt32(data.count)
withUnsafeMutablePointer(to: &ptr.pointee.data) { pointer in
for i in 0 ..< data.count {
pointer[i] = data[i]
}
}
return ptr
}
}
| mit | d16044ec3e867fe9285b5efc86e8ed33 | 37.3 | 108 | 0.630113 | 4.633065 | false | false | false | false |
eurofurence/ef-app_ios | Packages/EurofurenceModel/Sources/EurofurenceModel/Public/Default Dependency Implementations/Core Data Store/Model Adaptation/ReadAnnouncementEntity+Adaptation.swift | 3 | 686 | import Foundation
extension ReadAnnouncementEntity: EntityAdapting {
typealias AdaptedType = AnnouncementIdentifier
static func makeIdentifyingPredicate(for model: AnnouncementIdentifier) -> NSPredicate {
return NSPredicate(format: "announcementIdentifier == %@", model.rawValue)
}
func asAdaptedType() -> AnnouncementIdentifier {
guard let announcementIdentifier = announcementIdentifier else {
abandonDueToInconsistentState()
}
return AnnouncementIdentifier(announcementIdentifier)
}
func consumeAttributes(from value: AnnouncementIdentifier) {
announcementIdentifier = value.rawValue
}
}
| mit | 6dc523d988e9a24a59a8882a20b3f814 | 28.826087 | 92 | 0.72449 | 6.070796 | false | false | false | false |
LarkNan/SXMWB | SXMWeibo/SXMWeibo/Classes/Home/SXMPictureView.swift | 1 | 3403 | //
// SXMPictureView.swift
// SXMWeibo
//
// Created by 申铭 on 2017/3/12.
// Copyright © 2017年 shenming. All rights reserved.
//
import UIKit
import SDWebImage
class SXMPictureView: UICollectionView, UICollectionViewDataSource {
// 配图高度约束
@IBOutlet weak var pictureCollectionViewHeightCons: NSLayoutConstraint!
// 配图宽度约束
@IBOutlet weak var pictureCollectionViewWidthCons: NSLayoutConstraint!
// 配图布局对象
@IBOutlet weak var flowLayout: UICollectionViewFlowLayout!
var viewModel: StatusViewModel? {
didSet{
// 更新配图
reloadData()
let (itemSize, clvSize) = calculateSize()
// 更新cell尺寸
if itemSize != CGSizeZero {
flowLayout.itemSize = itemSize
}
// 更新collectionView尺寸
pictureCollectionViewHeightCons.constant = clvSize.height
pictureCollectionViewWidthCons.constant = clvSize.width
}
}
override func awakeFromNib() {
super.awakeFromNib()
self.dataSource = self
}
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return viewModel?.thumbnail_pic?.count ?? 0
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("pictureCell", forIndexPath: indexPath) as! HomePictureCell
// cell.backgroundColor = UIColor.redColor()
cell.url = viewModel!.thumbnail_pic![indexPath.item]
return cell
}
// MARK: - 内部控制方法
// 计算cell和collectionview的尺寸
private func calculateSize() -> (CGSize, CGSize) {
let count = viewModel?.thumbnail_pic?.count ?? 0
// 无配图
if count == 0 {
return (CGSizeZero, CGSizeZero)
}
// 一张配图
if count == 1 {
let key = viewModel?.thumbnail_pic!.first!.absoluteString
// 获取缓存的图片
let image = SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(key)
return (image.size, image.size)
}
let imageWidth: CGFloat = 90
let imageHeight: CGFloat = 90
let imageMargin: CGFloat = 10
// 四张配图
if count == 4 {
let col = 2
let row = col
let width = imageWidth * CGFloat(col) + CGFloat(col - 1) * imageMargin
let height = imageHeight * CGFloat(row) + CGFloat(row - 1) * imageMargin
return (CGSize(width: width, height: height), CGSize(width: width, height: height))
}
let col = 3
let row = (count - 1) / 3 + 1
let width = imageWidth * CGFloat(col) + CGFloat(col - 1) * imageMargin
let height = imageHeight * CGFloat(row) + CGFloat(row - 1) * imageMargin
return (CGSize(width: imageWidth, height: imageHeight), CGSize(width: width, height: height))
}
}
class HomePictureCell: UICollectionViewCell {
var url: NSURL? {
didSet {
customIconImageView.sd_setImageWithURL(url)
}
}
@IBOutlet weak var customIconImageView: UIImageView!
}
| mit | 910e34e878ec6a3d01fc6faf14c64374 | 31.117647 | 132 | 0.611111 | 5.009174 | false | false | false | false |
wangyaqing/LeetCode-swift | Solutions/6.ZigZag Conversion.playground/Contents.swift | 1 | 701 | //: Playground - noun: a place where people can play
func convert(_ s: String, _ numRows: Int) -> String {
let len = numRows * 2 - 2
guard len > 0 else { return s }
let chars = Array(s.characters)
var rowsArrow = [[Character]]()
for _ in 0..<numRows {
rowsArrow.append([Character]())
}
for index in 0..<chars.count {
let mold = index % len
if mold < numRows {
rowsArrow[mold].append(chars[index])
} else {
rowsArrow[len - mold].append(chars[index])
}
}
var result = ""
for index in 0..<numRows {
result += String(rowsArrow[index])
}
return result
}
convert("AAAAA", 2)
| mit | 1da105e69b6804aa77e823cdefa96502 | 24.035714 | 54 | 0.543509 | 3.809783 | false | false | false | false |
mpclarkson/StravaSwift | Sources/StravaSwift/Upload.swift | 1 | 2793 | //
// Upload.swift
// StravaSwift
//
// Created by Matthew on 11/11/2015.
// Copyright © 2015 Matthew Clarkson. All rights reserved.
//
import Foundation
import SwiftyJSON
/**
Upload struct
Uploading to Strava is an asynchronous process. A file is uploaded using a multipart/form-data POST request which performs initial checks on the data and enqueues the file for processing. The activity will not appear in other API requests until it has finished processing successfully.
Processing status may be checked by polling Strava. A one-second or longer polling interval is recommended. The mean processing time is currently around 8 seconds. Once processing is complete, Strava will respond to polling requests with the activity’s ID.
Errors can occur during the submission or processing steps and may be due to malformed activity data or duplicate data submission.
- warning: Not yet tested
**/
public struct UploadData {
public var activityType: ActivityType?
public var name: String?
public var description: String?
public var `private`: Bool?
public var trainer: Bool?
public var externalId: String?
public var dataType: DataType
public var file: Data
public init(name: String, dataType: DataType, file: Data) {
self.name = name
self.dataType = dataType
self.file = file
}
public init(activityType: ActivityType?, name: String?, description: String?,
`private`: Bool?, trainer: Bool?, externalId: String?, dataType: DataType, file: Data) {
self.activityType = activityType
self.description = description
self.`private` = `private`
self.trainer = trainer
self.externalId = externalId
self.name = name
self.dataType = dataType
self.file = file
}
internal var params: [String: Any] {
var params: [String: Any] = [:]
params["data_type"] = dataType.rawValue
params["name"] = name
params["description"] = description
if let `private` = `private` {
params["private"] = (`private` as NSNumber).stringValue
}
if let trainer = trainer {
params["trainer"] = (trainer as NSNumber).stringValue
}
params["external_id"] = externalId
return params
}
}
/**
Upload status
**/
public final class UploadStatus: Strava {
public let id: Int?
public let externalId: String?
public let error: String?
public let status: String?
public let activityId: Int?
public required init(_ json: JSON) {
id = json["id"].int
externalId = json["external_id"].string
error = json["error"].string
status = json["status"].string
activityId = json["activity_id"].int
}
}
| mit | 893c0c38fac424ec14ca7ce86c29b959 | 31.068966 | 286 | 0.662007 | 4.642263 | false | false | false | false |
erolbaykal/EBColorEyes | EBColorEyes/EBMainCameraVC.swift | 1 | 2046 | //
// EBMainCameraVC.swift
// EBColorEyes
//
// Created by beta on 26/04/16.
// Copyright © 2016 Baykal. All rights reserved.
//
import UIKit
import AVFoundation
import Accelerate
import QuartzCore
class EBMainCameraVC: UIViewController, EBCameraCaptureSessionControllerDelegate {
@IBOutlet weak var mainImageView: UIImageView!
@IBOutlet weak var mainButton: UIButton!
@IBOutlet weak var colorOutputLabel: UILabel!
let captureSessionController = EBCameraCaptureSessionController()
let colorNamer = EBColorNamer()
let colorAnalyser = EBImageColorAnalyser()
let synthesizer = AVSpeechSynthesizer()
var colorNameString:String?
override func viewDidLoad() {
super.viewDidLoad()
captureSessionController.delegate = self
}
func EBCameraCaptureSessionBufferToUIImage(controller: EBCameraCaptureSessionController, image: UIImage) {
self.colorNameString = self.colorAnalyser.analayseImageColor(image.CGImage!, colorOrder: imageColorOrder.rgb)
dispatch_async(dispatch_get_main_queue()) { () -> Void in
self.mainImageView.layer.magnificationFilter = kCAFilterNearest
self.mainImageView.image = image
self.colorOutputLabel.text = self.colorNameString
}
}
func speak(stringToSpeak : String){
let utterance = AVSpeechUtterance(string: stringToSpeak)
utterance.voice = AVSpeechSynthesisVoice(language: "en-US")
let synthesizer = AVSpeechSynthesizer()
synthesizer.speakUtterance(utterance)
}
@IBAction func didDoubleTapMainView(sender: AnyObject) {
let state : String = "CAMERA IS NOW \(self.captureSessionController.toggleTorch() ? "ON" : "OFF")"
self.speak(state)
}
@IBAction func didTapMainButton(sender: AnyObject) {
let colorString = colorNameString
self.speak(colorString!)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
| gpl-3.0 | 5b23a6ef6908c00e9b4452b59cdba080 | 30.461538 | 118 | 0.692421 | 4.927711 | false | false | false | false |
rbreslow/SEPTAKit | SEPTAKitExample/TrainViewViewController.swift | 1 | 1467 | //
// TrainViewViewController.swift
// SEPTAKitExample
//
// Created by Rocky Breslow on 8/19/15.
// Copyright (c) 2015 Rocky Breslow. All rights reserved.
//
import UIKit
import MapKit
import SEPTAKit
class TrainViewViewController: UIViewController, TrainViewDelegate {
@IBOutlet weak var mapView: MKMapView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func reloadMap(sender: AnyObject) {
SEPTAKit.trainView(self)
}
func didLoadData(trains: [Train]) {
// http://stackoverflow.com/questions/10865088/how-do-i-remove-all-annotations-from-mkmapview-except-the-user-location-annotati
// Clears all annotations from MapView
let annotationsToRemove = mapView.annotations.filter { $0 !== self.mapView.userLocation }
mapView.removeAnnotations(annotationsToRemove)
for train in trains {
var point = MKPointAnnotation()
point.coordinate = CLLocationCoordinate2D(latitude: train.lat, longitude: train.lon)
point.title = "\(train.dest) #\(train.trainNo)"
point.subtitle = "Next Stop: \(train.nextStop)"
mapView.addAnnotation(point)
}
}
}
| mit | a8b683ecef55f675dc7ea935c3a28d07 | 30.212766 | 135 | 0.663258 | 4.392216 | false | false | false | false |
qvacua/vimr | VimR/VimR/KeysPrefReducer.swift | 1 | 739 | /**
* Tae Won Ha - http://taewon.de - @hataewon
* See LICENSE
*/
import Foundation
final class KeysPrefReducer: ReducerType {
typealias StateType = AppState
typealias ActionType = KeysPref.Action
func typedReduce(_ pair: ReduceTuple) -> ReduceTuple {
var state = pair.state
switch pair.action {
case let .isLeftOptionMeta(value):
state.mainWindowTemplate.isLeftOptionMeta = value
state.mainWindows.keys.forEach { state.mainWindows[$0]?.isLeftOptionMeta = value }
case let .isRightOptionMeta(value):
state.mainWindowTemplate.isRightOptionMeta = value
state.mainWindows.keys.forEach { state.mainWindows[$0]?.isRightOptionMeta = value }
}
return (state, pair.action, true)
}
}
| mit | dfc70f8cd3300379025788970edbb68e | 26.37037 | 89 | 0.710419 | 4.198864 | false | false | false | false |
sonsongithub/reddift | application/FrontViewController.swift | 1 | 29134 | //
// FrontViewController.swift
// reddift
//
// Created by sonson on 2015/09/02.
// Copyright © 2015年 sonson. All rights reserved.
//
import reddift
import UIKit
class FrontViewController: UITableViewController, UIViewControllerPreviewingDelegate, UITextFieldDelegate, UIViewControllerTransitioningDelegate, ImageViewAnimator {
@IBOutlet var titleTextField: UITextField?
var searchController = SearchController(style: .plain)
var cellar: LinkContainerCellar = LinkContainerCellar()
@IBOutlet var rightListButton: UIBarButtonItem?
@IBOutlet var leftAccountButton: UIBarButtonItem?
var refresh = UIRefreshControl()
var searchControllerViewBottomSpaceConstraint: NSLayoutConstraint?
// func hideThumbnail(thumbnail: Thumbnail?) {
// let imageIncludingCells = self.tableView.visibleCells.flatMap({$0 as? ImageViewAnimator})
// if let thumbnail = thumbnail {
// for i in 0..<imageIncludingCells.count {
// if let imageView = imageIncludingCells[i].targetImageView(thumbnail: thumbnail) {
// imageView.isHidden = true
// } else {
// imageView.isHidden = false
// }
// }
// } else {
// for i in 0..<imageIncludingCells.count {
// if let imageView = imageIncludingCells[i].targetImageView(thumbnail: thumbnail) {
// imageView.isHidden = true
// } else {
// imageView.isHidden = false
// }
// }
// }
// }
func targetImageView(thumbnail: Thumbnail) -> UIImageView? {
let imageIncludingCells = self.tableView.visibleCells.compactMap({$0 as? ImageViewAnimator})
for i in 0..<imageIncludingCells.count {
if let imageView = imageIncludingCells[i].targetImageView(thumbnail: thumbnail) {
return imageView
}
}
return nil
}
func imageViews() -> [UIImageView] {
return self.tableView.visibleCells
.compactMap({$0 as? ImageViewAnimator})
.flatMap({$0.imageViews()})
}
func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
return ImageViewPageDismissAnimator()
}
func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
return ImageViewPageModalAnimator()
}
func showBars() {
// UIView.animateWithDuration(1,
// animations: { () -> Void in
// self.navigationController?.navigationBar.alpha = 1
// self.navigationController?.toolbar.alpha = 1
// }) { (success) -> Void in
// }
}
// MARK: - action
@objc func didChangeThumbnailPage(notification: Notification) {
if let userInfo = notification.userInfo, let thumbnail = userInfo["thumbnail"] as? Thumbnail {
if let index = cellar.containers.index(where: { $0.link.id == thumbnail.parentID }) {
let rect = tableView.rectForRow(at: IndexPath(row: index, section: 0))
tableView.scrollRectToVisible(rect, animated: false)
if let cell = tableView.cellForRow(at: IndexPath(row: index, section: 0)) as? ImageViewAnimator {
if let imageView = cell.targetImageView(thumbnail: thumbnail) {
let rect = tableView.convert(imageView.bounds, from: imageView)
tableView.contentOffset = CGPoint(x: 0, y: rect.origin.y - 64)
}
}
}
self.imageViews().forEach({$0.isHidden = false})
}
}
@objc func didTapActionNotification(notification: Notification) {
if let userInfo = notification.userInfo, let link = userInfo["link"] as? Link, let contents = userInfo["contents"] as? LinkContainable {
let controller = UIAlertController(title: link.title, message: link.url, preferredStyle: .actionSheet)
let shareAction = UIAlertAction(title: "Share", style: .default, handler: { (_) -> Void in
let sharedURL = URL(string: link.url)!
let activityController = UIActivityViewController(activityItems: [sharedURL], applicationActivities: nil)
self.present(activityController, animated: true, completion: nil)
})
controller.addAction(shareAction)
let reportAction = UIAlertAction(title: "Report", style: .default, handler: { (_) -> Void in
contents.report()
})
controller.addAction(reportAction)
let hideAction = UIAlertAction(title: "Hide", style: .destructive, handler: { (_) -> Void in
contents.hide()
})
controller.addAction(hideAction)
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: { (_) -> Void in
})
controller.addAction(cancelAction)
self.present(controller, animated: true, completion: nil)
}
}
@objc func didTapCommentNotification(notification: Notification) {
if let userInfo = notification.userInfo, let link = userInfo["link"] as? Link {
let commentViewController = CommentViewController(nibName: nil, bundle: nil)
commentViewController.link = link
self.navigationController?.pushViewController(commentViewController, animated: true)
}
}
@objc func didTapNameNotification(notification: Notification) {
if let userInfo = notification.userInfo, let name = userInfo["name"] as? String {
let controller = UserViewController.controller(name)
self.present(controller, animated: true, completion: nil)
}
}
@objc func didTapTitleNotification(notification: Notification) {
if let userInfo = notification.userInfo, let link = userInfo["link"] as? Link, let url = URL(string: link.url) {
let controller = WebViewController(nibName: nil, bundle: nil)
controller.url = url
let nav = UINavigationController(rootViewController: controller)
self.present(nav, animated: true, completion: nil)
}
}
@objc func didTapThumbnailNotification(notification: Notification) {
if let userInfo = notification.userInfo,
let _ = userInfo["link"] as? Link,
let thumbnail = userInfo["thumbnail"] as? Thumbnail,
let _ = userInfo["view"] as? UIImageView {
let controller = createImageViewPageControllerWith(cellar.thumbnails, openThumbnail: thumbnail)
controller.modalPresentationStyle = .custom
controller.transitioningDelegate = self
self.present(controller, animated: true, completion: nil)
}
}
@objc func refreshDidChange(sender: AnyObject) {
print("refreshDidChange")
refresh.attributedTitle = NSAttributedString(string: cellar.loadingMessage())
DispatchQueue.main.async {
self.cellar.load(atTheBeginning: true)
}
}
@objc func closeSearchController(sender: AnyObject) {
titleTextField?.resignFirstResponder()
self.navigationController?.isToolbarHidden = false
self.navigationItem.leftBarButtonItem = self.leftAccountButton
self.navigationItem.rightBarButtonItem = self.rightListButton
if searchController.view.superview == self.navigationController?.view {
searchController.close(sender: self)
searchControllerViewBottomSpaceConstraint = nil
searchController.removeFromParentViewController()
}
}
@IBAction func compose(sender: AnyObject) {
// cellar.containers
if let c = cellar as? SubredditCellar {
let nav = PostCommentViewController.controller(with: c.subreddit)
self.present(nav, animated: true, completion: nil)
}
}
@IBAction func openTab(sender: AnyObject) {
// let rect = self.view.frame
//
// self.navigationController?.navigationBar.alpha = 0
// self.navigationController?.toolbar.alpha = 0
// self.tableView.showsVerticalScrollIndicator = false
// UIGraphicsBeginImageContextWithOptions(CGSize(width:rect.size.width, height:rect.size.height), false, 0.0)
// let context = UIGraphicsGetCurrentContext()
// context!.translate(x: 0.0, y: 0.0)
// self.navigationController?.view.layer.render(in: context!)
// let image = UIGraphicsGetImageFromCurrentImageContext()
// TabManager.sharedInstance.setScreenshot(image: image!)
// UIGraphicsEndImageContext()
//
// self.navigationController?.navigationBar.alpha = 1
// self.navigationController?.toolbar.alpha = 1
// self.tableView.showsVerticalScrollIndicator = true
//
// let nav = TabSelectViewController.sharedNavigationController
// if let vc = nav.topViewController as? TabSelectViewController {
// vc.startAnimationWhenWillAppearWithSnapshotView(view: self.navigationController!.view.snapshotView(afterScreenUpdates: true)!)
// }
// self.present(nav, animated: false, completion: { () -> Void in
// if let vc = nav.topViewController as? TabSelectViewController {
// vc.startAnimationWhenDidAppear()
// }
// })
}
// MARK: - Notification
@objc func openSubreddit(notification: NSNotification) {
if let userInfo = notification.userInfo, let subreddit = userInfo[SearchController.subredditKey] as? String {
cellar = SubredditCellar(subreddit: subreddit, width: self.view.frame.size.width, fontSize: 18)
self.tableView.reloadData()
cellar.load(atTheBeginning: true)
}
refresh.attributedTitle = NSAttributedString(string: cellar.tryLoadingMessage())
closeSearchController(sender: self)
}
@objc func searchSubreddit(notification: NSNotification) {
if let userInfo = notification.userInfo, let query = userInfo[SearchController.queryKey] as? String {
cellar = SearchLinkCellar(query: query, subreddit: nil, width: self.view.frame.size.width, fontSize: 18)
self.tableView.reloadData()
cellar.load(atTheBeginning: true)
}
refresh.attributedTitle = NSAttributedString(string: cellar.tryLoadingMessage())
closeSearchController(sender: self)
}
@objc func didUpdateSingleImageSize(notification: NSNotification) {
if let userInfo = notification.userInfo {
if let obj = userInfo["obj"] as? MediaLinkContainer {
print(obj)
for i in 0..<cellar.containers.count {
let b = cellar.containers[i]
if b.link.id == obj.link.id {
print(i)
self.tableView.beginUpdates()
self.tableView.reloadRows(at: [IndexPath(row: i, section: 0)], with: .fade)
self.tableView.endUpdates()
break
}
}
}
}
}
@objc func didLoadImage(notification: NSNotification) {
if let userInfo = notification.userInfo, let indexPath = userInfo[MediaLinkContainerPrefetchAtIndexPathKey] as? IndexPath, let container = userInfo[MediaLinkContainerPrefetchContentKey] as? LinkContainable {
if 0..<self.cellar.containers.count ~= indexPath.row {
if container === self.cellar.containers[indexPath.row] {
self.tableView.beginUpdates()
self.tableView.reloadRows(at: [indexPath], with: .fade)
self.tableView.endUpdates()
}
}
}
}
@objc func didLoadLinkContainerCellar(notification: NSNotification) {
if let userInfo = notification.userInfo, let atTheBeginning = userInfo[LinkContainerCellar.isAtTheBeginningKey] as? Bool {
if atTheBeginning {
self.tableView.reloadData()
refresh.endRefreshing()
}
refresh.attributedTitle = NSAttributedString(string: cellar.tryLoadingMessage())
} else if let userInfo = notification.userInfo, let indices = userInfo[LinkContainerCellar.insertIndicesKey] as? [IndexPath], let cellar = userInfo[LinkContainerCellar.providerKey] as? LinkContainerCellar {
if self.cellar === cellar {
self.tableView.beginUpdates()
self.tableView.insertRows(at: indices, with: .none)
self.tableView.endUpdates()
refresh.attributedTitle = NSAttributedString(string: cellar.tryLoadingMessage())
}
}
}
@objc func didChangedDraggingThumbnail(notification: Notification) {
if let userInfo = notification.userInfo, let thumbnail = userInfo["thumbnail"] as? Thumbnail {
self.imageViews().forEach({$0.isHidden = false})
self.targetImageView(thumbnail: thumbnail)?.isHidden = true
}
// self.navigationController?.navigationBar.alpha = 0
// self.navigationController?.toolbar.alpha = 0
}
@objc func didUpdateLinkContainable(notification: Notification) {
if let userInfo = notification.userInfo, let contents = userInfo["contents"] as? LinkContainable {
if let index = self.cellar.containers.index(where: {contents.link.id == $0.link.id}) {
let indices = [IndexPath(row: index, section: 0)]
self.tableView.beginUpdates()
self.tableView.reloadRows(at: indices, with: .none)
self.tableView.endUpdates()
}
}
}
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransition(to: size, with: coordinator)
print("viewWillTransition")
self.cellar.layout(with: size.width, fontSize: 18)
self.tableView.reloadData()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
// let con = CommentViewController(nibName: nil, bundle: nil)
// print(con.link)
// con.link = Link(id: "2zbpqj")
// self.navigationController?.pushViewController(con, animated: true)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "OpenComment" {
if let indexPath = self.tableView.indexPathForSelectedRow, let viewController = segue.destination as? CommentViewController {
let contents = cellar.containers[indexPath.row]
viewController.link = contents.link
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
override func viewDidLoad() {
super.viewDidLoad()
NotificationCenter.default.addObserver(self, selector: #selector(FrontViewController.openSubreddit(notification:)), name: SearchControllerDidOpenSubredditName, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(FrontViewController.searchSubreddit(notification:)), name: SearchControllerDidSearchSubredditName, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(FrontViewController.openSubreddit(notification:)), name: SubredditSelectTabBarControllerDidOpenSubredditName, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(FrontViewController.didUpdateSingleImageSize(notification:)), name: MediaLinkContainerSingleImageSizeDidUpdate, object: nil)
if MediaLinkCellSingleImageSize {
NotificationCenter.default.addObserver(self, selector: #selector(FrontViewController.didLoadImage(notification:)), name: LinkContainerDidLoadImageName, object: nil)
}
NotificationCenter.default.addObserver(self, selector: #selector(FrontViewController.didLoadLinkContainerCellar(notification:)), name: LinkContainerCellarDidLoadName, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(FrontViewController.didTapActionNotification(notification:)), name: LinkCellDidTapActionNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(FrontViewController.didTapCommentNotification(notification:)), name: LinkCellDidTapCommentNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(FrontViewController.didTapNameNotification(notification:)), name: LinkCellDidTapNameNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(FrontViewController.didTapTitleNotification(notification:)), name: LinkCellDidTapTitleNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(FrontViewController.didTapThumbnailNotification(notification:)), name: LinkCellDidTapThumbnailNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(FrontViewController.didUpdateLinkContainable(notification:)), name: ThingContainableDidUpdate, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(FrontViewController.didChangeThumbnailPage(notification:)), name: ImageViewPageControllerDidChangePageName, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(FrontViewController.didChangedDraggingThumbnail(notification:)), name: ImageViewPageControllerDidStartDraggingThumbnailName, object: nil)
let backButtonItem = UIBarButtonItem(title: "", style: .plain, target: nil, action: nil)
self.navigationItem.backBarButtonItem = backButtonItem
tableView.separatorInset = UIEdgeInsets.zero
tableView.layoutMargins = UIEdgeInsets.zero
tableView.register(LinkCell.self, forCellReuseIdentifier: "LinkCell")
tableView.register(ThumbnailLinkCell.self, forCellReuseIdentifier: "ThumbnailLinkCell")
tableView.register(InvisibleCell.self, forCellReuseIdentifier: "InvisibleCell")
refresh.attributedTitle = NSAttributedString(string: "Loading...")
refresh.addTarget(self, action: #selector(FrontViewController.refreshDidChange(sender:)), for: .valueChanged)
tableView.addSubview(refresh)
// cellar = SubredditCellar(subreddit: "movies", width: self.view.frame.size.width, fontSize: 18)
cellar = SubredditCellar(subreddit: "test", width: self.view.frame.size.width, fontSize: 18)
self.tableView.reloadData()
cellar.load(atTheBeginning: true)
registerForPreviewing(with: self, sourceView: self.view)
NotificationCenter.default.addObserver(self, selector: #selector(FrontViewController.keyboardWillChangeFrame(notification:)), name: .UIKeyboardDidShow, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(FrontViewController.keyboardWillChangeFrame(notification:)), name: .UIKeyboardWillHide, object: nil)
}
// MARK: - UIViewControllerPreviewingDelegate
func previewingContext(_ previewingContext: UIViewControllerPreviewing, commit viewControllerToCommit: UIViewController) {
if viewControllerToCommit is CommentViewController {
self.navigationController?.pushViewController(viewControllerToCommit, animated: false)
} else if let controller = viewControllerToCommit as? ImageViewPageController {
controller.setOffset()
controller.modalPresentationStyle = .custom
controller.transitioningDelegate = self
self.present(viewControllerToCommit, animated: false, completion: nil)
} else if let controller = viewControllerToCommit as? WebViewController {
let nav = UINavigationController(rootViewController: controller)
self.present(nav, animated: false, completion: nil)
} else {
self.present(viewControllerToCommit, animated: false, completion: nil)
}
}
func previewingContext(_ previewingContext: UIViewControllerPreviewing, viewControllerForLocation location: CGPoint) -> UIViewController? {
if let cell = getCellAt(location) as? LinkCell {
if let (thumbnail, sourceRect, _, _) = cell.thumbnailAt(location, peekView: self.view) {
previewingContext.sourceRect = sourceRect
let controller = createImageViewPageControllerWith(cellar.thumbnails, openThumbnail: thumbnail, isOpenedBy3DTouch: true)
controller.isNavigationBarHidden = true
return controller
} else if let (name, sourceRect) = cell.userAt(location, peekView: self.view) {
previewingContext.sourceRect = sourceRect
let nav = UserViewController.controller(name)
return nav
} else if let (sourceRect, contents) = cell.commentAt(location, peekView: self.view) {
previewingContext.sourceRect = sourceRect
let commentViewController = CommentViewController(nibName: nil, bundle: nil)
commentViewController.link = contents.link
return commentViewController
} else if let (url, sourceRect) = cell.urlAt(location, peekView: self.view) {
previewingContext.sourceRect = sourceRect
let controller = WebViewController(nibName: nil, bundle: nil)
controller.url = url
return controller
} else {
if let container = cell.container, let url = URL(string: container.link.url) {
let sourceRect = cell.convert(cell.bounds, to: self.view)
previewingContext.sourceRect = sourceRect
let controller = WebViewController(nibName: nil, bundle: nil)
controller.url = url
return controller
}
}
}
return nil
}
func getCellAt(_ location: CGPoint) -> UITableViewCell? {
if let view = self.view {
for cell in tableView.visibleCells {
if let parent = cell.superview {
let p = view.convert(location, to: parent)
let r = cell.frame
if r.contains(p) {
return cell
}
}
}
}
return nil
}
// MARK: - Table view delegate & data source
override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
cellar.containers[indexPath.row].downloadImages()
if tableView == self.tableView {
if indexPath.row == (cellar.containers.count - 1) {
cellar.load(atTheBeginning: false)
}
}
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return cellar.containers[indexPath.row].height
}
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return cellar.containers.count
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let container = cellar.containers[indexPath.row]
let cell = tableView.dequeueReusableCell(withIdentifier: container.cellIdentifier)
switch (container, cell) {
case (_, let cell as InvisibleCell):
return cell
case (let container as MediaLinkContainer, _):
// aa
let cell = MediaLinkCell(numberOfThumbnails: container.thumbnails.count)
cell.container = container
return cell
case (let container, let cell as LinkCell):
cell.container = container
return cell
default:
return UITableViewCell(style: .default, reuseIdentifier: "Default")
}
}
// MARK: - UITextFieldDelegate
@objc func keyboardWillChangeFrame(notification: Notification) {
if let userInfo = notification.userInfo {
if let rect = userInfo[UIKeyboardFrameEndUserInfoKey] as? CGRect {
print(rect)
if let searchControllerViewBottomSpaceConstraint = self.searchControllerViewBottomSpaceConstraint {
searchControllerViewBottomSpaceConstraint.constant = 667 - rect.origin.y
}
}
}
}
func textFieldDidEndEditing(_ textField: UITextField) {
}
func textFieldDidBeginEditing(_ textField: UITextField) {
searchController = SearchController(style: .plain)
if let navigationController = self.navigationController {
navigationController.addChildViewController(searchController)
navigationController.view.addSubview(searchController.view)
searchController.view.translatesAutoresizingMaskIntoConstraints = false
let views: [String: UIView] = [
"v1": searchController.view,
"v2": self.navigationController!.view
]
navigationController.view.addConstraints(
NSLayoutConstraint.constraints(withVisualFormat: "H:|-0-[v1]-0-|", options: NSLayoutFormatOptions(), metrics: [:], views: views)
)
navigationController.view.bringSubview(toFront: navigationController.navigationBar)
let constraint1 = NSLayoutConstraint(item: navigationController.view, attribute: .top, relatedBy: .equal, toItem: searchController.view, attribute: .top, multiplier: 1, constant: -64)
let constraint2 = NSLayoutConstraint(item: navigationController.view, attribute: .bottom, relatedBy: .equal, toItem: searchController.view, attribute: .bottom, multiplier: 1, constant: 100)
navigationController.view.addConstraint(constraint1)
navigationController.view.addConstraint(constraint2)
searchControllerViewBottomSpaceConstraint = constraint2
navigationController.isToolbarHidden = true
self.navigationItem.rightBarButtonItem = nil
self.navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .cancel, target: self, action: #selector(FrontViewController.closeSearchController(sender:)))
searchController.view.alpha = 0
UIView.animate(withDuration: 0.3) {
self.searchController.view.alpha = 1
}
}
}
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
print(textField.text!)
if let t = textField.text {
let query = t + string
searchController.didChangeQuery(text: query)
}
return true
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
// if let t = textField.text {
// }
return false
}
// MARK: - LinkContainerCellar
func didLoadContents(controller: LinkContainerCellar, indexPaths: [NSIndexPath]) {
DispatchQueue.main.async(execute: { () -> Void in
self.tableView.beginUpdates()
self.tableView.insertRows(at: indexPaths.map { $0 as IndexPath}, with: .none)
self.tableView.endUpdates()
})
}
func didFailLoadContents(controller: LinkContainerCellar, error: NSError) {
if error.code == 401 {
DispatchQueue.main.async(execute: { () -> Void in
// authentication expired?
let alert = UIAlertController(title: "Error", message: "Authentication failed. Do you want to try again?", preferredStyle: .alert)
let actionOK = UIAlertAction(title: "Try", style: .default, handler: { (_) -> Void in
// reload
})
alert.addAction(actionOK)
let actionCancel = UIAlertAction(title: "Cancel", style: .default, handler: nil)
alert.addAction(actionCancel)
self.present(alert, animated: true, completion: nil)
})
}
}
}
| mit | 178fa882ebcba6779c560757a2284e49 | 48.20777 | 215 | 0.645464 | 5.512015 | false | false | false | false |
apple/swift | stdlib/public/BackDeployConcurrency/TaskSleep.swift | 5 | 9919 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2020 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import Swift
@_implementationOnly import _SwiftConcurrencyShims
@available(SwiftStdlib 5.1, *)
extension Task where Success == Never, Failure == Never {
@available(*, deprecated, renamed: "Task.sleep(nanoseconds:)")
/// Suspends the current task for at least the given duration
/// in nanoseconds.
///
/// This function doesn't block the underlying thread.
public static func sleep(_ duration: UInt64) async {
return await Builtin.withUnsafeContinuation { (continuation: Builtin.RawUnsafeContinuation) -> Void in
let job = _taskCreateNullaryContinuationJob(
priority: Int(Task.currentPriority.rawValue),
continuation: continuation)
_enqueueJobGlobalWithDelay(duration, job)
}
}
/// The type of continuation used in the implementation of
/// sleep(nanoseconds:).
private typealias SleepContinuation = UnsafeContinuation<(), Error>
/// Describes the state of a sleep() operation.
private enum SleepState {
/// The sleep continuation has not yet begun.
case notStarted
// The sleep continuation has been created and is available here.
case activeContinuation(SleepContinuation)
/// The sleep has finished.
case finished
/// The sleep was canceled.
case cancelled
/// The sleep was canceled before it even got started.
case cancelledBeforeStarted
/// Decode sleep state from the word of storage.
init(word: Builtin.Word) {
switch UInt(word) & 0x03 {
case 0:
let continuationBits = UInt(word) & ~0x03
if continuationBits == 0 {
self = .notStarted
} else {
let continuation = unsafeBitCast(
continuationBits, to: SleepContinuation.self)
self = .activeContinuation(continuation)
}
case 1:
self = .finished
case 2:
self = .cancelled
case 3:
self = .cancelledBeforeStarted
default:
fatalError("Bitmask failure")
}
}
/// Decode sleep state by loading from the given pointer
init(loading wordPtr: UnsafeMutablePointer<Builtin.Word>) {
self.init(word: Builtin.atomicload_seqcst_Word(wordPtr._rawValue))
}
/// Encode sleep state into a word of storage.
var word: UInt {
switch self {
case .notStarted:
return 0
case .activeContinuation(let continuation):
let continuationBits = unsafeBitCast(continuation, to: UInt.self)
return continuationBits
case .finished:
return 1
case .cancelled:
return 2
case .cancelledBeforeStarted:
return 3
}
}
}
/// Called when the sleep(nanoseconds:) operation woke up without being
/// canceled.
private static func onSleepWake(
_ wordPtr: UnsafeMutablePointer<Builtin.Word>
) {
while true {
let state = SleepState(loading: wordPtr)
switch state {
case .notStarted:
fatalError("Cannot wake before we even started")
case .activeContinuation(let continuation):
// We have an active continuation, so try to transition to the
// "finished" state.
let (_, won) = Builtin.cmpxchg_seqcst_seqcst_Word(
wordPtr._rawValue,
state.word._builtinWordValue,
SleepState.finished.word._builtinWordValue)
if Bool(_builtinBooleanLiteral: won) {
// The sleep finished, so invoke the continuation: we're done.
continuation.resume()
return
}
// Try again!
continue
case .finished:
fatalError("Already finished normally, can't do that again")
case .cancelled:
// The task was cancelled, which means the continuation was
// called by the cancellation handler. We need to deallocate the flag
// word, because it was left over for this task to complete.
wordPtr.deallocate()
return
case .cancelledBeforeStarted:
// Nothing to do;
return
}
}
}
/// Called when the sleep(nanoseconds:) operation has been canceled before
/// the sleep completed.
private static func onSleepCancel(
_ wordPtr: UnsafeMutablePointer<Builtin.Word>
) {
while true {
let state = SleepState(loading: wordPtr)
switch state {
case .notStarted:
// We haven't started yet, so try to transition to the cancelled-before
// started state.
let (_, won) = Builtin.cmpxchg_seqcst_seqcst_Word(
wordPtr._rawValue,
state.word._builtinWordValue,
SleepState.cancelledBeforeStarted.word._builtinWordValue)
if Bool(_builtinBooleanLiteral: won) {
return
}
// Try again!
continue
case .activeContinuation(let continuation):
// We have an active continuation, so try to transition to the
// "cancelled" state.
let (_, won) = Builtin.cmpxchg_seqcst_seqcst_Word(
wordPtr._rawValue,
state.word._builtinWordValue,
SleepState.cancelled.word._builtinWordValue)
if Bool(_builtinBooleanLiteral: won) {
// We recorded the task cancellation before the sleep finished, so
// invoke the continuation with the cancellation error.
continuation.resume(throwing: _Concurrency.CancellationError())
return
}
// Try again!
continue
case .finished, .cancelled, .cancelledBeforeStarted:
// The operation already finished, so there is nothing more to do.
return
}
}
}
/// Suspends the current task for at least the given duration
/// in nanoseconds.
///
/// If the task is canceled before the time ends,
/// this function throws `CancellationError`.
///
/// This function doesn't block the underlying thread.
public static func sleep(nanoseconds duration: UInt64) async throws {
// Allocate storage for the storage word.
let wordPtr = UnsafeMutablePointer<Builtin.Word>.allocate(capacity: 1)
// Initialize the flag word to "not started", which means the continuation
// has neither been created nor completed.
Builtin.atomicstore_seqcst_Word(
wordPtr._rawValue, SleepState.notStarted.word._builtinWordValue)
do {
// Install a cancellation handler to resume the continuation by
// throwing CancellationError.
try await withTaskCancellationHandler {
let _: () = try await withUnsafeThrowingContinuation { continuation in
while true {
let state = SleepState(loading: wordPtr)
switch state {
case .notStarted:
// The word that describes the active continuation state.
let continuationWord =
SleepState.activeContinuation(continuation).word
// Try to swap in the continuation word.
let (_, won) = Builtin.cmpxchg_seqcst_seqcst_Word(
wordPtr._rawValue,
state.word._builtinWordValue,
continuationWord._builtinWordValue)
if !Bool(_builtinBooleanLiteral: won) {
// Keep trying!
continue
}
// Create a task that resumes the continuation normally if it
// finishes first. Enqueue it directly with the delay, so it fires
// when we're done sleeping.
let sleepTaskFlags = taskCreateFlags(
priority: nil, isChildTask: false, copyTaskLocals: false,
inheritContext: false, enqueueJob: false,
addPendingGroupTaskUnconditionally: false)
let (sleepTask, _) = Builtin.createAsyncTask(sleepTaskFlags) {
onSleepWake(wordPtr)
}
_enqueueJobGlobalWithDelay(
duration, Builtin.convertTaskToJob(sleepTask))
return
case .activeContinuation, .finished:
fatalError("Impossible to have multiple active continuations")
case .cancelled:
fatalError("Impossible to have cancelled before we began")
case .cancelledBeforeStarted:
// Finish the continuation normally. We'll throw later, after
// we clean up.
continuation.resume()
return
}
}
}
} onCancel: {
onSleepCancel(wordPtr)
}
// Determine whether we got cancelled before we even started.
let cancelledBeforeStarted: Bool
switch SleepState(loading: wordPtr) {
case .notStarted, .activeContinuation, .cancelled:
fatalError("Invalid state for non-cancelled sleep task")
case .cancelledBeforeStarted:
cancelledBeforeStarted = true
case .finished:
cancelledBeforeStarted = false
}
// We got here without being cancelled, so deallocate the storage for
// the flag word and continuation.
wordPtr.deallocate()
// If we got cancelled before we even started, through the cancellation
// error now.
if cancelledBeforeStarted {
throw _Concurrency.CancellationError()
}
} catch {
// The task was cancelled; propagate the error. The "on wake" task is
// responsible for deallocating the flag word and continuation, if it's
// still running.
throw error
}
}
}
| apache-2.0 | 5b57ee996983379e379cfb77a717c43a | 32.510135 | 106 | 0.621534 | 5.37033 | false | false | false | false |
ktmswzw/jwtSwiftDemoClient | Temp/BookViewController.swift | 1 | 3115 | //
// BookViewController.swift
// Temp
//
// Created by vincent on 4/2/16.
// Copyright © 2016 xecoder. All rights reserved.
//
import UIKit
import Eureka
import JWT
import Alamofire
import SwiftyJSON
class BookViewController: FormViewController {
var detailItem: Book?
func initializeForm()
{
// form = Section(header: "Settings", footer: "These settings change how the navigation accessory view behaves")
//
//
// +++ Section()
// form +++
//
// Section()
//
// <<< TextRow() {
form
= TextRow() {
$0.title = "ID"
$0.value = self.detailItem?.id
}
<<< TextRow() {
$0.title = "Title"
$0.value = self.detailItem?.title
}
+++ Section()
<<< DateInlineRow() {
$0.title = "Public Date"
$0.value = self.detailItem?.publicDate
}
}
override func viewDidLoad() {
super.viewDidLoad()
initializeForm()
self.navigationItem.leftBarButtonItem?.target = self
self.navigationItem.leftBarButtonItem?.action = "cancelTapped:"
let addButton = UIBarButtonItem(barButtonSystemItem: .Done, target: self, action: "deleteRow:")
self.navigationItem.rightBarButtonItem = addButton
// Do any additional setup after loading the view.
}
//
func deleteRow(sender: AnyObject) {
deleteBook((self.detailItem?.id)!)
}
func deleteBook(id: String) {
let jwt = JWTTools()
let newDict: [String: String] = ["id": id]
let headers = jwt.getHeader(jwt.token, myDictionary: newDict)
Alamofire.request(.DELETE, "http://192.168.137.1:80/book/jwtDelete",headers:headers)
.responseJSON { response in
switch response.result {
case .Success:
if let json = response.result.value {
let myJosn = JSON(json)
NSLog("\(myJosn)")
self.navigationController?.popViewControllerAnimated(true)
}
case .Failure:
NSLog("error ")
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// 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 | 3bcecf5cfde99b134f88b54c7f648406 | 26.315789 | 127 | 0.505138 | 5.434555 | false | false | false | false |
auth0/Lock.swift | LockTests/PasswordlessAuthenticatableErrorSpec.swift | 2 | 2583 | // PasswordlessAuthenticatableErrorSpec.swift
//
// Copyright (c) 2017 Auth0 (http://auth0.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Quick
import Nimble
@testable import Lock
class PasswordlessAuthenticatableErrorSpec: QuickSpec {
override func spec() {
describe("localised message response") {
it("should return default string for invalid input") {
let error = PasswordlessAuthenticatableError.nonValidInput
expect(error.localizableMessage).to(contain("SOMETHING WENT WRONG"))
}
it("should return default string for code not sent") {
let error = PasswordlessAuthenticatableError.codeNotSent
expect(error.localizableMessage).to(contain("SOMETHING WENT WRONG"))
}
it("should return specific string for invalid limnk") {
let error = PasswordlessAuthenticatableError.invalidLink
expect(error.localizableMessage).to(contain("PROBLEM WITH YOUR LINK"))
}
it("should return specific string for no signup") {
let error = PasswordlessAuthenticatableError.noSignup
expect(error.localizableMessage).to(contain("DISABLED FOR THIS ACCOUNT"))
}
}
describe("user visibility") {
it("should return false") {
let error = PasswordlessAuthenticatableError.nonValidInput
expect(error.userVisible).to(beFalse())
}
}
}
}
| mit | 849b532aa7cf9ffb0220c95b91023309 | 39.359375 | 89 | 0.680991 | 5.197183 | false | false | false | false |
Floater-ping/DYDemo | DYDemo/DYDemo/Classes/Home/Controller/RecommendController.swift | 1 | 6443 | //
// RecommendController.swift
// DYDemo
//
// Created by ZYP-MAC on 2017/8/4.
// Copyright © 2017年 ZYP-MAC. All rights reserved.
//
import UIKit
//MARK:- 定义常量
fileprivate let pItemMargin : CGFloat = 10
fileprivate let pItemW : CGFloat = (pScreenWidth - pItemMargin * 3) / 2
fileprivate let pNormalItemH : CGFloat = pItemW * 3 / 4
fileprivate let pPrettyItemH : CGFloat = pItemW * 4 / 3
fileprivate let pHeaderViewH : CGFloat = 50
fileprivate let pCycleVieH : CGFloat = pScreenWidth * 3 / 8
fileprivate let pGameVieH : CGFloat = 90
fileprivate let pNormalCellID = "pNormalCellID"
fileprivate let pPrettyCellID = "pPrettyCellID"
fileprivate let pHeaderViewID = "pHeaderViewID"
class RecommendController: UIViewController {
//MARK:- 懒加载属性
fileprivate lazy var collectionView : UICollectionView = {[unowned self] in
// 1.创建layout
let layout = UICollectionViewFlowLayout()
layout.minimumLineSpacing = 0
layout.minimumInteritemSpacing = pItemMargin
layout.scrollDirection = .vertical
layout.headerReferenceSize = CGSize(width: pScreenWidth, height: pHeaderViewH)
layout.sectionInset = UIEdgeInsets(top: 0, left: 10, bottom: 0, right: 10)
let collectionView = UICollectionView(frame: self.view.bounds, collectionViewLayout: layout)
collectionView.backgroundColor = UIColor.white
collectionView.dataSource = self
collectionView.delegate = self
// 注册头部
collectionView.register(UINib(nibName: "HomeCollectionHeaderView", bundle: nil), forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: pHeaderViewID)
/// 注册cell
// collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: pNormalCellID)
collectionView.register(UINib(nibName: "CollectionNormalCell", bundle: nil), forCellWithReuseIdentifier: pNormalCellID)
// 颜值cell
collectionView.register(UINib(nibName: "CollectionPrettyCell", bundle: nil), forCellWithReuseIdentifier: pPrettyCellID)
// 设置大小随父控件拉伸
collectionView.autoresizingMask = [.flexibleHeight,.flexibleWidth]
return collectionView;
}()
fileprivate lazy var recomendVM : RecommendViewModel = RecommendViewModel()
/// 轮播view
fileprivate lazy var cycleView : RecommendCycleView = {
let cycleView = RecommendCycleView.recommendCycleView()
cycleView.frame = CGRect(x: 0, y: -pCycleVieH-pGameVieH, width: pScreenWidth, height: pCycleVieH)
return cycleView
}()
fileprivate lazy var gameView : RecommendGameView = {
let gameView = RecommendGameView.recommendGameView()
gameView.frame = CGRect(x: 0, y: -pGameVieH, width: pScreenWidth, height: pGameVieH);
return gameView;
}()
//MARK:- 系统回调函数
override func viewDidLoad() {
super.viewDidLoad()
// 设置UI页面
setUpUI()
loadData()
}
}
//MARK:- 设置UI页面的内容
extension RecommendController {
fileprivate func setUpUI(){
// 1.将UICollectionView添加到控制器的view上
view.addSubview(collectionView)
// 2.将cycleView添加到collectionView上
collectionView.addSubview(cycleView)
collectionView.addSubview(gameView)
// 3.设置collectionView的内边距
collectionView.contentInset = UIEdgeInsets(top: pCycleVieH+pGameVieH, left: 0, bottom: 0, right: 0)
}
}
//MARK:- 网络请求-加载数据
extension RecommendController {
func loadData() {
// 1.请求推荐数据
recomendVM.requestData {
self.collectionView.reloadData()
self.gameView.groups = self.recomendVM.anchorGroupArr
}
// 1.请求轮播数据
recomendVM.requestCycleDate {
// self不会产生强引用:闭包对控制器产生强引用;控制器对属性产生强引用,但是属性没有对闭包产生强引用
self.cycleView.cycleModelArr = self.recomendVM.cycleModelArr
}
}
}
//MARK:- UICollectionViewDataSource
extension RecommendController : UICollectionViewDataSource {
func numberOfSections(in collectionView: UICollectionView) -> Int {
return recomendVM.anchorGroupArr.count
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
let group = recomendVM.anchorGroupArr[section]
return group.anchorArr.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
// 取出数据
let groupModel = recomendVM.anchorGroupArr[indexPath.section]
let anchorModel = groupModel.anchorArr[indexPath.item]
var cell : CollectionBaseCell!
if indexPath.section == 1 {
cell = collectionView.dequeueReusableCell(withReuseIdentifier: pPrettyCellID, for: indexPath) as! CollectionPrettyCell
}else {
cell = collectionView.dequeueReusableCell(withReuseIdentifier: pNormalCellID, for: indexPath) as! CollectionNormalCell
}
cell.anchorModel = anchorModel
return cell
}
func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
let headerV = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: pHeaderViewID, for: indexPath) as! HomeCollectionHeaderView
let group = recomendVM.anchorGroupArr[indexPath.section]
headerV.groupModel = group
return headerV
}
}
//MARK:- UICollectionViewDelegate
extension RecommendController : UICollectionViewDelegateFlowLayout{
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
if indexPath.section == 1 {
return CGSize(width: pItemW, height: pPrettyItemH)
}else {
return CGSize(width: pItemW, height: pNormalItemH)
}
}
}
| mit | 1ed479a07cd6808ec9054c1e3378f4d7 | 34.222857 | 190 | 0.679267 | 5.378709 | false | false | false | false |
airbnb/lottie-ios | Sources/Private/MainThread/NodeRenderSystem/Nodes/RenderNodes/GradientStrokeNode.swift | 3 | 5123 | //
// GradientStrokeNode.swift
// lottie-swift
//
// Created by Brandon Withrow on 1/23/19.
//
import CoreGraphics
import Foundation
// MARK: - GradientStrokeProperties
final class GradientStrokeProperties: NodePropertyMap, KeypathSearchable {
// MARK: Lifecycle
init(gradientStroke: GradientStroke) {
keypathName = gradientStroke.name
opacity = NodeProperty(provider: KeyframeInterpolator(keyframes: gradientStroke.opacity.keyframes))
startPoint = NodeProperty(provider: KeyframeInterpolator(keyframes: gradientStroke.startPoint.keyframes))
endPoint = NodeProperty(provider: KeyframeInterpolator(keyframes: gradientStroke.endPoint.keyframes))
colors = NodeProperty(provider: KeyframeInterpolator(keyframes: gradientStroke.colors.keyframes))
gradientType = gradientStroke.gradientType
numberOfColors = gradientStroke.numberOfColors
width = NodeProperty(provider: KeyframeInterpolator(keyframes: gradientStroke.width.keyframes))
miterLimit = CGFloat(gradientStroke.miterLimit)
lineCap = gradientStroke.lineCap
lineJoin = gradientStroke.lineJoin
if let dashes = gradientStroke.dashPattern {
var dashPatterns = ContiguousArray<ContiguousArray<Keyframe<LottieVector1D>>>()
var dashPhase = ContiguousArray<Keyframe<LottieVector1D>>()
for dash in dashes {
if dash.type == .offset {
dashPhase = dash.value.keyframes
} else {
dashPatterns.append(dash.value.keyframes)
}
}
dashPattern = NodeProperty(provider: GroupInterpolator(keyframeGroups: dashPatterns))
self.dashPhase = NodeProperty(provider: KeyframeInterpolator(keyframes: dashPhase))
} else {
dashPattern = NodeProperty(provider: SingleValueProvider([LottieVector1D]()))
dashPhase = NodeProperty(provider: SingleValueProvider(LottieVector1D(0)))
}
keypathProperties = [
"Opacity" : opacity,
"Start Point" : startPoint,
"End Point" : endPoint,
"Colors" : colors,
"Stroke Width" : width,
"Dashes" : dashPattern,
"Dash Phase" : dashPhase,
]
properties = Array(keypathProperties.values)
}
// MARK: Internal
var keypathName: String
let opacity: NodeProperty<LottieVector1D>
let startPoint: NodeProperty<LottieVector3D>
let endPoint: NodeProperty<LottieVector3D>
let colors: NodeProperty<[Double]>
let width: NodeProperty<LottieVector1D>
let dashPattern: NodeProperty<[LottieVector1D]>
let dashPhase: NodeProperty<LottieVector1D>
let lineCap: LineCap
let lineJoin: LineJoin
let miterLimit: CGFloat
let gradientType: GradientType
let numberOfColors: Int
let keypathProperties: [String: AnyNodeProperty]
let properties: [AnyNodeProperty]
}
// MARK: - GradientStrokeNode
final class GradientStrokeNode: AnimatorNode, RenderNode {
// MARK: Lifecycle
init(parentNode: AnimatorNode?, gradientStroke: GradientStroke) {
strokeRender = GradientStrokeRenderer(parent: parentNode?.outputNode)
strokeProperties = GradientStrokeProperties(gradientStroke: gradientStroke)
self.parentNode = parentNode
}
// MARK: Internal
let strokeRender: GradientStrokeRenderer
let strokeProperties: GradientStrokeProperties
let parentNode: AnimatorNode?
var hasLocalUpdates = false
var hasUpstreamUpdates = false
var lastUpdateFrame: CGFloat? = nil
var renderer: NodeOutput & Renderable {
strokeRender
}
// MARK: Animator Node Protocol
var propertyMap: NodePropertyMap & KeypathSearchable {
strokeProperties
}
var isEnabled = true {
didSet {
strokeRender.isEnabled = isEnabled
}
}
func localUpdatesPermeateDownstream() -> Bool {
false
}
func rebuildOutputs(frame _: CGFloat) {
/// Update gradient properties
strokeRender.gradientRender.start = strokeProperties.startPoint.value.pointValue
strokeRender.gradientRender.end = strokeProperties.endPoint.value.pointValue
strokeRender.gradientRender.opacity = strokeProperties.opacity.value.cgFloatValue
strokeRender.gradientRender.colors = strokeProperties.colors.value.map { CGFloat($0) }
strokeRender.gradientRender.type = strokeProperties.gradientType
strokeRender.gradientRender.numberOfColors = strokeProperties.numberOfColors
/// Now update stroke properties
strokeRender.strokeRender.opacity = strokeProperties.opacity.value.cgFloatValue
strokeRender.strokeRender.width = strokeProperties.width.value.cgFloatValue
strokeRender.strokeRender.miterLimit = strokeProperties.miterLimit
strokeRender.strokeRender.lineCap = strokeProperties.lineCap
strokeRender.strokeRender.lineJoin = strokeProperties.lineJoin
/// Get dash lengths
let dashLengths = strokeProperties.dashPattern.value.map { $0.cgFloatValue }
if dashLengths.count > 0, dashLengths.isSupportedLayerDashPattern {
strokeRender.strokeRender.dashPhase = strokeProperties.dashPhase.value.cgFloatValue
strokeRender.strokeRender.dashLengths = dashLengths
} else {
strokeRender.strokeRender.dashLengths = nil
strokeRender.strokeRender.dashPhase = nil
}
}
}
| apache-2.0 | 82fea18216eb2223ce722849c2034ccb | 32.927152 | 109 | 0.754441 | 5.303313 | false | false | false | false |
mackoj/iosMobileDeviceManager | MDM/Models.swift | 1 | 1545 | //
// Models.swift
// MDM
//
// Created by Jeffrey Macko on 11/09/15.
// Copyright © 2015 PagesJaunes. All rights reserved.
//
import Foundation
import Parse
class PJUser : PFObject {
func login() -> String {
return self.objectForKey("login") as! String
}
func mail() -> String {
return self.objectForKey("mail") as! String
}
}
class BorrowedDevice : PFObject {
func model() -> String {
return self.objectForKey("model") as! String
}
func type__() -> String {
return self.objectForKey("type") as! String
}
func userId() -> String {
return self.objectForKey("userId") as! String
}
func user() -> PJUser {
let tUser : PJUser = self.objectForKey("userId") as! PJUser
if tUser.isDataAvailable() == false {
tUser.fetch()
}
return tUser
}
func installationId() -> String {
return self.objectForKey("installationId") as! String
}
func installation() -> PFInstallation {
let installation : PFInstallation = self.objectForKey("installationId") as! PFInstallation
if installation.isDataAvailable() == false {
installation.fetch()
}
return installation
}
func manufacturer() -> String {
return self.objectForKey("manufacturer") as! String
}
func systemName() -> String {
return self.objectForKey("systemName") as! String
}
func systemVersion() -> String {
return self.objectForKey("systemVersion") as! String
}
func broken() -> Bool {
return self.objectForKey("broken") as! Bool
}
}
| gpl-2.0 | 781a0701472c8bad1fe6903f811c89cf | 19.586667 | 95 | 0.641839 | 4.172973 | false | false | false | false |
alblue/swift | stdlib/public/core/StringGutsVisitor.swift | 7 | 520 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 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
//
//===----------------------------------------------------------------------===//
| apache-2.0 | ecf98445b63dbda678bd5d72f447f749 | 42.333333 | 80 | 0.511538 | 5.652174 | false | false | false | false |
zyrx/eidolon | Kiosk/App/Networking/APIKeys.swift | 6 | 949 | import Foundation
import Keys
private let minimumKeyLength = 2
// Mark: - API Keys
struct APIKeys {
let key: String
let secret: String
// MARK: Shared Keys
private struct SharedKeys {
static var instance = APIKeys()
}
static var sharedKeys: APIKeys {
get {
return SharedKeys.instance
}
set (newSharedKeys) {
SharedKeys.instance = newSharedKeys
}
}
// MARK: Methods
var stubResponses: Bool {
return key.characters.count < minimumKeyLength || secret.characters.count < minimumKeyLength
}
// MARK: Initializers
init(key: String, secret: String) {
self.key = key
self.secret = secret
}
init(keys: EidolonKeys) {
self.init(key: keys.artsyAPIClientKey() ?? "", secret: keys.artsyAPIClientSecret() ?? "")
}
init() {
let keys = EidolonKeys()
self.init(keys: keys)
}
}
| mit | fcf4d2009a84fb46f559baf93ed04868 | 18.367347 | 100 | 0.589041 | 4.255605 | false | false | false | false |
joninsky/JVUtilities | JVUtilities/FlowerMenu.swift | 1 | 16512 | //
// FlowerMenu.swift
// JVUtilities
//
// Created by Jon Vogel on 4/22/16.
// Copyright © 2016 Jon Vogel. All rights reserved.
//
import UIKit
public protocol FlowerMenuDelegate {
func flowerMenuDidSelectPedalWithID(theMenu: FlowerMenu, identifier: String, pedal: UIView)
func flowerMenuDidExpand()
func flowerMenuDidRetract()
}
public enum Position {
case UpperRight
case UpperLeft
case LowerRight
case LowerLeft
case Center
}
public class FlowerMenu: UIImageView {
//MARK: Public Variables
public var centerView: UIView!
public var pedals: [UIView] = [UIView]()
public var pedalSize: CGFloat!
public var pedalDistance: CGFloat = 100
public var pedalSpace: CGFloat = 50
public var startAngle: CGFloat!
public var growthDuration: NSTimeInterval = 0.4
public var stagger: NSTimeInterval = 0.06
public var menuIsExpanded: Bool = false
public var delegate: FlowerMenuDelegate?
public var showPedalLabels = false
public var currentPosition: Position! {
willSet(value) {
self.previousPosition = self.currentPosition
}
didSet{
self.constrainToPosition(self.currentPosition, animate: true)
}
}
//MARK: Private Variables
var pedalIDs: [String: UIView] = [String: UIView]()
var positionView: UIView!
var previousPosition: Position?
var arrayOfConstraints: [NSLayoutConstraint] = [NSLayoutConstraint]()
lazy var focusView = UIView()
//var theSuperView: UIView!
//MARK: Init functions
public init(withPosition: Position, andSuperView view: UIView, andImage: UIImage?){
super.init(image: andImage)
self.translatesAutoresizingMaskIntoConstraints = false
self.userInteractionEnabled = true
view.addSubview(self)
self.constrainToPosition(withPosition, animate: false)
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(FlowerMenu.didTapCenterView(_:)))
self.addGestureRecognizer(tapGesture)
self.currentPosition = withPosition
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
//MARK: Public functions
public func addPedal(theImage: UIImage, identifier: String){
let newPedal = self.createAndConstrainPedal(theImage, name: identifier)
self.addSubview(newPedal)
self.constrainPedalToSelf(newPedal)
self.pedals.append(newPedal)
self.pedalIDs[identifier] = newPedal
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(FlowerMenu.didTapPopOutView(_:)))
newPedal.addGestureRecognizer(tapGesture)
let panGesture = UIPanGestureRecognizer(target: self, action: #selector(FlowerMenu.pannedViews(_:)))
newPedal.addGestureRecognizer(panGesture)
newPedal.alpha = 0
}
public func selectPedalWithID(identifier: String) {
for key in self.pedalIDs.keys {
if key == identifier {
guard let view = self.pedalIDs[key] else{
return
}
self.delegate?.flowerMenuDidSelectPedalWithID(self, identifier: key, pedal: view)
}
}
}
public func getPedalFromIdentifier(identifier: String) -> UIView {
return UIView()
}
public override func pointInside(point: CGPoint, withEvent event: UIEvent?) -> Bool {
if CGRectContainsPoint(self.bounds, point) {
return true
}
for view in self.pedals {
if CGRectContainsPoint(view.frame, point) {
return true
}
}
return false
}
public func grow(){
for (index, view) in self.pedals.enumerate() {
let indexAsDouble = Double(index)
UIView.animateWithDuration(self.growthDuration, delay: self.stagger * indexAsDouble, usingSpringWithDamping: 0.7, initialSpringVelocity: 0.4, options: UIViewAnimationOptions.AllowUserInteraction, animations: {
view.alpha = 1
view.transform = self.getTransformForPopupViewAtIndex(CGFloat(index))
}, completion: { (didComplete) in
self.delegate?.flowerMenuDidExpand()
})
}
self.menuIsExpanded = true
// self.currentPosition = .Center
for c in self.arrayOfConstraints {
c.constant += 100
}
self.setNeedsLayout()
UIView.animateWithDuration(0.2) {
self.layoutIfNeeded()
}
self.focusView.frame = self.superview!.frame
self.focusView.alpha = 0.5
self.focusView.backgroundColor = UIColor.blackColor()
self.superview?.insertSubview(self.focusView, belowSubview: self)
}
public func shrivel(){
for (index, view) in self.pedals.enumerate() {
let indexAsDouble = Double(index)
UIView.animateWithDuration(self.growthDuration, delay: self.stagger * indexAsDouble, usingSpringWithDamping: 0.7, initialSpringVelocity: 0.4, options: UIViewAnimationOptions.AllowUserInteraction, animations: {
view.alpha = 0
view.transform = CGAffineTransformIdentity
}, completion: { (didComplete) in
self.delegate?.flowerMenuDidRetract()
})
}
self.menuIsExpanded = false
// if self.previousPosition != nil {
// self.currentPosition = previousPosition
// self.previousPosition = nil
// }
for c in self.arrayOfConstraints {
c.constant -= 100
}
self.setNeedsLayout()
UIView.animateWithDuration(0.2) {
self.layoutIfNeeded()
}
self.focusView.removeFromSuperview()
}
internal func didTapPopOutView(sender: UITapGestureRecognizer) {
for key in self.pedalIDs.keys {
guard let view = self.pedalIDs[key] else{
break
}
if view == sender.view {
self.delegate?.flowerMenuDidSelectPedalWithID(self, identifier: key, pedal: view)
}
}
}
internal func didTapCenterView(sender: UITapGestureRecognizer){
if self.menuIsExpanded {
self.shrivel()
//self.currentPosition = .UpperRight
}else{
self.grow()
//self.currentPosition = .Center
}
}
internal func pannedViews(sender: UIPanGestureRecognizer) {
guard let theView = sender.view else {
return
}
var indexOfView: Int?
for (index, view) in self.pedals.enumerate() {
if view == theView{
indexOfView = index
break
}
}
let point = sender.locationInView(self)
let centerX = self.bounds.origin.x + self.bounds.size.width / 2
let centerY = self.bounds.origin.y + self.bounds.size.height / 2
if sender.state == UIGestureRecognizerState.Changed {
let deltaX = point.x - centerX
let deltaY = point.y - centerY
let atan = Double(atan2(deltaX, -deltaY))
let angle = atan * Double(180) / M_PI
//self.pedalDistance = sqrt(pow(point.x - centerX, 2) + pow(point.y - centerY, 2))
self.startAngle = CGFloat(angle) - self.pedalSpace * CGFloat(indexOfView!)
theView.center = point
theView.transform = CGAffineTransformIdentity
for (index, aView) in self.pedals.enumerate() {
if aView != theView {
aView.transform = self.getTransformForPopupViewAtIndex(CGFloat(index))
}
}
}else if sender.state == UIGestureRecognizerState.Ended {
theView.center = CGPointMake(centerX, centerY)
for (index, aView) in self.pedals.enumerate() {
aView.transform = self.getTransformForPopupViewAtIndex(CGFloat(index))
}
}
}
internal func getTransformForPopupViewAtIndex(index: CGFloat) -> CGAffineTransform{
let newAngle = Double(self.startAngle + (self.pedalSpace * index))
let deltaY = Double(-self.pedalDistance) * cos(newAngle / 180 * M_PI)
let deltaX = Double(self.pedalDistance) * sin(newAngle / 180 * M_PI)
return CGAffineTransformMakeTranslation(CGFloat(deltaX), CGFloat(deltaY))
}
private func createAndConstrainPedal(image: UIImage, name: String) -> UIView {
let newPedal = UIView()
let pedalImage = UIImageView(image: image)
let pedalLabel = UILabel()
newPedal.translatesAutoresizingMaskIntoConstraints = false
pedalImage.translatesAutoresizingMaskIntoConstraints = false
newPedal.userInteractionEnabled = true
pedalLabel.userInteractionEnabled = true
pedalImage.userInteractionEnabled = true
pedalLabel.translatesAutoresizingMaskIntoConstraints = false
pedalLabel.numberOfLines = 1
if self.showPedalLabels == false {
pedalLabel.text = name
pedalLabel.hidden = true
}
pedalLabel.text = name
pedalLabel.adjustsFontSizeToFitWidth = true
newPedal.addSubview(pedalImage)
newPedal.addSubview(pedalLabel)
let dictionaryOfViews = ["image": pedalImage, "label": pedalLabel]
self.constrainPedal(newPedal, pedalSubViews: dictionaryOfViews)
return newPedal
}
//MARK: Constraint Adding
func constrainToPosition(thePosition: Position, animate: Bool) {
if self.arrayOfConstraints.count > 0 {
self.superview?.removeConstraints(self.arrayOfConstraints)
self.arrayOfConstraints.removeAll()
}
switch thePosition {
case .Center:
let verticalConstraint = NSLayoutConstraint(item: self, attribute: NSLayoutAttribute.CenterY, relatedBy: NSLayoutRelation.Equal, toItem: self.superview, attribute: NSLayoutAttribute.CenterY, multiplier: 1.0, constant: 0)
let horizontalConstraint = NSLayoutConstraint(item: self, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: self.superview, attribute: NSLayoutAttribute.CenterX, multiplier: 1.0, constant: 0)
self.arrayOfConstraints.append(verticalConstraint)
self.arrayOfConstraints.append(horizontalConstraint)
self.startAngle = 0
print("Constrain To Center")
case .LowerLeft:
let horizontalConstraints = NSLayoutConstraint.constraintsWithVisualFormat("H:|-28-[me]", options: [], metrics: nil, views: ["me": self])
let verticalConstraints = NSLayoutConstraint.constraintsWithVisualFormat("V:[me]-28-|", options: [], metrics: nil, views: ["me":self])
self.arrayOfConstraints.appendContentsOf(horizontalConstraints)
self.arrayOfConstraints.appendContentsOf(verticalConstraints)
self.startAngle = 10
print("Constrain To Lower Left")
case .LowerRight:
let horizontalConstraints = NSLayoutConstraint.constraintsWithVisualFormat("H:[me]-28-|", options: [], metrics: nil, views: ["me": self])
let verticalConstraints = NSLayoutConstraint.constraintsWithVisualFormat("V:[me]-28-|", options: [], metrics: nil, views: ["me":self])
self.arrayOfConstraints.appendContentsOf(horizontalConstraints)
self.arrayOfConstraints.appendContentsOf(verticalConstraints)
self.startAngle = -80
print("Constrain To Lower Right")
case .UpperLeft:
if self.superview is UINavigationBar {
let horizontalConstraints = NSLayoutConstraint.constraintsWithVisualFormat("H:|[me]", options: [], metrics: nil, views: ["me": self])
let verticalConstraints = NSLayoutConstraint.constraintsWithVisualFormat("V:|[me]", options: [], metrics: nil, views: ["me":self])
self.arrayOfConstraints.appendContentsOf(horizontalConstraints)
self.arrayOfConstraints.appendContentsOf(verticalConstraints)
}else{
let horizontalConstraints = NSLayoutConstraint.constraintsWithVisualFormat("H:|-10-[me]", options: [], metrics: nil, views: ["me": self])
let verticalConstraints = NSLayoutConstraint.constraintsWithVisualFormat("V:|-20-[me]", options: [], metrics: nil, views: ["me":self])
self.arrayOfConstraints.appendContentsOf(horizontalConstraints)
self.arrayOfConstraints.appendContentsOf(verticalConstraints)
}
print("Constrain To Upper Left")
self.startAngle = 100
case .UpperRight:
let horizontalConstraints = NSLayoutConstraint.constraintsWithVisualFormat("H:[me]-10-|", options: [], metrics: nil, views: ["me": self])
let verticalConstraints = NSLayoutConstraint.constraintsWithVisualFormat("V:|-20-[me]", options: [], metrics: nil, views: ["me":self])
self.arrayOfConstraints.appendContentsOf(horizontalConstraints)
self.arrayOfConstraints.appendContentsOf(verticalConstraints)
self.startAngle = 170
print("Constrain To Upper Right")
}
self.superview?.addConstraints(self.arrayOfConstraints)
self.setNeedsLayout()
if animate {
UIView.animateWithDuration(0.5) {
self.layoutIfNeeded()
}
}else{
self.layoutIfNeeded()
}
}
private func constrainPedal(thePedal: UIView, pedalSubViews: [String: AnyObject]){
var arrayOfConstraint = [NSLayoutConstraint]()
let imageLabelVertical = NSLayoutConstraint.constraintsWithVisualFormat("V:|[image][label]|", options: [], metrics: nil, views: pedalSubViews)
let imageHorizontal = NSLayoutConstraint.constraintsWithVisualFormat("H:|-(>=0)-[image]-(>=0)-|", options: [], metrics: nil, views: pedalSubViews)
guard let theImage = pedalSubViews["image"] as? UIImageView, let label = pedalSubViews["label"] as? UILabel else {
return
}
if self.showPedalLabels == false {
let labeHeight = NSLayoutConstraint(item: label, attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.Height, multiplier: 1.0, constant: 0)
arrayOfConstraint.append(labeHeight)
}
let moreImageHorizontal = NSLayoutConstraint(item: theImage, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: thePedal, attribute: NSLayoutAttribute.CenterX, multiplier: 1.0, constant: 0)
let labelHorizontal = NSLayoutConstraint.constraintsWithVisualFormat("H:|[label]|", options: [], metrics: nil, views: pedalSubViews)
arrayOfConstraint.appendContentsOf(imageLabelVertical)
arrayOfConstraint.appendContentsOf(imageHorizontal)
arrayOfConstraint.append(moreImageHorizontal)
arrayOfConstraint.appendContentsOf(labelHorizontal)
thePedal.addConstraints(arrayOfConstraint)
}
private func constrainPedalToSelf(thePedal: UIView) {
var arrayOfConstraints = [NSLayoutConstraint]()
let centerX = NSLayoutConstraint(item: thePedal, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.CenterX, multiplier: 1.0, constant: 0)
let centerY = NSLayoutConstraint(item: thePedal, attribute: NSLayoutAttribute.CenterY, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.CenterY, multiplier: 1.0, constant: 0)
arrayOfConstraints.append(centerX)
arrayOfConstraints.append(centerY)
self.addConstraints(arrayOfConstraints)
}
}
| mit | 825ad8b2b8599a2b6691bcf0601a622e | 39.767901 | 234 | 0.629035 | 5.429464 | false | false | false | false |
wireapp/wire-ios | Wire-iOS Tests/Notification Service Extension/LegacyNotificationServiceTest.swift | 1 | 7027 | //
// Wire
// Copyright (C) 2022 Wire Swiss GmbH
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
import Foundation
import XCTest
import Wire_Notification_Service_Extension
final class LegacyNotificationServiceTests: XCTestCase {
var sut: LegacyNotificationService!
var request: UNNotificationRequest!
var notificationContent: UNNotificationContent!
var contentResult: UNNotificationContent?
var coreDataFixture: CoreDataFixture!
var mockConversation: ZMConversation!
var currentUserIdentifier: UUID!
var callEventHandlerMock: CallEventHandlerMock!
var otherUser: ZMUser! {
return coreDataFixture.otherUser
}
var selfUser: ZMUser! {
return coreDataFixture.selfUser
}
var client: UserClient! {
coreDataFixture.mockUserClient()
}
override func setUp() {
super.setUp()
sut = LegacyNotificationService()
callEventHandlerMock = CallEventHandlerMock()
currentUserIdentifier = UUID.create()
notificationContent = createNotificationContent()
request = UNNotificationRequest(identifier: currentUserIdentifier.uuidString,
content: notificationContent,
trigger: nil)
coreDataFixture = CoreDataFixture()
mockConversation = createTeamGroupConversation()
client.user = otherUser
createAccount(with: currentUserIdentifier)
sut.didReceive(request, withContentHandler: contentHandlerMock)
sut.callEventHandler = callEventHandlerMock
}
override func tearDown() {
callEventHandlerMock = nil
sut = nil
notificationContent = nil
request = nil
contentResult = nil
coreDataFixture = nil
currentUserIdentifier = nil
mockConversation = nil
super.tearDown()
}
func testThatItHandlesGeneratedNotification() {
// GIVEN
let unreadConversationCount = 5
let note = textNotification(mockConversation, sender: otherUser)
// WHEN
XCTAssertNotEqual(note?.content, contentResult)
sut.notificationSessionDidGenerateNotification(note, unreadConversationCount: unreadConversationCount)
// THEN
let content = try? XCTUnwrap(note?.content)
XCTAssertEqual(content, contentResult)
XCTAssertEqual(content?.badge?.intValue, unreadConversationCount)
}
func testThatItReportsCallEvent() {
// GIVEN
let event = createEvent()
// WHEN
XCTAssertFalse(callEventHandlerMock.reportIncomingVoIPCallCalled)
sut.reportCallEvent(event, currentTimestamp: Date().timeIntervalSince1970)
// THEN
XCTAssertTrue(callEventHandlerMock.reportIncomingVoIPCallCalled)
}
func testThatItDoesNotReportCallEventForNonCallEvent() {
// GIVEN
let genericMessage = GenericMessage(content: Text(content: "Hello Hello!", linkPreviews: []),
nonce: UUID.create())
let payload: [String: Any] = [
"id": UUID.create().transportString(),
"conversation": mockConversation.remoteIdentifier!.transportString(),
"from": otherUser.remoteIdentifier.transportString(),
"time": Date().transportString(),
"data": ["text": try? genericMessage.serializedData().base64String()],
"type": "conversation.otr-message-add"
]
let event = ZMUpdateEvent(fromEventStreamPayload: payload as ZMTransportData, uuid: UUID.create())!
// WHEN
XCTAssertFalse(callEventHandlerMock.reportIncomingVoIPCallCalled)
sut.reportCallEvent(event, currentTimestamp: Date().timeIntervalSince1970)
// THEN
XCTAssertFalse(callEventHandlerMock.reportIncomingVoIPCallCalled)
}
}
// MARK: - Helpers
extension LegacyNotificationServiceTests {
private func createAccount(with id: UUID) {
guard let sharedContainer = Bundle.main.appGroupIdentifier.map(FileManager.sharedContainerDirectory) else {
XCTFail("There's no sharedContainer")
fatalError()
}
let manager = AccountManager(sharedDirectory: sharedContainer)
let account = Account(userName: "Test Account", userIdentifier: id)
manager.addOrUpdate(account)
}
private func createNotificationContent() -> UNMutableNotificationContent {
let content = UNMutableNotificationContent()
content.body = "body"
content.title = "title"
let storage = ["data": ["user": currentUserIdentifier.uuidString]]
let userInfo = NotificationUserInfo(storage: storage)
content.userInfo = userInfo.storage
return content
}
private func textNotification(_ conversation: ZMConversation, sender: ZMUser) -> ZMLocalNotification? {
let event = createEvent()
return ZMLocalNotification(event: event, conversation: conversation, managedObjectContext: coreDataFixture.uiMOC)
}
private func createEvent() -> ZMUpdateEvent {
let genericMessage = GenericMessage(content: Text(content: "Hello Hello!", linkPreviews: []),
nonce: UUID.create())
let payload: [String: Any] = [
"id": UUID.create().transportString(),
"conversation": mockConversation.remoteIdentifier!.transportString(),
"from": otherUser.remoteIdentifier.transportString(),
"time": Date().transportString(),
"data": ["text": try? genericMessage.serializedData().base64String(),
"sender": otherUser.clients.first?.remoteIdentifier],
"type": "conversation.otr-message-add"
]
return ZMUpdateEvent(fromEventStreamPayload: payload as ZMTransportData, uuid: UUID.create())!
}
private func createTeamGroupConversation() -> ZMConversation {
return ZMConversation.createTeamGroupConversation(moc: coreDataFixture.uiMOC, otherUser: otherUser, selfUser: selfUser)
}
private func contentHandlerMock(_ content: UNNotificationContent) {
contentResult = content
}
}
class CallEventHandlerMock: CallEventHandlerProtocol {
var reportIncomingVoIPCallCalled: Bool = false
func reportIncomingVoIPCall(_ payload: [String: Any]) {
reportIncomingVoIPCallCalled = true
}
}
| gpl-3.0 | f9cd86c95492274548dd1961c6fbdf32 | 34.135 | 127 | 0.676391 | 5.708367 | false | false | false | false |
cismet/belis-app | belis-app/LeuchteActionForms.swift | 1 | 16161 |
//
// LeuchteActionForms.swift
// belis-app
//
// Created by Thorsten Hell on 12.11.15.
// Copyright © 2015 cismet. All rights reserved.
//
import Foundation
import SwiftForms
class LeuchtenerneuerungAction : ObjectAction {
enum PT:String {
case INBETRIEBNAHMEDATUM
case LEUCHTENTYP
}
override init(){
super.init()
title="Leuchtenerneuerung"
}
override func getFormDescriptor()->FormDescriptor {
let form = FormDescriptor()
form.title = "Leuchtenerneuerung"
let section0 = FormSectionDescriptor(headerTitle: nil, footerTitle: nil)
var row = FormRowDescriptor(tag: PT.INBETRIEBNAHMEDATUM.rawValue, type: .date, title: "Inbetriebnahme")
row.value=Date() as AnyObject?
//section0.headerTitle = "Informationen zu den durchgeführten Tätigkeiten"
section0.rows.append(row)
row = FormRowDescriptor(tag: PT.LEUCHTENTYP.rawValue, type: .picker, title: "Leuchtentyp")
row.configuration.selection.options = CidsConnector.sharedInstance().sortedLeuchtenTypListKeys as [AnyObject]
row.configuration.selection.optionTitleClosure = { value in
let typ=CidsConnector.sharedInstance().leuchtentypList[value as! String]
return "\(typ?.leuchtenTyp ?? "unbekannter Typ") - \(typ?.fabrikat ?? "unbekanntes Fabrikat")"
}
section0.rows.append(row)
form.sections = [section0]
form.sections.append(contentsOf: getStatusManagingSections())
return form
}
// EUREKA Form Syntax
// func getForm()->Form {
// return Form()
// +++ Section()
// <<< DateRow(){
// $0.title = "Inbetriebnahme"
// $0.value = Date(timeIntervalSinceReferenceDate: 0)
// }
// //Better Picker Support when #808 is merged in
// <<< PushRow<String>("Leuchtentyp") {
// $0.title = $0.tag
// $0.options = ["A","B","C","D"]
// $0.value = "A"
// }.onPresent({ (_, vc) in
// vc.enableDeselection = false
// })
// }
//
override func getPreferredSize()->CGSize {
return CGSize(width: 500, height: 100 + statusManagingSectionsHeight)
}
override func save(){
if arbeitsprotokoll_id != -1 {
let content = formVC.form.formValues()
showWaiting()
let apc=getParameterContainer()
let date=content[PT.INBETRIEBNAHMEDATUM.rawValue]!
let nowDouble = date.timeIntervalSince1970
let millis = Int64(nowDouble!*1000) + Int64(nowDouble!/1000)
let param = "\(millis)"
apc.append(PT.INBETRIEBNAHMEDATUM.rawValue, value: param as AnyObject)
if let x=content[PT.LEUCHTENTYP.rawValue] {
apc.append(PT.LEUCHTENTYP.rawValue, value: x)
}
saveStatus(apc:apc)
CidsConnector.sharedInstance().executeSimpleServerAction(actionName: "ProtokollLeuchteLeuchtenerneuerung", params: apc, handler: defaultAfterSaveHandler)
}
}
}
class LeuchtmittelwechselEPAction : ObjectAction {
enum PT:String {
case WECHSELDATUM
case LEBENSDAUER
case LEUCHTMITTEL
case PRUEFDATUM
case ERDUNG_IN_ORDNUNG
}
override init(){
super.init()
title="Leuchtmittelwechsel (mit EP)"
}
override func getFormDescriptor()->FormDescriptor {
let form = FormDescriptor()
form.title = "Leuchtmittelwechsel (mit EP)"
let section0 = FormSectionDescriptor(headerTitle: nil, footerTitle: nil)
var row = FormRowDescriptor(tag: PT.PRUEFDATUM.rawValue, type: .date, title: "Elektrische Prüfung am Mast")
row.value=Date() as AnyObject?
section0.rows.append(row)
row = FormRowDescriptor(tag: PT.ERDUNG_IN_ORDNUNG.rawValue, type: .booleanSwitch, title: "Erdung in Ordnung")
section0.rows.append(row)
row = FormRowDescriptor(tag: PT.WECHSELDATUM.rawValue, type: .date, title: "Wechseldatum")
row.value=Date() as AnyObject?
section0.rows.append(row)
row = FormRowDescriptor(tag: PT.LEUCHTMITTEL.rawValue, type: .picker, title: "eingesetztes Leuchtmittel")
row.configuration.selection.options=CidsConnector.sharedInstance().sortedLeuchtmittelListKeys as [AnyObject]
row.configuration.selection.optionTitleClosure = { value in
let lm=CidsConnector.sharedInstance().leuchtmittelList[value as! String]
return "\(lm?.hersteller ?? "ohne Hersteller") - \(lm?.lichtfarbe ?? "")"
}
section0.rows.append(row)
row = FormRowDescriptor(tag: PT.LEBENSDAUER.rawValue, type: .name, title: "Lebensdauer des Leuchtmittels")
row.configuration.cell.appearance = ["textField.placeholder" : "in Monaten" as AnyObject, "textField.textAlignment" : NSTextAlignment.right.rawValue as AnyObject]
section0.rows.append(row)
form.sections = [section0]
form.sections.append(contentsOf: getStatusManagingSections())
return form
}
override func getPreferredSize()->CGSize {
return CGSize(width: 500, height: 250 + statusManagingSectionsHeight)
}
override func save(){
if arbeitsprotokoll_id != -1 {
let content = formVC.form.formValues()
showWaiting()
let apc=getParameterContainer()
let datepd=content[PT.PRUEFDATUM.rawValue]!
let nowDoublepd = datepd.timeIntervalSince1970
let millispd = Int64(nowDoublepd!*1000) + Int64(nowDoublepd!/1000)
let parampd = "\(millispd)"
apc.append(PT.PRUEFDATUM.rawValue, value: parampd as AnyObject)
//------------------
var erdung=""
if let erdInOrdnung=content[PT.ERDUNG_IN_ORDNUNG.rawValue] as? Bool{
if erdInOrdnung{
erdung="ja"
}
else {
erdung="nein"
}
}
else {
erdung="nein"
}
apc.append(PT.ERDUNG_IN_ORDNUNG.rawValue, value: erdung as AnyObject)
//------------------
let datewd=content[PT.WECHSELDATUM.rawValue]!
let nowDoublewd = datewd.timeIntervalSince1970
let milliswd = Int64(nowDoublewd!*1000) + Int64(nowDoublewd!/1000)
let paramwd = "\(milliswd)"
apc.append(PT.WECHSELDATUM.rawValue, value: paramwd as AnyObject)
//------------------
if let lid=content[PT.LEUCHTMITTEL.rawValue] {
apc.append(PT.LEUCHTMITTEL.rawValue, value: lid)
}
//------------------
if let lebensdauer=content[PT.LEBENSDAUER.rawValue] {
apc.append(PT.LEBENSDAUER.rawValue, value: lebensdauer)
}
saveStatus(apc:apc)
CidsConnector.sharedInstance().executeSimpleServerAction(actionName: "ProtokollLeuchteLeuchtmittelwechselElekpruefung", params: apc, handler: defaultAfterSaveHandler)
}
}
}
class LeuchtmittelwechselAction : ObjectAction {
enum PT:String {
case WECHSELDATUM
case LEBENSDAUER
case LEUCHTMITTEL
}
override init(){
super.init()
title="Leuchtmittelwechsel"
}
override func getFormDescriptor()->FormDescriptor {
let form = FormDescriptor()
form.title = "Leuchtmittelwechsel"
let section0 = FormSectionDescriptor(headerTitle: nil, footerTitle: nil)
var row = FormRowDescriptor(tag: PT.WECHSELDATUM.rawValue, type: .date, title: "Wechseldatum")
row.value=Date() as AnyObject?
section0.rows.append(row)
row = FormRowDescriptor(tag: PT.LEUCHTMITTEL.rawValue, type: .picker, title: "eingesetztes Leuchtmittel")
row.configuration.selection.options = CidsConnector.sharedInstance().sortedLeuchtmittelListKeys as [AnyObject]
row.configuration.selection.optionTitleClosure = { value in
let lm=CidsConnector.sharedInstance().leuchtmittelList[value as! String]
return "\(lm?.hersteller ?? "ohne Hersteller") - \(lm?.lichtfarbe ?? "")"
}
section0.rows.append(row)
row = FormRowDescriptor(tag: PT.LEBENSDAUER.rawValue, type: .name, title: "Lebensdauer des Leuchtmittels")
row.configuration.cell.appearance = ["textField.placeholder" : "in Monaten" as AnyObject, "textField.textAlignment" : NSTextAlignment.right.rawValue as AnyObject]
section0.rows.append(row)
form.sections = [section0]
form.sections.append(contentsOf: getStatusManagingSections())
return form
}
override func getPreferredSize()->CGSize {
return CGSize(width: 500, height: 150 + statusManagingSectionsHeight)
}
override func save(){
if arbeitsprotokoll_id != -1 {
let content = formVC.form.formValues()
showWaiting()
let apc=getParameterContainer()
let datewd=content[PT.WECHSELDATUM.rawValue]!
let nowDoublewd = datewd.timeIntervalSince1970
let milliswd = Int64(nowDoublewd!*1000) + Int64(nowDoublewd!/1000)
let paramwd = "\(milliswd)"
apc.append(PT.WECHSELDATUM.rawValue, value: paramwd as AnyObject)
//------------------
if let lid=content[PT.LEUCHTMITTEL.rawValue] {
apc.append(PT.LEUCHTMITTEL.rawValue, value: lid)
}
//------------------
if let lebensdauer=content[PT.LEBENSDAUER.rawValue] {
apc.append(PT.LEBENSDAUER.rawValue, value: lebensdauer)
}
saveStatus(apc:apc)
CidsConnector.sharedInstance().executeSimpleServerAction(actionName: "ProtokollLeuchteLeuchtmittelwechsel", params: apc, handler: defaultAfterSaveHandler)
}
}
}
class RundsteuerempfaengerwechselAction : ObjectAction {
enum PT:String {
case EINBAUDATUM
case RUNDSTEUEREMPFAENGER
}
override init(){
super.init()
title="Rundsteuerempfängerwechsel"
}
override func getFormDescriptor()->FormDescriptor {
let form = FormDescriptor()
form.title = "Rundsteuerempfängerwechsel"
let section0 = FormSectionDescriptor(headerTitle: nil, footerTitle: nil)
var row = FormRowDescriptor(tag: PT.EINBAUDATUM.rawValue, type: .date, title: "Einbaudatum")
row.value=Date() as AnyObject?
section0.rows.append(row)
row = FormRowDescriptor(tag: PT.RUNDSTEUEREMPFAENGER.rawValue, type: .picker, title: "Rundsteuerempfänger")
row.configuration.selection.options = CidsConnector.sharedInstance().sortedRundsteuerempfaengerListKeys as [AnyObject]
row.configuration.selection.optionTitleClosure = { value in
let rse=CidsConnector.sharedInstance().rundsteuerempfaengerList[value as! String]
return"\(rse?.herrsteller_rs ?? "ohne Hersteller") - \(rse?.rs_typ ?? "")"
}
section0.rows.append(row)
form.sections = [section0]
form.sections.append(contentsOf: getStatusManagingSections())
return form
}
override func getPreferredSize()->CGSize {
return CGSize(width: 500, height: 100 + statusManagingSectionsHeight)
}
override func save(){
if arbeitsprotokoll_id != -1 {
let content = formVC.form.formValues()
showWaiting()
let apc=getParameterContainer()
let datewd=content[PT.EINBAUDATUM.rawValue]!
let nowDoublewd = datewd.timeIntervalSince1970
let milliswd = Int64(nowDoublewd!*1000) + Int64(nowDoublewd!/1000)
let paramwd = "\(milliswd)"
apc.append(PT.EINBAUDATUM.rawValue, value: paramwd as AnyObject)
//------------------
if let rid=content[PT.RUNDSTEUEREMPFAENGER.rawValue]{
apc.append(PT.RUNDSTEUEREMPFAENGER.rawValue, value: rid)
}
saveStatus(apc:apc)
CidsConnector.sharedInstance().executeSimpleServerAction(actionName: "ProtokollLeuchteRundsteuerempfaengerwechsel", params: apc, handler: defaultAfterSaveHandler)
}
}
}
class SonderturnusAction : ObjectAction {
enum PT:String {
case DATUM
}
override init(){
super.init()
title="Sonderturnus"
}
override func getFormDescriptor()->FormDescriptor {
let form = FormDescriptor()
form.title = "Sonderturnus"
let section0 = FormSectionDescriptor(headerTitle: nil, footerTitle: nil)
let row = FormRowDescriptor(tag: PT.DATUM.rawValue, type: .date, title: "Sonderturnus")
row.value=Date() as AnyObject?
section0.rows.append(row)
form.sections = [section0]
form.sections.append(contentsOf: getStatusManagingSections())
return form
}
override func getPreferredSize()->CGSize {
return CGSize(width: 500, height: 60 + statusManagingSectionsHeight)
}
override func save(){
if arbeitsprotokoll_id != -1 {
let content = formVC.form.formValues()
showWaiting()
let apc=getParameterContainer()
let datewd=content[PT.DATUM.rawValue]!
let nowDoublewd = datewd.timeIntervalSince1970
let milliswd = Int64(nowDoublewd!*1000) + Int64(nowDoublewd!/1000)
let paramwd = "\(milliswd)"
apc.append(PT.DATUM.rawValue, value: paramwd as AnyObject)
saveStatus(apc:apc)
CidsConnector.sharedInstance().executeSimpleServerAction(actionName: "ProtokollLeuchteSonderturnus", params: apc, handler: defaultAfterSaveHandler)
}
}
}
class VorschaltgeraetwechselAction : ObjectAction {
enum PT:String {
case WECHSELDATUM
case VORSCHALTGERAET
}
override init(){
super.init()
title="Vorschaltgerätwechsel"
}
override func getFormDescriptor()->FormDescriptor {
let form = FormDescriptor()
form.title = "Vorschaltgerätwechsel"
let section0 = FormSectionDescriptor(headerTitle: nil, footerTitle: nil)
var row = FormRowDescriptor(tag: PT.WECHSELDATUM.rawValue, type: .date, title: "Einbaudatum")
row.value=Date() as AnyObject?
section0.rows.append(row)
row = FormRowDescriptor(tag: PT.VORSCHALTGERAET.rawValue, type: .name, title: "Vorschaltgerät")
row.configuration.cell.appearance = ["textField.textAlignment" : NSTextAlignment.right.rawValue as AnyObject]
section0.rows.append(row)
form.sections = [section0]
form.sections.append(contentsOf: getStatusManagingSections())
return form
}
override func getPreferredSize()->CGSize {
return CGSize(width: 500, height: 100 + statusManagingSectionsHeight)
}
override func save(){
if arbeitsprotokoll_id != -1 {
let content = formVC.form.formValues()
showWaiting()
let apc=getParameterContainer()
let datewd=content[PT.WECHSELDATUM.rawValue]!
let nowDoublewd = datewd.timeIntervalSince1970
let milliswd = Int64(nowDoublewd!*1000) + Int64(nowDoublewd!/1000)
let paramwd = "\(milliswd)"
apc.append(PT.WECHSELDATUM.rawValue, value: paramwd as AnyObject)
//------------------
if let vid=content[PT.VORSCHALTGERAET.rawValue]{
apc.append(PT.VORSCHALTGERAET.rawValue, value: vid)
}
saveStatus(apc:apc)
CidsConnector.sharedInstance().executeSimpleServerAction(actionName: "ProtokollLeuchteVorschaltgeraetwechsel", params: apc, handler: defaultAfterSaveHandler)
}
}
}
| mit | 042ec328c4534d2559e2b77a4a94832e | 39.076923 | 178 | 0.617795 | 4.64777 | false | false | false | false |
benlangmuir/swift | test/PCMacro/init.swift | 20 | 1453 | // RUN: %empty-directory(%t)
// RUN: cp %s %t/main.swift
// RUN: %target-build-swift -whole-module-optimization -module-name PlaygroundSupport -emit-module-path %t/PlaygroundSupport.swiftmodule -parse-as-library -c -o %t/PlaygroundSupport.o %S/Inputs/PCMacroRuntime.swift %S/Inputs/SilentPlaygroundsRuntime.swift
// RUN: %target-build-swift -Xfrontend -pc-macro -o %t/main -I=%t %t/PlaygroundSupport.o %t/main.swift
// RUN: %target-codesign %t/main
// RUN: %target-run %t/main | %FileCheck %s
// RUN: %target-build-swift -Xfrontend -pc-macro -Xfrontend -playground -Xfrontend -debugger-support -o %t/main2 -I=%t %t/PlaygroundSupport.o %t/main.swift
// RUN: %target-run %t/main | %FileCheck %s
// REQUIRES: executable_test
// XFAIL: *
// FIXME: rdar://problem/30234450 PCMacro tests fail on linux in optimized mode
// UNSUPPORTED: OS=linux-gnu
import PlaygroundSupport
class A {
func access() -> Void {
}
}
class B {
var a : A = A()
init() {
a.access()
}
func mutateIvar() -> Void {
a.access()
}
}
var b = B()
// CHECK: [25:1-25:12] pc before
// this should be logging the init, this is tracked in the init.swift test.
// Once fixed update this test to include it.
// CHECK-NEXT: [17:3-17:9] pc before
// CHECK-NEXT: [17:3-17:9] pc after
// CHECK-NEXT: [18:5-18:15] pc before
// CHECK-NEXT: [11:3-11:24] pc before
// CHECK-NEXT: [11:3-11:24] pc after
// CHECK-NEXT: [18:5-18:15] pc after
// CHECK-NEXT: [25:1-25:12] pc after
| apache-2.0 | 787b2a81d71c5bbc543a13d566bc2d74 | 32.790698 | 255 | 0.678596 | 2.935354 | false | true | false | false |
imex94/KCLTech-iOS-Sessions-2014-2015 | session202/session202/Store.swift | 1 | 777 | //
// Store.swift
// session202
//
// Created by Alex Telek on 09/11/2014.
// Copyright (c) 2014 KCLTech. All rights reserved.
//
import UIKit
class Store {
class func saveData(user: User) {
let userDefaults = NSUserDefaults.standardUserDefaults()
let data = NSKeyedArchiver.archivedDataWithRootObject(user)
userDefaults.setObject(data, forKey: user.username)
userDefaults.synchronize()
}
class func loadData(username: String) -> User? {
let userDefaults = NSUserDefaults.standardUserDefaults()
if let userData = userDefaults.objectForKey(username) as? NSData {
var user = NSKeyedUnarchiver.unarchiveObjectWithData(userData) as! User
return user
}
return nil
}
} | mit | 22716138b1607b487ec13c1d29db2369 | 27.814815 | 83 | 0.664093 | 4.709091 | false | false | false | false |
jngd/advanced-ios10-training | T17E01/T17E01/ViewController.swift | 1 | 3916 | /**
* Copyright (c) 2016 Juan Garcia
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
import UIKit
import EventKit
class ViewController: UIViewController {
/***** Outlets *****/
@IBOutlet weak var calendarNameTextField: UITextField!
@IBOutlet weak var datePicker: UIDatePicker!
@IBOutlet weak var eventTextField: UITextField!
@IBOutlet weak var titleTextField: UITextField!
@IBOutlet weak var recurrencySwitch: UISwitch!
/***** Vars *****/
var eventStore: EKEventStore!
var calendar: EKCalendar!
/***** Actions *****/
@IBAction func saveEvent(_ sender: AnyObject) {
self.eventStore.requestAccess(to: .event) {
(granted, error) -> Void in
guard granted else { fatalError("Permission denied") }
let calendar = self.eventStore.calendar(
withIdentifier: UserDefaults.standard.object(forKey: "calendarIdentifier") as! String)
guard calendar != nil else { fatalError("Calendar not valid") }
let event = EKEvent(eventStore: self.eventStore)
event.title = self.eventTextField.text!
event.startDate = self.datePicker.date
event.endDate =
self.datePicker.date.addingTimeInterval(60*60)
if self.recurrencySwitch.isOn {
event.addRecurrenceRule(EKRecurrenceRule(recurrenceWith: .weekly,
interval: 1, end: nil))
}
event.calendar = calendar!
do{
try self.eventStore.save(event, span: .thisEvent)
let alerta = UIAlertController(title: "Calendar",
message: "Event created \(event.title) in \(calendar!.title)",
preferredStyle: .alert)
alerta.addAction(UIAlertAction(title: "Ok", style: .default, handler: nil))
OperationQueue.main.addOperation(){
self.present(alerta, animated: true,
completion: nil)
}
}catch let error as NSError{
print("An errors occurs saving event \(error.localizedDescription)")
}
}
}
@IBAction func saveCalendar(_ sender: AnyObject) {
self.eventStore.requestAccess(to: .event) {
(granted, error) -> Void in
guard granted else { fatalError("Permission denied") }
let name = self.calendarNameTextField.text
let aux = self.eventStore.sources
let calendar = EKCalendar(for: .event, eventStore: self.eventStore)
calendar.source = aux[0]
calendar.title = name!
print(calendar.calendarIdentifier)
do {
try self.eventStore.saveCalendar(calendar, commit: true)
UserDefaults.standard.set(calendar.calendarIdentifier,
forKey: "calendarIdentifier")
} catch let error as NSError {
print("Error saving calendar: \(error.localizedDescription)")
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
eventStore = EKEventStore()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
// :]
| apache-2.0 | fe136a7da5cd9c4f721b4d99bfc49734 | 30.328 | 97 | 0.693054 | 4.284464 | false | false | false | false |
wufeiyue/FYShareView | FYShareView/ViewController.swift | 1 | 2229 | //
// ViewController.swift
// FYShareView
//
// Created by 武飞跃 on 2017/10/24.
// Copyright © 2017年 wufeiyue.com. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
var shareView: FYShareView!
override func viewDidLoad() {
super.viewDidLoad()
setupBtnView()
setupShareView()
}
//MARK: - 创始化分享视图
func setupShareView() {
let friend = FYShareItemModel(title: "朋友圈", normal: "share_friend", highlighted: "share_friend_hover", id: "friend")
let qq = FYShareItemModel(title: "QQ", normal: "share_qq", highlighted: "share_qq_hover", id: "qq")
let sina = FYShareItemModel(title: "微博", normal: "share_sina", highlighted: "share_sina_hover", id: "sina")
let wechat = FYShareItemModel(title: "微信", normal: "share_weixin", highlighted: "share_weixin_hover", id: "wechat")
let qzone = FYShareItemModel(title: "QQ空间", normal: "share_zone", highlighted: "share_zone_hover", id: "qzone")
shareView = FYShareView(frame: view.bounds, items: [wechat, friend, sina, qq, qzone])
shareView.delegate = self
var style = FYShareStyle()
style.insetHorizontal = 10
style.cancelHeight = 42
shareView.style = style
view.addSubview(shareView)
}
//MARK: - 创建按钮视图
func setupBtnView() {
let btn = UIButton(type: .system)
btn.setTitle("点击", for: .normal)
btn.setTitleColor(UIColor.white, for: .normal)
btn.bounds = CGRect(x: 0, y: 0, width: 100, height: 44)
btn.center = view.center
btn.backgroundColor = UIColor.black
btn.addTarget(self, action: #selector(btnDidTapped), for: .touchUpInside)
view.addSubview(btn)
}
@objc func btnDidTapped() {
shareView.show()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
extension ViewController: FYShareViewDelegate {
func shareView(itemDidTapped identifier: String) {
print("identifier:\(identifier)")
}
}
| mit | 196e17db56375017f96e60bb7c5192bf | 30.941176 | 124 | 0.621087 | 4.044693 | false | false | false | false |
anirudh24seven/wikipedia-ios | Wikipedia/Code/WMFFontSliderContainer.swift | 1 | 1475 | import UIKit
import SWStepSlider
@objc public protocol WMFFontSliderViewControllerDelegate{
func sliderValueChangedInController(controller: WMFFontSliderViewController, value: Int)
}
public class WMFFontSliderViewController: UIViewController {
@IBOutlet private var slider: SWStepSlider!
private var maximumValue: Int?
private var currentValue: Int?
public weak var delegate: WMFFontSliderViewControllerDelegate?
public override func viewDidLoad() {
super.viewDidLoad()
if let max = self.maximumValue {
if let current = self.currentValue {
self.setValues(0, maximum: max, current: current)
self.maximumValue = nil
self.currentValue = nil
}
}
}
public func setValuesWithSteps(steps: Int, current: Int) {
if self.isViewLoaded() {
self.setValues(0, maximum: steps-1, current: current)
}else{
maximumValue = steps-1
currentValue = current
}
}
func setValues(minimum: Int, maximum: Int, current: Int){
self.slider.minimumValue = minimum
self.slider.maximumValue = maximum
self.slider.value = current
}
@IBAction func fontSliderValueChanged(slider: SWStepSlider) {
if let delegate = self.delegate {
delegate.sliderValueChangedInController(self, value: self.slider.value)
}
}
}
| mit | 604b485b19d098dc91deca11f5bea342 | 27.921569 | 92 | 0.635932 | 5.017007 | false | false | false | false |
KeithPiTsui/Pavers | Pavers/Pavers.playground/Pages/ParsecArithmetic.xcplaygroundpage/Contents.swift | 2 | 1796 | import PaversFRP
import PaversParsec
let digit = character(CharacterSet.decimalDigits.contains)
let decimals = digit.many
let decimalPoint = character{$0 == "."}
let number = (decimals >>> (decimalPoint >>> decimals).optional).map { (args) -> Double in
let (first, second) = args
var values: [Character] = first
if let s = second {
values += [s.0] + s.1
}
let str = String(values)
return Double(str)!
}
let muls = character{$0 == "*"}
let divs = character{$0 == "/"}
let adds = character{$0 == "+"}
let mins = character{$0 == "-"}
// Expression = ['-'] Term { ( '+' | '-' ) Term }.
// Term = number | { ( '*' | '/' ) number }.
// Term1 = Factor | { ( powerroot | power ) Factor | production | percentage }.
// Factor = number | preanser | '(' Expression ')' | Function | variable .
// Function = functionIdentifier [ '(' ParameterList ')' ].
// ParameterList = Expression { ',' | Expression } | Null.
//let term = number
// >>> ((muls <|> divs) >>> number).zeroOrMany
//
//print(term.run("2*3/2"))
//
//let expression = mins.optional
// >>> term
// >>> ((adds <|> mins) >>> term).zeroOrMany
////
//print(expression.run("0-2.4*2.1-2/3.2+2"))
//let x = (character{$0 == "*"} *> number).zeroOrMany
let multiplication = curry({$0 * $1.reduce(1) { $0 * $1}})
<^> number
<*> (muls *> number).zeroOrMany
multiplication.run("1*2*3")
let division = curry({ $0 / $1.reduce(1) { $0 * $1} })
<^> multiplication
<*> (divs *> multiplication).zeroOrMany
division.run("10/5*2")
let addition = curry({ $0 + $1.reduce(0) { $0 + $1} })
<^> division
<*> (adds *> division).zeroOrMany
let minus = curry({ $0 - $1.reduce(0) { $0 + $1} })
<^> addition
<*> (mins *> addition).zeroOrMany
let expression = minus
expression.run("2.4*2.1/3+1-10.0/2.0+5")
| mit | 2ad3ee6511aee2e7ce5af6b85d2670cc | 25.80597 | 90 | 0.576837 | 3.145359 | false | false | false | false |
pennlabs/penn-mobile-ios | PennMobile/More Tab/Profile Page/ProfilePageViewController.swift | 1 | 2936 | //
// AccountPageViewController.swift
// PennMobile
//
// Created by Andrew Antenberg on 9/26/21.
// Copyright © 2021 PennLabs. All rights reserved.
//
import Foundation
import UIKit
class ProfilePageViewController: UIViewController, ShowsAlertForError {
var account: Account!
let tableView = UITableView(frame: .zero, style: .insetGrouped)
let picker = UIImagePickerController()
var viewModel: ProfilePageViewModel!
var profileInfo: [(text: String, info: String)] = []
var educationInfo: [(text: String, info: String)] = []
override func viewDidLoad() {
super.viewDidLoad()
setupView()
guard Account.isLoggedIn else {
self.showAlert(withMsg: "Please login to use this feature", title: "Login Error", completion: { self.navigationController?.popViewController(animated: true)})
return
}
setupPickerController()
setupViewModel()
setupTableView()
}
func setupPickerController() {
picker.sourceType = .photoLibrary
picker.allowsEditing = true
}
func setupViewModel() {
viewModel = ProfilePageViewModel()
tableView.delegate = viewModel
tableView.dataSource = viewModel
picker.delegate = viewModel
viewModel.delegate = self
}
func setupView() {
self.title = "Account"
view.backgroundColor = .uiGroupedBackground
}
func setupTableView() {
view.addSubview(tableView)
tableView.register(ProfilePageTableViewCell.self, forCellReuseIdentifier: ProfilePageTableViewCell.identifier)
tableView.register(ProfilePictureTableViewCell.self, forCellReuseIdentifier: ProfilePictureTableViewCell.identifier)
tableView.translatesAutoresizingMaskIntoConstraints = false
tableView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor).isActive = true
tableView.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor).isActive = true
tableView.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor).isActive = true
tableView.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor).isActive = true
tableView.rowHeight = UITableView.automaticDimension
tableView.estimatedRowHeight = 600
}
}
extension ProfilePageViewController: ProfilePageViewModelDelegate {
func presentImagePicker() {
present(picker, animated: true)
}
func presentTableView(isMajors: Bool) {
let targetController = InfoTableViewController()
targetController.isMajors = isMajors
navigationController?.pushViewController(targetController, animated: true)
}
func imageSelected(_ image: UIImage) {
if let cell = tableView.cellForRow(at: .init(row: 0, section: 0)) as? ProfilePictureTableViewCell {
cell.profilePicImage = image
}
}
}
| mit | c0cd2177a88cc84eb92d990232f6572b | 34.792683 | 170 | 0.705963 | 5.415129 | false | false | false | false |
johndpope/Coiffeur | Coiffeur/src/view/TableCellView.swift | 1 | 991 | //
// TableCellView.swift
// Coiffeur
//
// Created by Anton Leuski on 4/5/15.
// Copyright (c) 2015 Anton Leuski. All rights reserved.
//
import Cocoa
// actually, this code is not being used currently. I keep it here for reference...
class TableCellView : NSTableCellView {
override var backgroundStyle: NSBackgroundStyle {
didSet {
// If the cell's text color is black, this sets it to white
if let cell = self.textField?.cell() as? NSCell {
cell.backgroundStyle = self.backgroundStyle
}
// Otherwise you need to change the color manually
switch (self.backgroundStyle) {
case NSBackgroundStyle.Light:
if let textField = self.textField {
textField.textColor = NSColor(calibratedWhite: 0.0, alpha: 1.0)
}
break;
default:
if let textField = self.textField {
textField.textColor = NSColor(calibratedWhite: 1.0, alpha: 1.0)
}
break;
}
}
}
}
| apache-2.0 | 723fd107dd45654e7f10c88c9f6526e1 | 25.078947 | 83 | 0.629667 | 4.290043 | false | false | false | false |
easyui/Alamofire | Tests/URLProtocolTests.swift | 4 | 5239 | //
// URLProtocolTests.swift
//
// Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/)
//
// 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 Alamofire
import Foundation
import XCTest
class ProxyURLProtocol: URLProtocol {
// MARK: Properties
enum PropertyKeys {
static let handledByForwarderURLProtocol = "HandledByProxyURLProtocol"
}
lazy var session: URLSession = {
let configuration: URLSessionConfiguration = {
let configuration = URLSessionConfiguration.ephemeral
configuration.headers = HTTPHeaders.default
return configuration
}()
let session = URLSession(configuration: configuration, delegate: self, delegateQueue: nil)
return session
}()
weak var activeTask: URLSessionTask?
// MARK: Class Request Methods
override class func canInit(with request: URLRequest) -> Bool {
if URLProtocol.property(forKey: PropertyKeys.handledByForwarderURLProtocol, in: request) != nil {
return false
}
return true
}
override class func canonicalRequest(for request: URLRequest) -> URLRequest {
if let headers = request.allHTTPHeaderFields {
do {
return try URLEncoding.default.encode(request, with: headers)
} catch {
return request
}
}
return request
}
override class func requestIsCacheEquivalent(_ a: URLRequest, to b: URLRequest) -> Bool {
false
}
// MARK: Loading Methods
override func startLoading() {
// rdar://26849668 - URLProtocol had some API's that didn't make the value type conversion
let urlRequest = (request.urlRequest! as NSURLRequest).mutableCopy() as! NSMutableURLRequest
URLProtocol.setProperty(true, forKey: PropertyKeys.handledByForwarderURLProtocol, in: urlRequest)
activeTask = session.dataTask(with: urlRequest as URLRequest)
activeTask?.resume()
}
override func stopLoading() {
activeTask?.cancel()
}
}
// MARK: -
extension ProxyURLProtocol: URLSessionDataDelegate {
// MARK: NSURLSessionDelegate
func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) {
client?.urlProtocol(self, didLoad: data)
}
func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
if let response = task.response {
client?.urlProtocol(self, didReceive: response, cacheStoragePolicy: .notAllowed)
}
client?.urlProtocolDidFinishLoading(self)
}
}
// MARK: -
class URLProtocolTestCase: BaseTestCase {
var manager: Session!
// MARK: Setup and Teardown
override func setUp() {
super.setUp()
manager = {
let configuration: URLSessionConfiguration = {
let configuration = URLSessionConfiguration.default
configuration.protocolClasses = [ProxyURLProtocol.self]
configuration.headers["Session-Configuration-Header"] = "foo"
return configuration
}()
return Session(configuration: configuration)
}()
}
// MARK: Tests
func testThatURLProtocolReceivesRequestHeadersAndSessionConfigurationHeaders() {
// Given
let endpoint = Endpoint.responseHeaders.modifying(\.headers, to: ["Request-Header": "foobar"])
let expectation = self.expectation(description: "GET request should succeed")
var response: DataResponse<Data?, AFError>?
// When
manager.request(endpoint)
.response { resp in
response = resp
expectation.fulfill()
}
waitForExpectations(timeout: timeout)
// Then
XCTAssertNotNil(response?.request)
XCTAssertNotNil(response?.response)
XCTAssertNotNil(response?.data)
XCTAssertNil(response?.error)
XCTAssertEqual(response?.response?.headers["Request-Header"], "foobar")
XCTAssertEqual(response?.response?.headers["Session-Configuration-Header"], "foo")
}
}
| mit | fcf92a41b1459dd3dd0333e75c4e47f2 | 31.74375 | 105 | 0.670357 | 5.29727 | false | true | false | false |
damicreabox/Git2Swift | Sources/Git2Swift/index/Index.swift | 1 | 1726 | //
// Index.swift
// Git2Swift
//
// Created by Damien Giron on 01/08/2016.
//
//
import Foundation
import CLibgit2
/// Git index
public class Index {
/// Git2Swift repository
public let repository : Repository
/// Libgit2 index pointer
internal let idx: UnsafeMutablePointer<OpaquePointer?>
/// Has conflict in index
public var conflicts : Bool {
get {
return git_index_has_conflicts(idx.pointee) == 1
}
}
/// Constructor with repository and libgit2 index pointer
///
/// - parameter repository: Git2Swift repository
/// - parameter idx: Libgit2 index
///
/// - returns: Index
init(repository: Repository, idx: UnsafeMutablePointer<OpaquePointer?>) {
self.repository = repository
self.idx = idx
}
/// Constructor with repository and return repository index
///
/// - parameter repository: Git2Swift repository
///
/// - throws: GitError
///
/// - returns: Index
convenience init(repository: Repository) throws {
let idx = UnsafeMutablePointer<OpaquePointer?>.allocate(capacity: 1)
// Create index
let error = git_repository_index(idx, repository.pointer.pointee)
if (error != 0) {
idx.deinitialize()
idx.deallocate(capacity: 1)
throw gitUnknownError("Unable to init repository index", code: error)
}
self.init(repository: repository, idx: idx)
}
deinit {
if let ptr = idx.pointee {
git_index_free(ptr)
}
idx.deinitialize()
idx.deallocate(capacity: 1)
}
}
| apache-2.0 | a31acb11cdb3bc1e6675906c0b174e4b | 23.309859 | 81 | 0.577636 | 4.690217 | false | false | false | false |
noppoMan/aws-sdk-swift | Sources/Soto/Services/GroundStation/GroundStation_Paginator.swift | 1 | 16525 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Soto for AWS open source project
//
// Copyright (c) 2017-2020 the Soto project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of Soto project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
// THIS FILE IS AUTOMATICALLY GENERATED by https://github.com/soto-project/soto/tree/main/CodeGenerator. DO NOT EDIT.
import SotoCore
// MARK: Paginators
extension GroundStation {
/// Returns a list of Config objects.
///
/// Provide paginated results to closure `onPage` for it to combine them into one result.
/// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`.
///
/// Parameters:
/// - input: Input for request
/// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called.
/// - logger: Logger used flot logging
/// - eventLoop: EventLoop to run this process on
/// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned
/// along with a boolean indicating if the paginate operation should continue.
public func listConfigsPaginator<Result>(
_ input: ListConfigsRequest,
_ initialValue: Result,
logger: Logger = AWSClient.loggingDisabled,
on eventLoop: EventLoop? = nil,
onPage: @escaping (Result, ListConfigsResponse, EventLoop) -> EventLoopFuture<(Bool, Result)>
) -> EventLoopFuture<Result> {
return client.paginate(
input: input,
initialValue: initialValue,
command: listConfigs,
tokenKey: \ListConfigsResponse.nextToken,
on: eventLoop,
onPage: onPage
)
}
/// Provide paginated results to closure `onPage`.
///
/// - Parameters:
/// - input: Input for request
/// - logger: Logger used flot logging
/// - eventLoop: EventLoop to run this process on
/// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue.
public func listConfigsPaginator(
_ input: ListConfigsRequest,
logger: Logger = AWSClient.loggingDisabled,
on eventLoop: EventLoop? = nil,
onPage: @escaping (ListConfigsResponse, EventLoop) -> EventLoopFuture<Bool>
) -> EventLoopFuture<Void> {
return client.paginate(
input: input,
command: listConfigs,
tokenKey: \ListConfigsResponse.nextToken,
on: eventLoop,
onPage: onPage
)
}
/// Returns a list of contacts. If statusList contains AVAILABLE, the request must include groundStation, missionprofileArn, and satelliteArn.
///
/// Provide paginated results to closure `onPage` for it to combine them into one result.
/// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`.
///
/// Parameters:
/// - input: Input for request
/// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called.
/// - logger: Logger used flot logging
/// - eventLoop: EventLoop to run this process on
/// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned
/// along with a boolean indicating if the paginate operation should continue.
public func listContactsPaginator<Result>(
_ input: ListContactsRequest,
_ initialValue: Result,
logger: Logger = AWSClient.loggingDisabled,
on eventLoop: EventLoop? = nil,
onPage: @escaping (Result, ListContactsResponse, EventLoop) -> EventLoopFuture<(Bool, Result)>
) -> EventLoopFuture<Result> {
return client.paginate(
input: input,
initialValue: initialValue,
command: listContacts,
tokenKey: \ListContactsResponse.nextToken,
on: eventLoop,
onPage: onPage
)
}
/// Provide paginated results to closure `onPage`.
///
/// - Parameters:
/// - input: Input for request
/// - logger: Logger used flot logging
/// - eventLoop: EventLoop to run this process on
/// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue.
public func listContactsPaginator(
_ input: ListContactsRequest,
logger: Logger = AWSClient.loggingDisabled,
on eventLoop: EventLoop? = nil,
onPage: @escaping (ListContactsResponse, EventLoop) -> EventLoopFuture<Bool>
) -> EventLoopFuture<Void> {
return client.paginate(
input: input,
command: listContacts,
tokenKey: \ListContactsResponse.nextToken,
on: eventLoop,
onPage: onPage
)
}
/// Returns a list of DataflowEndpoint groups.
///
/// Provide paginated results to closure `onPage` for it to combine them into one result.
/// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`.
///
/// Parameters:
/// - input: Input for request
/// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called.
/// - logger: Logger used flot logging
/// - eventLoop: EventLoop to run this process on
/// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned
/// along with a boolean indicating if the paginate operation should continue.
public func listDataflowEndpointGroupsPaginator<Result>(
_ input: ListDataflowEndpointGroupsRequest,
_ initialValue: Result,
logger: Logger = AWSClient.loggingDisabled,
on eventLoop: EventLoop? = nil,
onPage: @escaping (Result, ListDataflowEndpointGroupsResponse, EventLoop) -> EventLoopFuture<(Bool, Result)>
) -> EventLoopFuture<Result> {
return client.paginate(
input: input,
initialValue: initialValue,
command: listDataflowEndpointGroups,
tokenKey: \ListDataflowEndpointGroupsResponse.nextToken,
on: eventLoop,
onPage: onPage
)
}
/// Provide paginated results to closure `onPage`.
///
/// - Parameters:
/// - input: Input for request
/// - logger: Logger used flot logging
/// - eventLoop: EventLoop to run this process on
/// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue.
public func listDataflowEndpointGroupsPaginator(
_ input: ListDataflowEndpointGroupsRequest,
logger: Logger = AWSClient.loggingDisabled,
on eventLoop: EventLoop? = nil,
onPage: @escaping (ListDataflowEndpointGroupsResponse, EventLoop) -> EventLoopFuture<Bool>
) -> EventLoopFuture<Void> {
return client.paginate(
input: input,
command: listDataflowEndpointGroups,
tokenKey: \ListDataflowEndpointGroupsResponse.nextToken,
on: eventLoop,
onPage: onPage
)
}
/// Returns a list of ground stations.
///
/// Provide paginated results to closure `onPage` for it to combine them into one result.
/// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`.
///
/// Parameters:
/// - input: Input for request
/// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called.
/// - logger: Logger used flot logging
/// - eventLoop: EventLoop to run this process on
/// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned
/// along with a boolean indicating if the paginate operation should continue.
public func listGroundStationsPaginator<Result>(
_ input: ListGroundStationsRequest,
_ initialValue: Result,
logger: Logger = AWSClient.loggingDisabled,
on eventLoop: EventLoop? = nil,
onPage: @escaping (Result, ListGroundStationsResponse, EventLoop) -> EventLoopFuture<(Bool, Result)>
) -> EventLoopFuture<Result> {
return client.paginate(
input: input,
initialValue: initialValue,
command: listGroundStations,
tokenKey: \ListGroundStationsResponse.nextToken,
on: eventLoop,
onPage: onPage
)
}
/// Provide paginated results to closure `onPage`.
///
/// - Parameters:
/// - input: Input for request
/// - logger: Logger used flot logging
/// - eventLoop: EventLoop to run this process on
/// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue.
public func listGroundStationsPaginator(
_ input: ListGroundStationsRequest,
logger: Logger = AWSClient.loggingDisabled,
on eventLoop: EventLoop? = nil,
onPage: @escaping (ListGroundStationsResponse, EventLoop) -> EventLoopFuture<Bool>
) -> EventLoopFuture<Void> {
return client.paginate(
input: input,
command: listGroundStations,
tokenKey: \ListGroundStationsResponse.nextToken,
on: eventLoop,
onPage: onPage
)
}
/// Returns a list of mission profiles.
///
/// Provide paginated results to closure `onPage` for it to combine them into one result.
/// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`.
///
/// Parameters:
/// - input: Input for request
/// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called.
/// - logger: Logger used flot logging
/// - eventLoop: EventLoop to run this process on
/// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned
/// along with a boolean indicating if the paginate operation should continue.
public func listMissionProfilesPaginator<Result>(
_ input: ListMissionProfilesRequest,
_ initialValue: Result,
logger: Logger = AWSClient.loggingDisabled,
on eventLoop: EventLoop? = nil,
onPage: @escaping (Result, ListMissionProfilesResponse, EventLoop) -> EventLoopFuture<(Bool, Result)>
) -> EventLoopFuture<Result> {
return client.paginate(
input: input,
initialValue: initialValue,
command: listMissionProfiles,
tokenKey: \ListMissionProfilesResponse.nextToken,
on: eventLoop,
onPage: onPage
)
}
/// Provide paginated results to closure `onPage`.
///
/// - Parameters:
/// - input: Input for request
/// - logger: Logger used flot logging
/// - eventLoop: EventLoop to run this process on
/// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue.
public func listMissionProfilesPaginator(
_ input: ListMissionProfilesRequest,
logger: Logger = AWSClient.loggingDisabled,
on eventLoop: EventLoop? = nil,
onPage: @escaping (ListMissionProfilesResponse, EventLoop) -> EventLoopFuture<Bool>
) -> EventLoopFuture<Void> {
return client.paginate(
input: input,
command: listMissionProfiles,
tokenKey: \ListMissionProfilesResponse.nextToken,
on: eventLoop,
onPage: onPage
)
}
/// Returns a list of satellites.
///
/// Provide paginated results to closure `onPage` for it to combine them into one result.
/// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`.
///
/// Parameters:
/// - input: Input for request
/// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called.
/// - logger: Logger used flot logging
/// - eventLoop: EventLoop to run this process on
/// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned
/// along with a boolean indicating if the paginate operation should continue.
public func listSatellitesPaginator<Result>(
_ input: ListSatellitesRequest,
_ initialValue: Result,
logger: Logger = AWSClient.loggingDisabled,
on eventLoop: EventLoop? = nil,
onPage: @escaping (Result, ListSatellitesResponse, EventLoop) -> EventLoopFuture<(Bool, Result)>
) -> EventLoopFuture<Result> {
return client.paginate(
input: input,
initialValue: initialValue,
command: listSatellites,
tokenKey: \ListSatellitesResponse.nextToken,
on: eventLoop,
onPage: onPage
)
}
/// Provide paginated results to closure `onPage`.
///
/// - Parameters:
/// - input: Input for request
/// - logger: Logger used flot logging
/// - eventLoop: EventLoop to run this process on
/// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue.
public func listSatellitesPaginator(
_ input: ListSatellitesRequest,
logger: Logger = AWSClient.loggingDisabled,
on eventLoop: EventLoop? = nil,
onPage: @escaping (ListSatellitesResponse, EventLoop) -> EventLoopFuture<Bool>
) -> EventLoopFuture<Void> {
return client.paginate(
input: input,
command: listSatellites,
tokenKey: \ListSatellitesResponse.nextToken,
on: eventLoop,
onPage: onPage
)
}
}
extension GroundStation.ListConfigsRequest: AWSPaginateToken {
public func usingPaginationToken(_ token: String) -> GroundStation.ListConfigsRequest {
return .init(
maxResults: self.maxResults,
nextToken: token
)
}
}
extension GroundStation.ListContactsRequest: AWSPaginateToken {
public func usingPaginationToken(_ token: String) -> GroundStation.ListContactsRequest {
return .init(
endTime: self.endTime,
groundStation: self.groundStation,
maxResults: self.maxResults,
missionProfileArn: self.missionProfileArn,
nextToken: token,
satelliteArn: self.satelliteArn,
startTime: self.startTime,
statusList: self.statusList
)
}
}
extension GroundStation.ListDataflowEndpointGroupsRequest: AWSPaginateToken {
public func usingPaginationToken(_ token: String) -> GroundStation.ListDataflowEndpointGroupsRequest {
return .init(
maxResults: self.maxResults,
nextToken: token
)
}
}
extension GroundStation.ListGroundStationsRequest: AWSPaginateToken {
public func usingPaginationToken(_ token: String) -> GroundStation.ListGroundStationsRequest {
return .init(
maxResults: self.maxResults,
nextToken: token,
satelliteId: self.satelliteId
)
}
}
extension GroundStation.ListMissionProfilesRequest: AWSPaginateToken {
public func usingPaginationToken(_ token: String) -> GroundStation.ListMissionProfilesRequest {
return .init(
maxResults: self.maxResults,
nextToken: token
)
}
}
extension GroundStation.ListSatellitesRequest: AWSPaginateToken {
public func usingPaginationToken(_ token: String) -> GroundStation.ListSatellitesRequest {
return .init(
maxResults: self.maxResults,
nextToken: token
)
}
}
| apache-2.0 | 099f44e4a5eae9ed0075ddecd8becf5b | 41.590206 | 168 | 0.642602 | 5.226123 | false | false | false | false |
hsoi/RxSwift | RxCocoa/iOS/DataSources/RxCollectionViewReactiveArrayDataSource.swift | 7 | 3152 | //
// RxCollectionViewReactiveArrayDataSource.swift
// RxCocoa
//
// Created by Krunoslav Zaher on 6/29/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
#if os(iOS) || os(tvOS)
import Foundation
import UIKit
#if !RX_NO_MODULE
import RxSwift
#endif
// objc monkey business
class _RxCollectionViewReactiveArrayDataSource: NSObject, UICollectionViewDataSource {
func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
return 1
}
func _collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 0
}
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return _collectionView(collectionView, numberOfItemsInSection: section)
}
func _collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
rxAbstractMethod()
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
return _collectionView(collectionView, cellForItemAtIndexPath: indexPath)
}
}
class RxCollectionViewReactiveArrayDataSourceSequenceWrapper<S: SequenceType> : RxCollectionViewReactiveArrayDataSource<S.Generator.Element>
, RxCollectionViewDataSourceType {
typealias Element = S
override init(cellFactory: CellFactory) {
super.init(cellFactory: cellFactory)
}
func collectionView(collectionView: UICollectionView, observedEvent: Event<S>) {
switch observedEvent {
case .Next(let value):
super.collectionView(collectionView, observedElements: Array(value))
self.itemModels = Array(value)
case .Error(let error):
bindingErrorToInterface(error)
case .Completed:
break
}
}
}
// Please take a look at `DelegateProxyType.swift`
class RxCollectionViewReactiveArrayDataSource<Element> : _RxCollectionViewReactiveArrayDataSource {
typealias CellFactory = (UICollectionView, Int, Element) -> UICollectionViewCell
var itemModels: [Element]? = nil
func modelAtIndex(index: Int) -> Element? {
return itemModels?[index]
}
var cellFactory: CellFactory
init(cellFactory: CellFactory) {
self.cellFactory = cellFactory
}
// data source
override func _collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return itemModels?.count ?? 0
}
override func _collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
return cellFactory(collectionView, indexPath.item, itemModels![indexPath.item])
}
// reactive
func collectionView(collectionView: UICollectionView, observedElements: [Element]) {
self.itemModels = observedElements
collectionView.reloadData()
}
}
#endif
| mit | 37cf104a4dfdc51edadca2a9fcec4067 | 30.828283 | 140 | 0.693431 | 5.990494 | false | false | false | false |
MirAshrafUddin/MAColorWheel-rotable | MAColorWheel/MAColorWheel/MAColorWheel.swift | 1 | 23687 |
import Foundation
import UIKit
class MAColorWheel: UIView{
var colorPick : ColorPick!
var colorView : ColorView!
var tapped:Bool = false
var ButtonTapped = false
var ButtonTappedInRect = false
var angle: CGFloat = 0.0
var selectedColor: UIColor = UIColor.red
var animAngle:CGFloat = 0.0
var previousPos:CGPoint = CGPoint(x: 0, y: 0)
override init(frame: CGRect) {
super.init(frame: frame)
createView()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func createView(){
colorView = ColorView(frame: CGRect(x: 0, y: 0, width: 225, height: 225))
colorPick = ColorPick(frame: CGRect(x: 0, y: 0, width: 225, height: 225))
colorView.center = self.center
colorPick.center = self.center
colorPick.backgroundColor = UIColor.clear
colorView.backgroundColor = UIColor.clear
colorView.colorArray.append(UIColor.red)
colorView.colorArray.append(UIColor.green)
colorView.colorArray.append(UIColor.orange)
colorView.colorArray.append(UIColor.yellow)
colorView.colorArray.append(UIColor.blue)
colorView.colorArray.append(UIColor.brown)
colorView.colorArray.append(UIColor.magenta)
colorView.colorArray.append(UIColor.purple)
self.addSubview(colorView)
self.addSubview(colorPick)
//colorPaletteSelection(a: "#655f47", b: "#d74958", c: "#b5dcb9", d: "#6bbd99", e: "#7b8977", f: "#f9e393", g: "#c3aa5b", h: "#b89a2d")
ButtonTapped=false
}
func touchBegin(_ touches: Set<UITouch>) {
if let touch = touches.first {
let position = touch.location(in: self)
if incDecOverload(first: plusMinusOverload(first: colorView.center, second: CGPoint(x: colorView.frame.size.width/2,y: colorView.frame.size.width/2), option: 0),second: position,option: 1) && incDecOverload(first: plusMinusOverload(first: colorView.center, second: CGPoint(x: colorView.frame.size.width/2,y: colorView.frame.size.width/2), option: 1),second: position,option: 0){
print("POSITION: \(position)")
let target = colorView.center
print("TARGET: \(target)")
angle = atan2(target.y - position.y, target.x - position.x)
print("ANGLE: \(angle)")
ButtonTappedInRect=true
tapped=true
}
else{
ButtonTappedInRect=false
}
}
}
func touchMoved(_ touches: Set<UITouch>) {
let touch: UITouch = touches.first!
let position = touch.location(in: self)
if incDecOverload(first: plusMinusOverload(first: colorView.center, second: CGPoint(x: colorView.frame.size.width/2,y: colorView.frame.size.width/2), option: 0),second: position,option: 1) && incDecOverload(first: plusMinusOverload(first: colorView.center, second: CGPoint(x: colorView.frame.size.width/2,y: colorView.frame.size.width/2), option: 1),second: position,option: 0){
tapped=false
}
if ButtonTappedInRect{
var currentTouch = touch.location(in: self)
var previousTouch = touch.previousLocation(in: self)
currentTouch.x = currentTouch.x - colorView.center.x
currentTouch.y = colorView.center.y - currentTouch.y
previousTouch.x = previousTouch.x - colorView.center.x
previousTouch.y = colorView.center.y - previousTouch.y
let angleDifference = atan2(previousTouch.y, previousTouch.x) - atan2(currentTouch.y, currentTouch.x)
angle = atan2(self.transform.a, self.transform.b) + atan2(self.colorView.transform.a, self.colorView.transform.b);
//print("angle: \(angle)")
UIView.animate(withDuration: 0.05, animations: { () -> Void in
self.colorView.transform = self.colorView.transform.rotated(by: angleDifference)
})
}
}
func touchEnded(_ touches: Set<UITouch>) {
if tapped == true
{
//let touch: UITouch = touches.first!
if let touch = touches.first {
let position = touch.location(in: self)
let distance = (pow(colorView.center.x - position.x,2) + pow(colorView.center.y - position.y,2))
if distance < pow(80/2,2){
ButtonTapped=true
}
else{
colorSelectionWithTap()
}
}
}
else{
colorSelectionWithMotion()
}
UIView.animate(withDuration: 0.3, animations: {
self.colorView.transform = CGAffineTransform(rotationAngle: CGFloat(self.animAngle))
//self.colorView.transform = self.colorView.transform.rotated(by: self.angle)
})
//colorPick = ColorPick()
if ButtonTapped==false{
colorPick.counterColor = selectedColor
colorPick.setNeedsDisplay()
}
}
func colorSelectionWithMotion(){
if (0 < angle && angle < 0.78) {
let newAngle = 0 + 0.4
if CGFloat(newAngle) < angle && angle < 0.78 {
selectedColor = colorView.colorArray[5]
//selectedColor = UIColor.brown
animAngle=2.34
print("asdf")
} else {
selectedColor = colorView.colorArray[4]
//selectedColor = UIColor.blue
animAngle=3.14
}
}
else if (0.78 < angle && angle < 1.57) {
let newAngle = 0.78 + 0.4
if CGFloat(newAngle) < angle && angle < 1.57 {
selectedColor = colorView.colorArray[6]
//selectedColor = UIColor.magenta
animAngle=1.57
print("asdf")
} else {
selectedColor = colorView.colorArray[5]
//selectedColor = UIColor.brown
animAngle=2.34
}
}
else if (1.57 < angle && angle < 2.34) {
let newAngle = 1.57 + 0.4
if CGFloat(newAngle) < angle && angle < 2.34 {
selectedColor = colorView.colorArray[7]
//selectedColor = UIColor.purple
animAngle=0.78
print("asdf")
} else {
selectedColor = colorView.colorArray[6]
//selectedColor = UIColor.magenta
animAngle=1.57
}
}
else if (2.34 < angle && angle < 3.14) {
let newAngle = 2.34 + 0.4
if CGFloat(newAngle) < angle && angle < 3.14 {
selectedColor = colorView.colorArray[0]
//selectedColor = UIColor.red
animAngle = -0.01
print("asdf")
} else {
selectedColor = colorView.colorArray[7]
//selectedColor = UIColor.purple
animAngle=0.78
}
}
else if (3.14 < angle && angle < 3.92) {
let newAngle = 3.14 + 0.4
if CGFloat(newAngle) < angle && angle < 3.92 {
selectedColor = colorView.colorArray[1]
//selectedColor = UIColor.green
animAngle = -0.78
print("asdf")
} else {
selectedColor = colorView.colorArray[0]
//selectedColor = UIColor.red
animAngle = -0.01
}
}
else if (3.92 < angle && angle < 4.70) {
let newAngle = 3.92 + 0.4
if CGFloat(newAngle) < angle && angle < 4.70 {
selectedColor = colorView.colorArray[2]
//selectedColor = UIColor.orange
animAngle = -1.58
print("asdf")
} else {
selectedColor = colorView.colorArray[1]
//selectedColor = UIColor.green
animAngle = -0.78
}
}
else if (-1.58 < angle && angle < -0.78) {
let newAngle = -1.58 + 0.4
if CGFloat(newAngle) < angle && angle < -0.78 {
selectedColor = colorView.colorArray[3]
//selectedColor = UIColor.yellow
animAngle = -2.35
print("asdf")
} else {
selectedColor = colorView.colorArray[2]
//selectedColor = UIColor.orange
animAngle = -1.58
}
}
else if (-0.78 < angle && angle < 0) {
let newAngle = -0.78 + 0.4
if CGFloat(newAngle) < angle && angle < 0 {
selectedColor = colorView.colorArray[4]
//selectedColor = UIColor.blue
animAngle = 3.14
print("asdf")
} else {
selectedColor = colorView.colorArray[3]
//selectedColor = UIColor.yellow
animAngle = -2.35
}
}
}
func colorSelectionWithTap(){
if selectedColor == colorView.colorArray[0] {
if (1.2 < angle && angle < 1.9) {
animAngle = -0.01
selectedColor = colorView.colorArray[0]
} else if (1.9 < angle && angle < 2.6) {
animAngle = -0.78
selectedColor = colorView.colorArray[1]
}else if (2.6 < angle && angle < 3.1416 || -3.1416 < angle && angle < -2.7) {
animAngle = -1.58
selectedColor = colorView.colorArray[2]
}
else if (-2.7 < angle && angle < -1.9) {
animAngle = -2.35
selectedColor = colorView.colorArray[3]
} else if (-1.9 < angle && angle < -1.2) {
animAngle = 3.14
selectedColor = colorView.colorArray[4]
} else if (-1.2 < angle && angle < -0.4) {
animAngle = 2.34
selectedColor = colorView.colorArray[5]
}else if (-0.4 < angle && angle < 0.4) {
animAngle = 1.57
selectedColor = colorView.colorArray[6]
}
else if (0.4 < angle && angle < 1.2) {
animAngle = 0.78
selectedColor = colorView.colorArray[7]
}
}
else if selectedColor == colorView.colorArray[1] {
if (1.2 < angle && angle < 1.9) {
animAngle = -0.78
selectedColor = colorView.colorArray[1]
} else if (1.9 < angle && angle < 2.6) {
animAngle = -1.58
selectedColor = colorView.colorArray[2]
}else if (2.6 < angle && angle < 3.1416 || -3.1416 < angle && angle < -2.7) {
animAngle = -2.35
selectedColor = colorView.colorArray[3]
}
else if (-2.7 < angle && angle < -1.9) {
animAngle = 3.14
selectedColor = colorView.colorArray[4]
} else if (-1.9 < angle && angle < -1.2) {
animAngle = 2.34
selectedColor = colorView.colorArray[5]
} else if (-1.2 < angle && angle < -0.4) {
animAngle = 1.57
selectedColor = colorView.colorArray[6]
}else if (-0.4 < angle && angle < 0.4) {
animAngle = 0.78
selectedColor = colorView.colorArray[7]
}
else if (0.4 < angle && angle < 1.2) {
animAngle = -0.01
selectedColor = colorView.colorArray[0]
}
}
else if selectedColor == colorView.colorArray[2] {
if (1.2 < angle && angle < 1.9) {
animAngle = -1.58
selectedColor = colorView.colorArray[2]
} else if (1.9 < angle && angle < 2.6) {
animAngle = -2.35
selectedColor = colorView.colorArray[3]
}else if (2.6 < angle && angle < 3.1416 || -3.1416 < angle && angle < -2.7) {
animAngle = 3.14
selectedColor = colorView.colorArray[4]
}
else if (-2.7 < angle && angle < -1.9) {
animAngle = 2.34
selectedColor = colorView.colorArray[5]
} else if (-1.9 < angle && angle < -1.2) {
animAngle = 1.57
selectedColor = colorView.colorArray[6]
} else if (-1.2 < angle && angle < -0.4) {
animAngle = 0.78
selectedColor = colorView.colorArray[7]
}else if (-0.4 < angle && angle < 0.4) {
animAngle = -0.01
selectedColor = colorView.colorArray[0]
}
else if (0.4 < angle && angle < 1.2) {
animAngle = -0.78
selectedColor = colorView.colorArray[1]
}
}
else if selectedColor == colorView.colorArray[3] {
if (1.2 < angle && angle < 1.9) {
animAngle = -2.35
selectedColor = colorView.colorArray[3]
} else if (1.9 < angle && angle < 2.6) {
animAngle = 3.14
selectedColor = colorView.colorArray[4]
}else if (2.6 < angle && angle < 3.1416 || -3.1416 < angle && angle < -2.7) {
animAngle = 2.34
selectedColor = colorView.colorArray[5]
}
else if (-2.7 < angle && angle < -1.9) {
animAngle = 1.57
selectedColor = colorView.colorArray[6]
} else if (-1.9 < angle && angle < -1.2) {
animAngle = 0.78
selectedColor = colorView.colorArray[7]
} else if (-1.2 < angle && angle < -0.4) {
animAngle = -0.01
selectedColor = colorView.colorArray[0]
}else if (-0.4 < angle && angle < 0.4) {
animAngle = -0.78
selectedColor = colorView.colorArray[1]
}
else if (0.4 < angle && angle < 1.2) {
animAngle = -1.58
selectedColor = colorView.colorArray[2]
}
}
else if selectedColor == colorView.colorArray[4] {
if (1.2 < angle && angle < 1.9) {
animAngle = 3.14
selectedColor = colorView.colorArray[4]
} else if (1.9 < angle && angle < 2.6) {
animAngle = 2.34
selectedColor = colorView.colorArray[5]
}else if (2.6 < angle && angle < 3.1416 || -3.1416 < angle && angle < -2.7) {
animAngle = 1.57
selectedColor = colorView.colorArray[6]
}
else if (-2.7 < angle && angle < -1.9) {
animAngle = 0.78
selectedColor = colorView.colorArray[7]
} else if (-1.9 < angle && angle < -1.2) {
animAngle = -0.01
selectedColor = colorView.colorArray[0]
} else if (-1.2 < angle && angle < -0.4) {
animAngle = -0.78
selectedColor = colorView.colorArray[1]
}else if (-0.4 < angle && angle < 0.4) {
animAngle = -1.58
selectedColor = colorView.colorArray[2]
}
else if (0.4 < angle && angle < 1.2) {
animAngle = -2.35
selectedColor = colorView.colorArray[3]
}
}
else if selectedColor == colorView.colorArray[5] {
if (1.2 < angle && angle < 1.9) {
animAngle = 2.34
selectedColor = colorView.colorArray[5]
} else if (1.9 < angle && angle < 2.6) {
animAngle = 1.57
selectedColor = colorView.colorArray[6]
}else if (2.6 < angle && angle < 3.1416 || -3.1416 < angle && angle < -2.7) {
animAngle = 0.78
selectedColor = colorView.colorArray[7]
}
else if (-2.7 < angle && angle < -1.9) {
animAngle = -0.01
selectedColor = colorView.colorArray[0]
} else if (-1.9 < angle && angle < -1.2) {
animAngle = -0.78
selectedColor = colorView.colorArray[1]
} else if (-1.2 < angle && angle < -0.4) {
animAngle = -1.58
selectedColor = colorView.colorArray[2]
}else if (-0.4 < angle && angle < 0.4) {
animAngle = -2.35
selectedColor = colorView.colorArray[3]
}
else if (0.4 < angle && angle < 1.2) {
animAngle = 3.14
selectedColor = colorView.colorArray[4]
}
}
else if selectedColor == colorView.colorArray[6] {
if (1.2 < angle && angle < 1.9) {
animAngle = 1.57
selectedColor = colorView.colorArray[6]
} else if (1.9 < angle && angle < 2.6) {
animAngle = 0.78
selectedColor = colorView.colorArray[7]
}else if (2.6 < angle && angle < 3.1416 || -3.1416 < angle && angle < -2.7) {
animAngle = -0.01
selectedColor = colorView.colorArray[0]
}
else if (-2.7 < angle && angle < -1.9) {
animAngle = -0.78
selectedColor = colorView.colorArray[1]
} else if (-1.9 < angle && angle < -1.2) {
animAngle = -1.58
selectedColor = colorView.colorArray[2]
} else if (-1.2 < angle && angle < -0.4) {
animAngle = -2.35
selectedColor = colorView.colorArray[3]
}else if (-0.4 < angle && angle < 0.4) {
animAngle = 3.14
selectedColor = colorView.colorArray[4]
}
else if (0.4 < angle && angle < 1.2) {
animAngle = 2.34
selectedColor = colorView.colorArray[5]
}
}
else if selectedColor == colorView.colorArray[7] {
if (1.2 < angle && angle < 1.9) {
animAngle = 0.78
selectedColor = colorView.colorArray[7]
} else if (1.9 < angle && angle < 2.6) {
animAngle = -0.01
selectedColor = colorView.colorArray[0]
}else if (2.6 < angle && angle < 3.1416 || -3.1416 < angle && angle < -2.7) {
animAngle = -0.78
selectedColor = colorView.colorArray[1]
}
else if (-2.7 < angle && angle < -1.9) {
animAngle = -1.58
selectedColor = colorView.colorArray[2]
} else if (-1.9 < angle && angle < -1.2) {
animAngle = -2.35
selectedColor = colorView.colorArray[3]
} else if (-1.2 < angle && angle < -0.4) {
animAngle = 3.14
selectedColor = colorView.colorArray[4]
}else if (-0.4 < angle && angle < 0.4) {
animAngle = 2.34
selectedColor = colorView.colorArray[5]
}
else if (0.4 < angle && angle < 1.2) {
animAngle = 1.57
selectedColor = colorView.colorArray[6]
}
}
}
func plusMinusOverload (first: CGPoint, second: CGPoint, option: Int64) -> CGPoint {
if option==0{
return CGPoint(x: first.x - second.x,y: first.y - second.y)
}
else{
return CGPoint(x: first.x + second.x,y: first.y + second.y)
}
}
func incDecOverload (first: CGPoint, second: CGPoint, option: Int64) -> Bool {
if option==0{
if first.x>second.x && first.y>second.y{
return true
}
return false
}
else{
if second.x>first.x && second.y>first.y{
return true
}
return false
}
}
func colorPaletteSelection(col1: String, col2:String, col3:String, col4:String, col5:String, col6:String, col7:String, col8:String){
colorView.colorArray.removeAll()
colorView.colorArray.append(UIColor.init(hexString: col1)!)
colorView.colorArray.append(UIColor.init(hexString: col2)!)
colorView.colorArray.append(UIColor.init(hexString: col3)!)
colorView.colorArray.append(UIColor.init(hexString: col4)!)
colorView.colorArray.append(UIColor.init(hexString: col5)!)
colorView.colorArray.append(UIColor.init(hexString: col6)!)
colorView.colorArray.append(UIColor.init(hexString: col7)!)
colorView.colorArray.append(UIColor.init(hexString: col8)!)
colorPick.counterColor = colorView.colorArray[0]
selectedColor = colorView.colorArray[0]
}
}
| mit | 8e58d86548a88f822b23256bc3d15194 | 34.301043 | 390 | 0.441381 | 4.912277 | false | false | false | false |
austinzheng/swift | stdlib/public/core/SequenceAlgorithms.swift | 1 | 33257 | //===--- SequenceAlgorithms.swift -----------------------------*- swift -*-===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//===----------------------------------------------------------------------===//
// enumerated()
//===----------------------------------------------------------------------===//
extension Sequence {
/// Returns a sequence of pairs (*n*, *x*), where *n* represents a
/// consecutive integer starting at zero and *x* represents an element of
/// the sequence.
///
/// This example enumerates the characters of the string "Swift" and prints
/// each character along with its place in the string.
///
/// for (n, c) in "Swift".enumerated() {
/// print("\(n): '\(c)'")
/// }
/// // Prints "0: 'S'"
/// // Prints "1: 'w'"
/// // Prints "2: 'i'"
/// // Prints "3: 'f'"
/// // Prints "4: 't'"
///
/// When you enumerate a collection, the integer part of each pair is a counter
/// for the enumeration, but is not necessarily the index of the paired value.
/// These counters can be used as indices only in instances of zero-based,
/// integer-indexed collections, such as `Array` and `ContiguousArray`. For
/// other collections the counters may be out of range or of the wrong type
/// to use as an index. To iterate over the elements of a collection with its
/// indices, use the `zip(_:_:)` function.
///
/// This example iterates over the indices and elements of a set, building a
/// list consisting of indices of names with five or fewer letters.
///
/// let names: Set = ["Sofia", "Camilla", "Martina", "Mateo", "Nicolás"]
/// var shorterIndices: [Set<String>.Index] = []
/// for (i, name) in zip(names.indices, names) {
/// if name.count <= 5 {
/// shorterIndices.append(i)
/// }
/// }
///
/// Now that the `shorterIndices` array holds the indices of the shorter
/// names in the `names` set, you can use those indices to access elements in
/// the set.
///
/// for i in shorterIndices {
/// print(names[i])
/// }
/// // Prints "Sofia"
/// // Prints "Mateo"
///
/// - Returns: A sequence of pairs enumerating the sequence.
///
/// - Complexity: O(1)
@inlinable // protocol-only
public func enumerated() -> EnumeratedSequence<Self> {
return EnumeratedSequence(_base: self)
}
}
//===----------------------------------------------------------------------===//
// min(), max()
//===----------------------------------------------------------------------===//
extension Sequence {
/// Returns the minimum element in the sequence, using the given predicate as
/// the comparison between elements.
///
/// The predicate must be a *strict weak ordering* over the elements. That
/// is, for any elements `a`, `b`, and `c`, the following conditions must
/// hold:
///
/// - `areInIncreasingOrder(a, a)` is always `false`. (Irreflexivity)
/// - If `areInIncreasingOrder(a, b)` and `areInIncreasingOrder(b, c)` are
/// both `true`, then `areInIncreasingOrder(a, c)` is also
/// `true`. (Transitive comparability)
/// - Two elements are *incomparable* if neither is ordered before the other
/// according to the predicate. If `a` and `b` are incomparable, and `b`
/// and `c` are incomparable, then `a` and `c` are also incomparable.
/// (Transitive incomparability)
///
/// This example shows how to use the `min(by:)` method on a
/// dictionary to find the key-value pair with the lowest value.
///
/// let hues = ["Heliotrope": 296, "Coral": 16, "Aquamarine": 156]
/// let leastHue = hues.min { a, b in a.value < b.value }
/// print(leastHue)
/// // Prints "Optional(("Coral", 16))"
///
/// - Parameter areInIncreasingOrder: A predicate that returns `true`
/// if its first argument should be ordered before its second
/// argument; otherwise, `false`.
/// - Returns: The sequence's minimum element, according to
/// `areInIncreasingOrder`. If the sequence has no elements, returns
/// `nil`.
///
/// - Complexity: O(*n*), where *n* is the length of the sequence.
@inlinable // protocol-only
@warn_unqualified_access
public func min(
by areInIncreasingOrder: (Element, Element) throws -> Bool
) rethrows -> Element? {
var it = makeIterator()
guard var result = it.next() else { return nil }
while let e = it.next() {
if try areInIncreasingOrder(e, result) { result = e }
}
return result
}
/// Returns the maximum element in the sequence, using the given predicate
/// as the comparison between elements.
///
/// The predicate must be a *strict weak ordering* over the elements. That
/// is, for any elements `a`, `b`, and `c`, the following conditions must
/// hold:
///
/// - `areInIncreasingOrder(a, a)` is always `false`. (Irreflexivity)
/// - If `areInIncreasingOrder(a, b)` and `areInIncreasingOrder(b, c)` are
/// both `true`, then `areInIncreasingOrder(a, c)` is also
/// `true`. (Transitive comparability)
/// - Two elements are *incomparable* if neither is ordered before the other
/// according to the predicate. If `a` and `b` are incomparable, and `b`
/// and `c` are incomparable, then `a` and `c` are also incomparable.
/// (Transitive incomparability)
///
/// This example shows how to use the `max(by:)` method on a
/// dictionary to find the key-value pair with the highest value.
///
/// let hues = ["Heliotrope": 296, "Coral": 16, "Aquamarine": 156]
/// let greatestHue = hues.max { a, b in a.value < b.value }
/// print(greatestHue)
/// // Prints "Optional(("Heliotrope", 296))"
///
/// - Parameter areInIncreasingOrder: A predicate that returns `true` if its
/// first argument should be ordered before its second argument;
/// otherwise, `false`.
/// - Returns: The sequence's maximum element if the sequence is not empty;
/// otherwise, `nil`.
///
/// - Complexity: O(*n*), where *n* is the length of the sequence.
@inlinable // protocol-only
@warn_unqualified_access
public func max(
by areInIncreasingOrder: (Element, Element) throws -> Bool
) rethrows -> Element? {
var it = makeIterator()
guard var result = it.next() else { return nil }
while let e = it.next() {
if try areInIncreasingOrder(result, e) { result = e }
}
return result
}
}
extension Sequence where Element: Comparable {
/// Returns the minimum element in the sequence.
///
/// This example finds the smallest value in an array of height measurements.
///
/// let heights = [67.5, 65.7, 64.3, 61.1, 58.5, 60.3, 64.9]
/// let lowestHeight = heights.min()
/// print(lowestHeight)
/// // Prints "Optional(58.5)"
///
/// - Returns: The sequence's minimum element. If the sequence has no
/// elements, returns `nil`.
///
/// - Complexity: O(*n*), where *n* is the length of the sequence.
@inlinable
@warn_unqualified_access
public func min() -> Element? {
return self.min(by: <)
}
/// Returns the maximum element in the sequence.
///
/// This example finds the largest value in an array of height measurements.
///
/// let heights = [67.5, 65.7, 64.3, 61.1, 58.5, 60.3, 64.9]
/// let greatestHeight = heights.max()
/// print(greatestHeight)
/// // Prints "Optional(67.5)"
///
/// - Returns: The sequence's maximum element. If the sequence has no
/// elements, returns `nil`.
///
/// - Complexity: O(*n*), where *n* is the length of the sequence.
@inlinable
@warn_unqualified_access
public func max() -> Element? {
return self.max(by: <)
}
}
//===----------------------------------------------------------------------===//
// starts(with:)
//===----------------------------------------------------------------------===//
extension Sequence {
/// Returns a Boolean value indicating whether the initial elements of the
/// sequence are equivalent to the elements in another sequence, using
/// the given predicate as the equivalence test.
///
/// The predicate must be a *equivalence relation* over the elements. That
/// is, for any elements `a`, `b`, and `c`, the following conditions must
/// hold:
///
/// - `areEquivalent(a, a)` is always `true`. (Reflexivity)
/// - `areEquivalent(a, b)` implies `areEquivalent(b, a)`. (Symmetry)
/// - If `areEquivalent(a, b)` and `areEquivalent(b, c)` are both `true`, then
/// `areEquivalent(a, c)` is also `true`. (Transitivity)
///
/// - Parameters:
/// - possiblePrefix: A sequence to compare to this sequence.
/// - areEquivalent: A predicate that returns `true` if its two arguments
/// are equivalent; otherwise, `false`.
/// - Returns: `true` if the initial elements of the sequence are equivalent
/// to the elements of `possiblePrefix`; otherwise, `false`. If
/// `possiblePrefix` has no elements, the return value is `true`.
///
/// - Complexity: O(*m*), where *m* is the lesser of the length of the
/// sequence and the length of `possiblePrefix`.
@inlinable
public func starts<PossiblePrefix: Sequence>(
with possiblePrefix: PossiblePrefix,
by areEquivalent: (Element, PossiblePrefix.Element) throws -> Bool
) rethrows -> Bool {
var possiblePrefixIterator = possiblePrefix.makeIterator()
for e0 in self {
if let e1 = possiblePrefixIterator.next() {
if try !areEquivalent(e0, e1) {
return false
}
}
else {
return true
}
}
return possiblePrefixIterator.next() == nil
}
}
extension Sequence where Element: Equatable {
/// Returns a Boolean value indicating whether the initial elements of the
/// sequence are the same as the elements in another sequence.
///
/// This example tests whether one countable range begins with the elements
/// of another countable range.
///
/// let a = 1...3
/// let b = 1...10
///
/// print(b.starts(with: a))
/// // Prints "true"
///
/// Passing a sequence with no elements or an empty collection as
/// `possiblePrefix` always results in `true`.
///
/// print(b.starts(with: []))
/// // Prints "true"
///
/// - Parameter possiblePrefix: A sequence to compare to this sequence.
/// - Returns: `true` if the initial elements of the sequence are the same as
/// the elements of `possiblePrefix`; otherwise, `false`. If
/// `possiblePrefix` has no elements, the return value is `true`.
///
/// - Complexity: O(*m*), where *m* is the lesser of the length of the
/// sequence and the length of `possiblePrefix`.
@inlinable
public func starts<PossiblePrefix: Sequence>(
with possiblePrefix: PossiblePrefix
) -> Bool where PossiblePrefix.Element == Element {
return self.starts(with: possiblePrefix, by: ==)
}
}
//===----------------------------------------------------------------------===//
// elementsEqual()
//===----------------------------------------------------------------------===//
extension Sequence {
/// Returns a Boolean value indicating whether this sequence and another
/// sequence contain equivalent elements in the same order, using the given
/// predicate as the equivalence test.
///
/// At least one of the sequences must be finite.
///
/// The predicate must be a *equivalence relation* over the elements. That
/// is, for any elements `a`, `b`, and `c`, the following conditions must
/// hold:
///
/// - `areEquivalent(a, a)` is always `true`. (Reflexivity)
/// - `areEquivalent(a, b)` implies `areEquivalent(b, a)`. (Symmetry)
/// - If `areEquivalent(a, b)` and `areEquivalent(b, c)` are both `true`, then
/// `areEquivalent(a, c)` is also `true`. (Transitivity)
///
/// - Parameters:
/// - other: A sequence to compare to this sequence.
/// - areEquivalent: A predicate that returns `true` if its two arguments
/// are equivalent; otherwise, `false`.
/// - Returns: `true` if this sequence and `other` contain equivalent items,
/// using `areEquivalent` as the equivalence test; otherwise, `false.`
///
/// - Complexity: O(*m*), where *m* is the lesser of the length of the
/// sequence and the length of `other`.
@inlinable
public func elementsEqual<OtherSequence: Sequence>(
_ other: OtherSequence,
by areEquivalent: (Element, OtherSequence.Element) throws -> Bool
) rethrows -> Bool {
var iter1 = self.makeIterator()
var iter2 = other.makeIterator()
while true {
switch (iter1.next(), iter2.next()) {
case let (e1?, e2?):
if try !areEquivalent(e1, e2) {
return false
}
case (_?, nil), (nil, _?): return false
case (nil, nil): return true
}
}
}
}
extension Sequence where Element : Equatable {
/// Returns a Boolean value indicating whether this sequence and another
/// sequence contain the same elements in the same order.
///
/// At least one of the sequences must be finite.
///
/// This example tests whether one countable range shares the same elements
/// as another countable range and an array.
///
/// let a = 1...3
/// let b = 1...10
///
/// print(a.elementsEqual(b))
/// // Prints "false"
/// print(a.elementsEqual([1, 2, 3]))
/// // Prints "true"
///
/// - Parameter other: A sequence to compare to this sequence.
/// - Returns: `true` if this sequence and `other` contain the same elements
/// in the same order.
///
/// - Complexity: O(*m*), where *m* is the lesser of the length of the
/// sequence and the length of `other`.
@inlinable
public func elementsEqual<OtherSequence: Sequence>(
_ other: OtherSequence
) -> Bool where OtherSequence.Element == Element {
return self.elementsEqual(other, by: ==)
}
}
//===----------------------------------------------------------------------===//
// lexicographicallyPrecedes()
//===----------------------------------------------------------------------===//
extension Sequence {
/// Returns a Boolean value indicating whether the sequence precedes another
/// sequence in a lexicographical (dictionary) ordering, using the given
/// predicate to compare elements.
///
/// The predicate must be a *strict weak ordering* over the elements. That
/// is, for any elements `a`, `b`, and `c`, the following conditions must
/// hold:
///
/// - `areInIncreasingOrder(a, a)` is always `false`. (Irreflexivity)
/// - If `areInIncreasingOrder(a, b)` and `areInIncreasingOrder(b, c)` are
/// both `true`, then `areInIncreasingOrder(a, c)` is also
/// `true`. (Transitive comparability)
/// - Two elements are *incomparable* if neither is ordered before the other
/// according to the predicate. If `a` and `b` are incomparable, and `b`
/// and `c` are incomparable, then `a` and `c` are also incomparable.
/// (Transitive incomparability)
///
/// - Parameters:
/// - other: A sequence to compare to this sequence.
/// - areInIncreasingOrder: A predicate that returns `true` if its first
/// argument should be ordered before its second argument; otherwise,
/// `false`.
/// - Returns: `true` if this sequence precedes `other` in a dictionary
/// ordering as ordered by `areInIncreasingOrder`; otherwise, `false`.
///
/// - Note: This method implements the mathematical notion of lexicographical
/// ordering, which has no connection to Unicode. If you are sorting
/// strings to present to the end user, use `String` APIs that perform
/// localized comparison instead.
///
/// - Complexity: O(*m*), where *m* is the lesser of the length of the
/// sequence and the length of `other`.
@inlinable
public func lexicographicallyPrecedes<OtherSequence: Sequence>(
_ other: OtherSequence,
by areInIncreasingOrder: (Element, Element) throws -> Bool
) rethrows -> Bool
where OtherSequence.Element == Element {
var iter1 = self.makeIterator()
var iter2 = other.makeIterator()
while true {
if let e1 = iter1.next() {
if let e2 = iter2.next() {
if try areInIncreasingOrder(e1, e2) {
return true
}
if try areInIncreasingOrder(e2, e1) {
return false
}
continue // Equivalent
}
return false
}
return iter2.next() != nil
}
}
}
extension Sequence where Element : Comparable {
/// Returns a Boolean value indicating whether the sequence precedes another
/// sequence in a lexicographical (dictionary) ordering, using the
/// less-than operator (`<`) to compare elements.
///
/// This example uses the `lexicographicallyPrecedes` method to test which
/// array of integers comes first in a lexicographical ordering.
///
/// let a = [1, 2, 2, 2]
/// let b = [1, 2, 3, 4]
///
/// print(a.lexicographicallyPrecedes(b))
/// // Prints "true"
/// print(b.lexicographicallyPrecedes(b))
/// // Prints "false"
///
/// - Parameter other: A sequence to compare to this sequence.
/// - Returns: `true` if this sequence precedes `other` in a dictionary
/// ordering; otherwise, `false`.
///
/// - Note: This method implements the mathematical notion of lexicographical
/// ordering, which has no connection to Unicode. If you are sorting
/// strings to present to the end user, use `String` APIs that
/// perform localized comparison.
///
/// - Complexity: O(*m*), where *m* is the lesser of the length of the
/// sequence and the length of `other`.
@inlinable
public func lexicographicallyPrecedes<OtherSequence: Sequence>(
_ other: OtherSequence
) -> Bool where OtherSequence.Element == Element {
return self.lexicographicallyPrecedes(other, by: <)
}
}
//===----------------------------------------------------------------------===//
// contains()
//===----------------------------------------------------------------------===//
extension Sequence {
/// Returns a Boolean value indicating whether the sequence contains an
/// element that satisfies the given predicate.
///
/// You can use the predicate to check for an element of a type that
/// doesn't conform to the `Equatable` protocol, such as the
/// `HTTPResponse` enumeration in this example.
///
/// enum HTTPResponse {
/// case ok
/// case error(Int)
/// }
///
/// let lastThreeResponses: [HTTPResponse] = [.ok, .ok, .error(404)]
/// let hadError = lastThreeResponses.contains { element in
/// if case .error = element {
/// return true
/// } else {
/// return false
/// }
/// }
/// // 'hadError' == true
///
/// Alternatively, a predicate can be satisfied by a range of `Equatable`
/// elements or a general condition. This example shows how you can check an
/// array for an expense greater than $100.
///
/// let expenses = [21.37, 55.21, 9.32, 10.18, 388.77, 11.41]
/// let hasBigPurchase = expenses.contains { $0 > 100 }
/// // 'hasBigPurchase' == true
///
/// - Parameter predicate: A closure that takes an element of the sequence
/// as its argument and returns a Boolean value that indicates whether
/// the passed element represents a match.
/// - Returns: `true` if the sequence contains an element that satisfies
/// `predicate`; otherwise, `false`.
///
/// - Complexity: O(*n*), where *n* is the length of the sequence.
@inlinable
public func contains(
where predicate: (Element) throws -> Bool
) rethrows -> Bool {
for e in self {
if try predicate(e) {
return true
}
}
return false
}
/// Returns a Boolean value indicating whether every element of a sequence
/// satisfies a given predicate.
///
/// The following code uses this method to test whether all the names in an
/// array have at least five characters:
///
/// let names = ["Sofia", "Camilla", "Martina", "Mateo", "Nicolás"]
/// let allHaveAtLeastFive = names.allSatisfy({ $0.count >= 5 })
/// // allHaveAtLeastFive == true
///
/// - Parameter predicate: A closure that takes an element of the sequence
/// as its argument and returns a Boolean value that indicates whether
/// the passed element satisfies a condition.
/// - Returns: `true` if the sequence contains only elements that satisfy
/// `predicate`; otherwise, `false`.
///
/// - Complexity: O(*n*), where *n* is the length of the sequence.
@inlinable
public func allSatisfy(
_ predicate: (Element) throws -> Bool
) rethrows -> Bool {
return try !contains { try !predicate($0) }
}
}
extension Sequence where Element : Equatable {
/// Returns a Boolean value indicating whether the sequence contains the
/// given element.
///
/// This example checks to see whether a favorite actor is in an array
/// storing a movie's cast.
///
/// let cast = ["Vivien", "Marlon", "Kim", "Karl"]
/// print(cast.contains("Marlon"))
/// // Prints "true"
/// print(cast.contains("James"))
/// // Prints "false"
///
/// - Parameter element: The element to find in the sequence.
/// - Returns: `true` if the element was found in the sequence; otherwise,
/// `false`.
///
/// - Complexity: O(*n*), where *n* is the length of the sequence.
@inlinable
public func contains(_ element: Element) -> Bool {
if let result = _customContainsEquatableElement(element) {
return result
} else {
return self.contains { $0 == element }
}
}
}
//===----------------------------------------------------------------------===//
// count(where:)
//===----------------------------------------------------------------------===//
extension Sequence {
/// Returns the number of elements in the sequence that satisfy the given
/// predicate.
///
/// You can use this method to count the number of elements that pass a test.
/// The following example finds the number of names that are fewer than
/// five characters long:
///
/// let names = ["Jacqueline", "Ian", "Amy", "Juan", "Soroush", "Tiffany"]
/// let shortNameCount = names.count(where: { $0.count < 5 })
/// // shortNameCount == 3
///
/// To find the number of times a specific element appears in the sequence,
/// use the equal to operator (`==`) in the closure to test for a match.
///
/// let birds = ["duck", "duck", "duck", "duck", "goose"]
/// let duckCount = birds.count(where: { $0 == "duck" })
/// // duckCount == 4
///
/// The sequence must be finite.
///
/// - Parameter predicate: A closure that takes each element of the sequence
/// as its argument and returns a Boolean value indicating whether
/// the element should be included in the count.
/// - Returns: The number of elements in the sequence that satisfy the given
/// predicate.
@inlinable
public func count(
where predicate: (Element) throws -> Bool
) rethrows -> Int {
var count = 0
for e in self {
if try predicate(e) {
count += 1
}
}
return count
}
}
//===----------------------------------------------------------------------===//
// reduce()
//===----------------------------------------------------------------------===//
extension Sequence {
/// Returns the result of combining the elements of the sequence using the
/// given closure.
///
/// Use the `reduce(_:_:)` method to produce a single value from the elements
/// of an entire sequence. For example, you can use this method on an array
/// of numbers to find their sum or product.
///
/// The `nextPartialResult` closure is called sequentially with an
/// accumulating value initialized to `initialResult` and each element of
/// the sequence. This example shows how to find the sum of an array of
/// numbers.
///
/// let numbers = [1, 2, 3, 4]
/// let numberSum = numbers.reduce(0, { x, y in
/// x + y
/// })
/// // numberSum == 10
///
/// When `numbers.reduce(_:_:)` is called, the following steps occur:
///
/// 1. The `nextPartialResult` closure is called with `initialResult`---`0`
/// in this case---and the first element of `numbers`, returning the sum:
/// `1`.
/// 2. The closure is called again repeatedly with the previous call's return
/// value and each element of the sequence.
/// 3. When the sequence is exhausted, the last value returned from the
/// closure is returned to the caller.
///
/// If the sequence has no elements, `nextPartialResult` is never executed
/// and `initialResult` is the result of the call to `reduce(_:_:)`.
///
/// - Parameters:
/// - initialResult: The value to use as the initial accumulating value.
/// `initialResult` is passed to `nextPartialResult` the first time the
/// closure is executed.
/// - nextPartialResult: A closure that combines an accumulating value and
/// an element of the sequence into a new accumulating value, to be used
/// in the next call of the `nextPartialResult` closure or returned to
/// the caller.
/// - Returns: The final accumulated value. If the sequence has no elements,
/// the result is `initialResult`.
///
/// - Complexity: O(*n*), where *n* is the length of the sequence.
@inlinable
public func reduce<Result>(
_ initialResult: Result,
_ nextPartialResult:
(_ partialResult: Result, Element) throws -> Result
) rethrows -> Result {
var accumulator = initialResult
for element in self {
accumulator = try nextPartialResult(accumulator, element)
}
return accumulator
}
/// Returns the result of combining the elements of the sequence using the
/// given closure.
///
/// Use the `reduce(into:_:)` method to produce a single value from the
/// elements of an entire sequence. For example, you can use this method on an
/// array of integers to filter adjacent equal entries or count frequencies.
///
/// This method is preferred over `reduce(_:_:)` for efficiency when the
/// result is a copy-on-write type, for example an Array or a Dictionary.
///
/// The `updateAccumulatingResult` closure is called sequentially with a
/// mutable accumulating value initialized to `initialResult` and each element
/// of the sequence. This example shows how to build a dictionary of letter
/// frequencies of a string.
///
/// let letters = "abracadabra"
/// let letterCount = letters.reduce(into: [:]) { counts, letter in
/// counts[letter, default: 0] += 1
/// }
/// // letterCount == ["a": 5, "b": 2, "r": 2, "c": 1, "d": 1]
///
/// When `letters.reduce(into:_:)` is called, the following steps occur:
///
/// 1. The `updateAccumulatingResult` closure is called with the initial
/// accumulating value---`[:]` in this case---and the first character of
/// `letters`, modifying the accumulating value by setting `1` for the key
/// `"a"`.
/// 2. The closure is called again repeatedly with the updated accumulating
/// value and each element of the sequence.
/// 3. When the sequence is exhausted, the accumulating value is returned to
/// the caller.
///
/// If the sequence has no elements, `updateAccumulatingResult` is never
/// executed and `initialResult` is the result of the call to
/// `reduce(into:_:)`.
///
/// - Parameters:
/// - initialResult: The value to use as the initial accumulating value.
/// - updateAccumulatingResult: A closure that updates the accumulating
/// value with an element of the sequence.
/// - Returns: The final accumulated value. If the sequence has no elements,
/// the result is `initialResult`.
///
/// - Complexity: O(*n*), where *n* is the length of the sequence.
@inlinable
public func reduce<Result>(
into initialResult: __owned Result,
_ updateAccumulatingResult:
(_ partialResult: inout Result, Element) throws -> ()
) rethrows -> Result {
var accumulator = initialResult
for element in self {
try updateAccumulatingResult(&accumulator, element)
}
return accumulator
}
}
//===----------------------------------------------------------------------===//
// reversed()
//===----------------------------------------------------------------------===//
extension Sequence {
/// Returns an array containing the elements of this sequence in reverse
/// order.
///
/// The sequence must be finite.
///
/// - Returns: An array containing the elements of this sequence in
/// reverse order.
///
/// - Complexity: O(*n*), where *n* is the length of the sequence.
@inlinable
public __consuming func reversed() -> [Element] {
// FIXME(performance): optimize to 1 pass? But Array(self) can be
// optimized to a memcpy() sometimes. Those cases are usually collections,
// though.
var result = Array(self)
let count = result.count
for i in 0..<count/2 {
result.swapAt(i, count - ((i + 1) as Int))
}
return result
}
}
//===----------------------------------------------------------------------===//
// flatMap()
//===----------------------------------------------------------------------===//
extension Sequence {
/// Returns an array containing the concatenated results of calling the
/// given transformation with each element of this sequence.
///
/// Use this method to receive a single-level collection when your
/// transformation produces a sequence or collection for each element.
///
/// In this example, note the difference in the result of using `map` and
/// `flatMap` with a transformation that returns an array.
///
/// let numbers = [1, 2, 3, 4]
///
/// let mapped = numbers.map { Array(repeating: $0, count: $0) }
/// // [[1], [2, 2], [3, 3, 3], [4, 4, 4, 4]]
///
/// let flatMapped = numbers.flatMap { Array(repeating: $0, count: $0) }
/// // [1, 2, 2, 3, 3, 3, 4, 4, 4, 4]
///
/// In fact, `s.flatMap(transform)` is equivalent to
/// `Array(s.map(transform).joined())`.
///
/// - Parameter transform: A closure that accepts an element of this
/// sequence as its argument and returns a sequence or collection.
/// - Returns: The resulting flattened array.
///
/// - Complexity: O(*m* + *n*), where *n* is the length of this sequence
/// and *m* is the length of the result.
@inlinable
public func flatMap<SegmentOfResult : Sequence>(
_ transform: (Element) throws -> SegmentOfResult
) rethrows -> [SegmentOfResult.Element] {
var result: [SegmentOfResult.Element] = []
for element in self {
result.append(contentsOf: try transform(element))
}
return result
}
}
extension Sequence {
/// Returns an array containing the non-`nil` results of calling the given
/// transformation with each element of this sequence.
///
/// Use this method to receive an array of non-optional values when your
/// transformation produces an optional value.
///
/// In this example, note the difference in the result of using `map` and
/// `compactMap` with a transformation that returns an optional `Int` value.
///
/// let possibleNumbers = ["1", "2", "three", "///4///", "5"]
///
/// let mapped: [Int?] = possibleNumbers.map { str in Int(str) }
/// // [1, 2, nil, nil, 5]
///
/// let compactMapped: [Int] = possibleNumbers.compactMap { str in Int(str) }
/// // [1, 2, 5]
///
/// - Parameter transform: A closure that accepts an element of this
/// sequence as its argument and returns an optional value.
/// - Returns: An array of the non-`nil` results of calling `transform`
/// with each element of the sequence.
///
/// - Complexity: O(*m* + *n*), where *n* is the length of this sequence
/// and *m* is the length of the result.
@inlinable // protocol-only
public func compactMap<ElementOfResult>(
_ transform: (Element) throws -> ElementOfResult?
) rethrows -> [ElementOfResult] {
return try _compactMap(transform)
}
// The implementation of flatMap accepting a closure with an optional result.
// Factored out into a separate functions in order to be used in multiple
// overloads.
@inlinable // protocol-only
@inline(__always)
public func _compactMap<ElementOfResult>(
_ transform: (Element) throws -> ElementOfResult?
) rethrows -> [ElementOfResult] {
var result: [ElementOfResult] = []
for element in self {
if let newElement = try transform(element) {
result.append(newElement)
}
}
return result
}
}
| apache-2.0 | 099bbb3b9df11f10fdcd2823b5cc386b | 37.803967 | 83 | 0.60012 | 4.360168 | false | false | false | false |
sjtu-meow/iOS | Meow/Question.swift | 1 | 1035 | //
// Question.swift
// Meow
//
// Created by 林树子 on 2017/6/30.
// Copyright © 2017年 喵喵喵的伙伴. All rights reserved.
//
import SwiftyJSON
struct Question: ItemProtocol {
var id: Int!
var type: ItemType!
var profile: Profile!
var createTime: Date!
var title: String!
var content: String!
var answers: [Answer]?
var likeCount: Int!
var commentCount: Int!
}
extension Question: JSONConvertible {
static func fromJSON(_ json: JSON) -> Question? {
let item = Item.fromJSON(json)!
var question = self.init()
question.id = item.id
question.type = item.type
question.profile = item.profile
question.createTime = item.createTime
question.title <- json["title"]
question.content <- json["content"]
question.answers <- json["answers"]
question.likeCount <- json["likeCount"]
question.commentCount <- json["commentCount"]
return question
}
}
| apache-2.0 | 3923c5b4f69c27cd9950281f4e0ccd65 | 21.043478 | 53 | 0.600592 | 4.225 | false | false | false | false |
box/box-ios-sdk | Sources/Client/BoxClient.swift | 1 | 20204 | import Foundation
import os
/// Provides communication with Box APIs. Defines methods for communication with Box APIs
public class BoxClient {
/// Provides [File](../Structs/File.html) management.
public private(set) lazy var files = FilesModule(boxClient: self)
/// Provides [Folder](../Structs/Folder.html) management.
public private(set) lazy var folders = FoldersModule(boxClient: self)
/// Provides [User](../Structs/User.html) management.
public private(set) lazy var users = UsersModule(boxClient: self)
/// Provides [Group](../Structs/Group.html) management.
public private(set) lazy var groups = GroupsModule(boxClient: self)
/// Provides [Comment](../Structs/Comment.html) management.
public private(set) lazy var comments = CommentsModule(boxClient: self)
/// Provides [SharedItem](../Structs/SharedItem.html) management.
public private(set) lazy var sharedItems = SharedItemsModule(boxClient: self)
/// Web Links management.
public private(set) lazy var webLinks = WebLinksModule(boxClient: self)
/// Provides search functionality.
public private(set) lazy var search = SearchModule(boxClient: self)
/// Provides collections functionality.
public private(set) lazy var collections = CollectionsModule(boxClient: self)
/// Provides collaborations functionality.
public private(set) lazy var collaborations = CollaborationsModule(boxClient: self)
/// Provides collaborations whitelist functionality
public private(set) lazy var collaborationAllowList = CollaborationAllowlistModule(boxClient: self)
/// Metadata management.
public private(set) lazy var metadata = MetadataModule(boxClient: self)
/// Provides [Events](../Structs/Events.html) management.
public private(set) lazy var events = EventsModule(boxClient: self)
/// Metadata cascade policy.
public private(set) lazy var metadataCascadePolicy = MetadataCascadePolicyModule(boxClient: self)
/// Trash management.
public private(set) lazy var trash = TrashModule(boxClient: self)
/// Device Pin management.
public private(set) lazy var devicePins = DevicePinsModule(boxClient: self)
/// Recent Items management
public private(set) lazy var recentItems = RecentItemsModule(boxClient: self)
/// Webhooks management
public private(set) lazy var webhooks = WebhooksModule(boxClient: self)
/// Tasks management.
public private(set) lazy var tasks = TasksModule(boxClient: self)
/// Retention policy management.
public private(set) lazy var retentionPolicy = RetentionPoliciesModule(boxClient: self)
/// Provides [TermsOfService](../Structs/TermsOfService.html)
public private(set) lazy var termsOfService = TermsOfServicesModule(boxClient: self)
/// Legal Hold Policies management
public private(set) lazy var legalHolds = LegalHoldsModule(boxClient: self)
/// Storage Policies management
public private(set) lazy var storagePolicies = StoragePoliciesModule(boxClient: self)
/// Provides sign requests functionality.
public private(set) lazy var signRequests = SignRequestsModule(boxClient: self)
/// Provides file requests functionality.
public private(set) lazy var fileRequests = FileRequestsModule(boxClient: self)
/// Provides network communication with the Box APIs.
private var networkAgent: NetworkAgentProtocol
/// Provides authentication session management.
public private(set) var session: SessionProtocol
/// Requests header.
public private(set) var headers: BoxHTTPHeaders? = [:]
/// SDK request configuration.
public private(set) var configuration: BoxSDKConfiguration
/// Indicates whether this BoxClient instance has been destroyed
public private(set) var isDestroyed: Bool
/// ID of user's favorites collection.
public internal(set) var favoritesCollectionId: String?
/// Initializer
///
/// - Parameters:
/// - networkAgent: Provides network communication with the Box APIs.
/// - session: Provides authentication session management.
/// - configuration: Provides parameters to makes API calls in order to tailor it to their application's specific needs
public init(networkAgent: NetworkAgentProtocol, session: SessionProtocol, configuration: BoxSDKConfiguration) {
self.networkAgent = networkAgent
self.session = session
self.configuration = configuration
isDestroyed = false
}
/// Creates BoxClient instance based on shared link URL and password.
///
/// - Parameters:
/// - url: Shared link URL.
/// - password: Shared link password.
/// - Returns: Returns new standard BoxClient object.
public func withSharedLink(url: URL, password: String?) -> BoxClient {
let networkAgent = BoxNetworkAgent(configuration: configuration)
let client = BoxClient(networkAgent: networkAgent, session: session, configuration: configuration)
client.addSharedLinkHeader(sharedLink: url, sharedLinkPassword: password)
return client
}
/// Creates BoxClient instance based on user identifier.
///
/// - Parameter userId: User identifier.
/// - Returns: Returns new standard BoxCliennt object.
public func asUser(withId userId: String) -> BoxClient {
let networkAgent = BoxNetworkAgent(configuration: configuration)
let client = BoxClient(networkAgent: networkAgent, session: session, configuration: configuration)
client.addAsUserHeader(userId: userId)
return client
}
/// Destroys the client, revoking its access tokens and rendering it inoperable.
///
/// - Parameter completion: Called when the operation is complete.
public func destroy(completion: @escaping Callback<Void>) {
session.revokeTokens(completion: { result in
switch result {
case let .failure(error):
completion(.failure(error))
case .success:
self.isDestroyed = true
completion(.success(()))
}
})
}
/// Exchange the token.
///
/// - Parameters:
/// - scope: Scope or scopes that you want to apply to the resulting token.
/// - resource: Full url path to the file that the token should be generated for, eg: https://api.box.com/2.0/files/{file_id}
/// - sharedLink: Shared link to get a token for.
/// - completion: Returns the success or an error.
public func exchangeToken(
scope: Set<TokenScope>,
resource: String? = nil,
sharedLink: String? = nil,
completion: @escaping TokenInfoClosure
) {
session.downscopeToken(scope: scope, resource: resource, sharedLink: sharedLink, completion: completion)
}
}
extension BoxClient {
/// Makes a Box SDK request
///
/// - Parameters:
/// - request: Box SDK request
/// - completion: Returns standard BoxResponse object or error.
public func send(
request: BoxRequest,
completion: @escaping Callback<BoxResponse>
) {
guard !isDestroyed else {
completion(.failure(BoxSDKError(message: .clientDestroyed)))
return
}
session.getAccessToken { (result: Result<String, BoxSDKError>) in
switch result {
case let .failure(error):
completion(.failure(error))
return
case let .success(token):
let updatedRequest = request
updatedRequest.httpHeaders["Authorization"] = "Bearer \(token)"
updatedRequest.addBoxAPIRelatedHeaders(self.headers)
self.networkAgent.send(
request: updatedRequest,
completion: { [weak self] (result: Result<BoxResponse, BoxSDKError>) in
self?.handleAuthIssues(
result: result,
completion: completion
)
}
)
}
}
}
private func handleAuthIssues(
result: Result<BoxResponse, BoxSDKError>,
completion: @escaping Callback<BoxResponse>
) {
switch result {
case let .success(resultObj):
completion(.success(resultObj))
case let .failure(error):
if let apiError = error as? BoxAPIAuthError, apiError.message == .unauthorizedAccess {
if let tokenHandlingSession = session as? ExpiredTokenHandling {
tokenHandlingSession.handleExpiredToken(completion: { _ in completion(.failure(error)) })
return
}
}
completion(.failure(error))
}
}
private func addSharedLinkHeader(sharedLink: URL, sharedLinkPassword: String?) {
if let sharedLinkPassword = sharedLinkPassword {
headers?[BoxHTTPHeaderKey.boxApi] = "\(BoxAPIHeaderKey.sharedLink)=\(sharedLink.absoluteString)&\(BoxAPIHeaderKey.sharedLinkPassword)=\(sharedLinkPassword)"
}
else {
headers?[BoxHTTPHeaderKey.boxApi] = "\(BoxAPIHeaderKey.sharedLink)=\(sharedLink.absoluteString)"
}
}
private func addAsUserHeader(userId: String) {
headers?[BoxHTTPHeaderKey.asUser] = userId
}
}
// MARK: - BoxClientProtocol methods
extension BoxClient: BoxClientProtocol {
/// Performs an HTTP GET method call on an API endpoint and returns a response.
///
/// - Parameters:
/// - url: The URL of the API endpoint to call.
/// - httpHeaders: Additional information to be passed in the HTTP headers of the request.
/// - queryParameters: Additional parameters to be passed in the URL that is called.
/// - completion: Returns a BoxResponse object or an error if request fails
public func get(
url: URL,
httpHeaders: BoxHTTPHeaders = [:],
queryParameters: QueryParameters = [:],
completion: @escaping Callback<BoxResponse>
) {
send(
request: BoxRequest(
httpMethod: .get,
url: url,
httpHeaders: httpHeaders,
queryParams: queryParameters,
body: .empty
),
completion: completion
)
}
/// Performs an HTTP POST method call on an API endpoint and returns a response.
///
/// - Parameters:
/// - url: The URL of the API endpoint to call.
/// - httpHeaders: Additional information to be passed in the HTTP headers of the request.
/// - queryParameters: Additional parameters to be passed in the URL that is called.
/// - json: The JSON body of the request
/// - completion: Returns a BoxResponse object or an error if request fails
public func post(
url: URL,
httpHeaders: BoxHTTPHeaders = [:],
queryParameters: QueryParameters = [:],
json: Any? = nil,
completion: @escaping Callback<BoxResponse>
) {
send(
request: BoxRequest(
httpMethod: .post,
url: url,
httpHeaders: httpHeaders,
queryParams: queryParameters,
body: jsonToBody(json)
),
completion: completion
)
}
/// Performs an HTTP POST method call on an API endpoint and returns a response.
///
/// - Parameters:
/// - url: The URL of the API endpoint to call.
/// - httpHeaders: Additional information to be passed in the HTTP headers of the request.
/// - queryParameters: Additional parameters to be passed in the URL that is called.
/// - multipartBody: The multipart body of the request
/// - completion: Returns a BoxResponse object or an error if request fails
/// - Returns: BoxUploadTask
@discardableResult
public func post(
url: URL,
httpHeaders: BoxHTTPHeaders = [:],
queryParameters: QueryParameters = [:],
multipartBody: MultipartForm,
progress: @escaping (Progress) -> Void = { _ in },
completion: @escaping Callback<BoxResponse>
) -> BoxUploadTask {
let task = BoxUploadTask()
send(
request: BoxRequest(
httpMethod: .post,
url: url,
httpHeaders: httpHeaders,
queryParams: queryParameters,
body: .multipart(multipartBody),
task: task.receiveTask,
progress: progress
),
completion: completion
)
return task
}
/// Performs an HTTP PUT method call on an API endpoint and returns a response.
///
/// - Parameters:
/// - url: The URL of the API endpoint to call.
/// - httpHeaders: Additional information to be passed in the HTTP headers of the request.
/// - queryParameters: Additional parameters to be passed in the URL that is called.
/// - json: The JSON body of the request
/// - completion: Returns a BoxResponse object or an error if request fails
public func put(
url: URL,
httpHeaders: BoxHTTPHeaders = [:],
queryParameters: QueryParameters = [:],
json: Any? = nil,
completion: @escaping Callback<BoxResponse>
) {
send(
request: BoxRequest(
httpMethod: .put,
url: url,
httpHeaders: httpHeaders,
queryParams: queryParameters,
body: jsonToBody(json)
),
completion: completion
)
}
/// Performs an HTTP PUT method call on an API endpoint and returns a response.
///
/// - Parameters:
/// - url: The URL of the API endpoint to call.
/// - httpHeaders: Additional information to be passed in the HTTP headers of the request.
/// - queryParameters: Additional parameters to be passed in the URL that is called.
/// - multipartBody: The multipart body of the request
/// - completion: Returns a BoxResponse object or an error if request fails
/// - Returns: BoxUploadTask
@discardableResult
public func put(
url: URL,
httpHeaders: BoxHTTPHeaders = [:],
queryParameters: QueryParameters = [:],
multipartBody: MultipartForm,
progress: @escaping (Progress) -> Void = { _ in },
completion: @escaping Callback<BoxResponse>
) -> BoxUploadTask {
let task = BoxUploadTask()
send(
request: BoxRequest(
httpMethod: .put,
url: url,
httpHeaders: httpHeaders,
queryParams: queryParameters,
body: .multipart(multipartBody),
task: task.receiveTask,
progress: progress
),
completion: completion
)
return task
}
/// Performs an HTTP PUT method call on an API endpoint and returns a response - variant for chunked upload.
///
/// - Parameters:
/// - url: The URL of the API endpoint to call.
/// - httpHeaders: Additional information to be passed in the HTTP headers of the request.
/// - queryParameters: Additional parameters to be passed in the URL that is called.
/// - data: Binary body of the request
/// - progress: Closure where upload progress will be reported
/// - completion: Returns a BoxResponse object or an error if request fails
/// - Returns: BoxUploadTask
@discardableResult
public func put(
url: URL,
httpHeaders: BoxHTTPHeaders = [:],
queryParameters: QueryParameters = [:],
data: Data,
progress: @escaping (Progress) -> Void = { _ in },
completion: @escaping Callback<BoxResponse>
) -> BoxUploadTask {
let task = BoxUploadTask()
send(
request: BoxRequest(
httpMethod: .put,
url: url,
httpHeaders: httpHeaders,
queryParams: queryParameters,
body: .data(data),
task: task.receiveTask,
progress: progress
),
completion: completion
)
return task
}
/// Performs an HTTP OPTIONS method call on an API endpoint and returns a response.
///
/// - Parameters:
/// - url: The URL of the API endpoint to call.
/// - httpHeaders: Additional information to be passed in the HTTP headers of the request.
/// - queryParameters: Additional parameters to be passed in the URL that is called.
/// - json: The JSON body of the request
/// - completion: Returns a BoxResponse object or an error if request fails
/// - Returns: BoxNetworkTask
@discardableResult
public func options(
url: URL,
httpHeaders: BoxHTTPHeaders = [:],
queryParameters: QueryParameters = [:],
json: Any? = nil,
completion: @escaping Callback<BoxResponse>
) -> BoxNetworkTask {
let task = BoxNetworkTask()
send(
request: BoxRequest(
httpMethod: .options,
url: url,
httpHeaders: httpHeaders,
queryParams: queryParameters,
body: jsonToBody(json),
task: task.receiveTask
),
completion: completion
)
return task
}
/// Performs an HTTP DELETE method call on an API endpoint and returns a response.
///
/// - Parameters:
/// - url: The URL of the API endpoint to call.
/// - httpHeaders: Additional information to be passed in the HTTP headers of the request.
/// - queryParameters: Additional parameters to be passed in the URL that is called.
/// - completion: Returns a BoxResponse object or an error if request fails
public func delete(
url: URL,
httpHeaders: BoxHTTPHeaders = [:],
queryParameters: QueryParameters = [:],
completion: @escaping Callback<BoxResponse>
) {
send(
request: BoxRequest(
httpMethod: .delete,
url: url,
httpHeaders: httpHeaders,
queryParams: queryParameters,
body: .empty
),
completion: completion
)
}
/// Performs an HTTP GET method call for downloading on an API endpoint and returns a response.
///
/// - Parameters:
/// - url: The URL of the API endpoint to call.
/// - httpHeaders: Additional information to be passed in the HTTP headers of the request.
/// - queryParameters: Additional parameters to be passed in the URL that is called.
/// - downloadDestinationURL: The URL on disk where the data will be saved
/// - progress: Completion block to track the progress of the request
/// - completion: Returns a BoxResponse object or an error if request fails
/// - Returns: BoxDownloadTask
@discardableResult
public func download(
url: URL,
downloadDestinationURL: URL,
httpHeaders: BoxHTTPHeaders = [:],
queryParameters: QueryParameters = [:],
progress: @escaping (Progress) -> Void = { _ in },
completion: @escaping Callback<BoxResponse>
) -> BoxDownloadTask {
let task = BoxDownloadTask()
send(
request: BoxRequest(
httpMethod: .get,
url: url,
httpHeaders: httpHeaders,
queryParams: queryParameters,
downloadDestination: downloadDestinationURL,
task: task.receiveTask,
progress: progress
),
completion: completion
)
return task
}
}
private extension BoxClient {
func jsonToBody(_ json: Any?) -> BoxRequest.BodyType {
if let jsonObject = json as? [String: Any] {
return .jsonObject(jsonObject)
}
if let jsonArray = json as? [[String: Any]] {
return .jsonArray(jsonArray)
}
return .empty
}
}
| apache-2.0 | 8b4804cae954b7b99237bcc37ff4e6c4 | 39.166998 | 168 | 0.619135 | 5.188495 | false | false | false | false |
benlangmuir/swift | stdlib/public/core/Algorithm.swift | 28 | 5257 | //===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
/// Returns the lesser of two comparable values.
///
/// - Parameters:
/// - x: A value to compare.
/// - y: Another value to compare.
/// - Returns: The lesser of `x` and `y`. If `x` is equal to `y`, returns `x`.
@inlinable // protocol-only
public func min<T: Comparable>(_ x: T, _ y: T) -> T {
// In case `x == y` we pick `x`.
// This preserves any pre-existing order in case `T` has identity,
// which is important for e.g. the stability of sorting algorithms.
// `(min(x, y), max(x, y))` should return `(x, y)` in case `x == y`.
return y < x ? y : x
}
/// Returns the least argument passed.
///
/// - Parameters:
/// - x: A value to compare.
/// - y: Another value to compare.
/// - z: A third value to compare.
/// - rest: Zero or more additional values.
/// - Returns: The least of all the arguments. If there are multiple equal
/// least arguments, the result is the first one.
@inlinable // protocol-only
public func min<T: Comparable>(_ x: T, _ y: T, _ z: T, _ rest: T...) -> T {
var minValue = min(min(x, y), z)
// In case `value == minValue`, we pick `minValue`. See min(_:_:).
for value in rest where value < minValue {
minValue = value
}
return minValue
}
/// Returns the greater of two comparable values.
///
/// - Parameters:
/// - x: A value to compare.
/// - y: Another value to compare.
/// - Returns: The greater of `x` and `y`. If `x` is equal to `y`, returns `y`.
@inlinable // protocol-only
public func max<T: Comparable>(_ x: T, _ y: T) -> T {
// In case `x == y`, we pick `y`. See min(_:_:).
return y >= x ? y : x
}
/// Returns the greatest argument passed.
///
/// - Parameters:
/// - x: A value to compare.
/// - y: Another value to compare.
/// - z: A third value to compare.
/// - rest: Zero or more additional values.
/// - Returns: The greatest of all the arguments. If there are multiple equal
/// greatest arguments, the result is the last one.
@inlinable // protocol-only
public func max<T: Comparable>(_ x: T, _ y: T, _ z: T, _ rest: T...) -> T {
var maxValue = max(max(x, y), z)
// In case `value == maxValue`, we pick `value`. See min(_:_:).
for value in rest where value >= maxValue {
maxValue = value
}
return maxValue
}
/// An enumeration of the elements of a sequence or collection.
///
/// `EnumeratedSequence` is a sequence of pairs (*n*, *x*), where *n*s are
/// consecutive `Int` values starting at zero, and *x*s are the elements of a
/// base sequence.
///
/// To create an instance of `EnumeratedSequence`, call `enumerated()` on a
/// sequence or collection. The following example enumerates the elements of
/// an array.
///
/// var s = ["foo", "bar"].enumerated()
/// for (n, x) in s {
/// print("\(n): \(x)")
/// }
/// // Prints "0: foo"
/// // Prints "1: bar"
@frozen
public struct EnumeratedSequence<Base: Sequence> {
@usableFromInline
internal var _base: Base
/// Construct from a `Base` sequence.
@inlinable
internal init(_base: Base) {
self._base = _base
}
}
extension EnumeratedSequence {
/// The iterator for `EnumeratedSequence`.
///
/// An instance of this iterator wraps a base iterator and yields
/// successive `Int` values, starting at zero, along with the elements of the
/// underlying base iterator. The following example enumerates the elements of
/// an array:
///
/// var iterator = ["foo", "bar"].enumerated().makeIterator()
/// iterator.next() // (0, "foo")
/// iterator.next() // (1, "bar")
/// iterator.next() // nil
///
/// To create an instance, call
/// `enumerated().makeIterator()` on a sequence or collection.
@frozen
public struct Iterator {
@usableFromInline
internal var _base: Base.Iterator
@usableFromInline
internal var _count: Int
/// Construct from a `Base` iterator.
@inlinable
internal init(_base: Base.Iterator) {
self._base = _base
self._count = 0
}
}
}
extension EnumeratedSequence.Iterator: IteratorProtocol, Sequence {
/// The type of element returned by `next()`.
public typealias Element = (offset: Int, element: Base.Element)
/// Advances to the next element and returns it, or `nil` if no next element
/// exists.
///
/// Once `nil` has been returned, all subsequent calls return `nil`.
@inlinable
public mutating func next() -> Element? {
guard let b = _base.next() else { return nil }
let result = (offset: _count, element: b)
_count += 1
return result
}
}
extension EnumeratedSequence: Sequence {
/// Returns an iterator over the elements of this sequence.
@inlinable
public __consuming func makeIterator() -> Iterator {
return Iterator(_base: _base.makeIterator())
}
}
| apache-2.0 | 3fcb6846f71a8b0d326e116da7cf869e | 31.85625 | 80 | 0.610614 | 3.795668 | false | false | false | false |
BENMESSAOUD/yousign | YouSign/YouSign/Extensions/Node+Extension.swift | 1 | 1197 | //
// Node+Extension.swift
// YouSign
//
// Created by Mahmoud Ben Messaoud on 31/05/2017.
// Copyright © 2017 Mahmoud Ben Messaoud. All rights reserved.
//
import Foundation
extension Node {
var stringAttribute: String {
var result = kEmptyString
guard let allAttribute = self.attributes else {
return result
}
for (key, value) in allAttribute {
result.append(" \(key)=\(value)")
}
return result
}
var xml: String {
var result = kEmptyString
if (self.childs == nil && self.values == nil) {
result.append("<\(self.name)")
result.append("\(self.stringAttribute)/>")
return result
}
result.append("<\(self.name)")
result.append("\(self.stringAttribute)>")
if let allValues = self.values {
for (key, value) in allValues {
result.append("<\(key)>\(value)</\(key)>")
}
}
if let nodes = self.childs {
for node in nodes {
result.append(node.xml)
}
}
result.append("</\(self.name)>")
return result
}
}
| apache-2.0 | ae523efc87f0a15841249d8e2b1130a9 | 23.916667 | 63 | 0.518395 | 4.547529 | false | false | false | false |
apple/swift-nio-http2 | Tests/NIOHTTP2Tests/SimpleClientServerFramePayloadStreamTests.swift | 1 | 112393 | //===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftNIO open source project
//
// Copyright (c) 2017-2021 Apple Inc. and the SwiftNIO project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
import XCTest
import NIOCore
import NIOEmbedded
import NIOHPACK
@testable import NIOHTTP2
/// A channel handler that passes writes through but fires EOF once the first one hits.
final class EOFOnWriteHandler: ChannelOutboundHandler {
typealias OutboundIn = Any
typealias OutboundOut = Any
enum InactiveType {
case halfClose
case fullClose
case doNothing
}
private var type: InactiveType
init(type: InactiveType) {
assert(type != .doNothing)
self.type = type
}
func write(context: ChannelHandlerContext, data: NIOAny, promise: EventLoopPromise<Void>?) {
switch self.type {
case .halfClose:
context.fireUserInboundEventTriggered(ChannelEvent.inputClosed)
case .fullClose:
context.fireChannelInactive()
case .doNothing:
break
}
self.type = .doNothing
}
}
/// Emits a write to the channel the first time a write is received at this point of the pipeline.
final class WriteOnWriteHandler: ChannelOutboundHandler {
typealias OutboundIn = Any
typealias OutboundOut = Any
private var written = false
private let frame: HTTP2Frame
private let writePromise: EventLoopPromise<Void>
init(frame: HTTP2Frame, promise: EventLoopPromise<Void>) {
self.frame = frame
self.writePromise = promise
}
func write(context: ChannelHandlerContext, data: NIOAny, promise: EventLoopPromise<Void>?) {
if !self.written {
self.written = true
context.channel.write(self.frame, promise: self.writePromise)
}
context.write(data, promise: promise)
}
}
/// A channel handler that verifies that we never send flushes
/// for no reason.
final class NoEmptyFlushesHandler: ChannelOutboundHandler {
typealias OutboundIn = Any
typealias OutboundOut = Any
var writeCount = 0
func write(context: ChannelHandlerContext, data: NIOAny, promise: EventLoopPromise<Void>?) {
self.writeCount += 1
context.write(data, promise: promise)
}
func flush(context: ChannelHandlerContext) {
XCTAssertGreaterThan(self.writeCount, 0)
self.writeCount = 0
}
}
/// A channel handler that forcibly resets all inbound HEADERS frames it receives.
final class InstaResetHandler: ChannelInboundHandler {
typealias InboundIn = HTTP2Frame
typealias OutboundOut = HTTP2Frame
func channelRead(context: ChannelHandlerContext, data: NIOAny) {
let frame = self.unwrapInboundIn(data)
if case .headers = frame.payload {
let kaboomFrame = HTTP2Frame(streamID: frame.streamID, payload: .rstStream(.refusedStream))
context.writeAndFlush(self.wrapOutboundOut(kaboomFrame), promise: nil)
}
}
}
/// A channel handler that forcibly sends GOAWAY when it receives the first HEADERS frame.
final class InstaGoawayHandler: ChannelInboundHandler {
typealias InboundIn = HTTP2Frame
typealias OutboundOut = HTTP2Frame
func channelRead(context: ChannelHandlerContext, data: NIOAny) {
let frame = self.unwrapInboundIn(data)
if case .headers = frame.payload {
let kaboomFrame = HTTP2Frame(streamID: .rootStream, payload: .goAway(lastStreamID: .rootStream, errorCode: .inadequateSecurity, opaqueData: nil))
context.writeAndFlush(self.wrapOutboundOut(kaboomFrame), promise: nil)
}
}
}
/// A simple channel handler that records all user events.
final class UserEventRecorder: ChannelInboundHandler {
typealias InboundIn = HTTP2Frame
var events: [Any] = []
func userInboundEventTriggered(context: ChannelHandlerContext, event: Any) {
events.append(event)
}
}
/// A simple channel handler that enforces that stream closed events fire after the
/// frame is dispatched, not before.
final class ClosedEventVsFrameOrderingHandler: ChannelInboundHandler {
typealias InboundIn = HTTP2Frame
var seenFrame = false
var seenEvent = false
let targetStreamID: HTTP2StreamID
init(targetStreamID: HTTP2StreamID) {
self.targetStreamID = targetStreamID
}
func channelRead(context: ChannelHandlerContext, data: NIOAny) {
let frame = self.unwrapInboundIn(data)
switch (frame.payload, frame.streamID) {
case (.rstStream, self.targetStreamID),
(.goAway(_, _, _), .rootStream):
XCTAssertFalse(self.seenFrame)
XCTAssertFalse(self.seenEvent)
self.seenFrame = true
default:
break
}
context.fireChannelRead(data)
}
func userInboundEventTriggered(context: ChannelHandlerContext, event: Any) {
guard let evt = event as? StreamClosedEvent, evt.streamID == self.targetStreamID else {
return
}
XCTAssertTrue(self.seenFrame)
XCTAssertFalse(self.seenEvent)
self.seenEvent = true
}
}
/// A simple channel handler that adds the NIOHTTP2Handler handler dynamically
/// after a read event has been triggered.
class HTTP2ParserProxyHandler: ChannelInboundHandler, RemovableChannelHandler {
typealias InboundIn = ByteBuffer
func channelRead(context: ChannelHandlerContext, data: NIOAny) {
XCTAssertNoThrow(try context.pipeline.addHandler(
NIOHTTP2Handler(mode: .server)).wait())
context.fireChannelRead(data)
_ = context.pipeline.removeHandler(context: context)
}
}
class SimpleClientServerFramePayloadStreamTests: XCTestCase {
var clientChannel: EmbeddedChannel!
var serverChannel: EmbeddedChannel!
override func setUp() {
self.clientChannel = EmbeddedChannel()
self.serverChannel = EmbeddedChannel()
}
override func tearDown() {
self.clientChannel = nil
self.serverChannel = nil
}
/// Establish a basic HTTP/2 connection.
func basicHTTP2Connection(clientSettings: HTTP2Settings = nioDefaultSettings,
serverSettings: HTTP2Settings = nioDefaultSettings,
maximumBufferedControlFrames: Int = 10000,
withMultiplexerCallback multiplexerCallback: ((Channel) -> EventLoopFuture<Void>)? = nil) throws {
XCTAssertNoThrow(try self.clientChannel.pipeline.addHandler(NIOHTTP2Handler(mode: .client,
initialSettings: clientSettings,
maximumBufferedControlFrames: maximumBufferedControlFrames)).wait())
XCTAssertNoThrow(try self.serverChannel.pipeline.addHandler(NIOHTTP2Handler(mode: .server,
initialSettings: serverSettings,
maximumBufferedControlFrames: maximumBufferedControlFrames)).wait())
if let multiplexerCallback = multiplexerCallback {
XCTAssertNoThrow(try self.clientChannel.pipeline.addHandler(HTTP2StreamMultiplexer(mode: .client,
channel: self.clientChannel,
inboundStreamInitializer: multiplexerCallback)).wait())
XCTAssertNoThrow(try self.serverChannel.pipeline.addHandler(HTTP2StreamMultiplexer(mode: .server,
channel: self.serverChannel,
inboundStreamInitializer: multiplexerCallback)).wait())
}
try self.assertDoHandshake(client: self.clientChannel, server: self.serverChannel,
clientSettings: clientSettings, serverSettings: serverSettings)
}
/// Establish a basic HTTP/2 connection where the HTTP2Parser handler is added after the channel has been activated.
func basicHTTP2DynamicPipelineConnection() throws {
XCTAssertNoThrow(try self.clientChannel.pipeline.addHandler(NIOHTTP2Handler(mode: .client)).wait())
XCTAssertNoThrow(try self.serverChannel.pipeline.addHandler(HTTP2ParserProxyHandler()).wait())
try self.assertDoHandshake(client: self.clientChannel, server: self.serverChannel)
}
func testBasicRequestResponse() throws {
// Begin by getting the connection up.
try self.basicHTTP2Connection()
// We're now going to try to send a request from the client to the server.
let headers = HPACKHeaders([(":path", "/"), (":method", "POST"), (":scheme", "https"), (":authority", "localhost")])
var requestBody = self.clientChannel.allocator.buffer(capacity: 128)
requestBody.writeStaticString("A simple HTTP/2 request.")
let clientStreamID = HTTP2StreamID(1)
let reqFrame = HTTP2Frame(streamID: clientStreamID, payload: .headers(.init(headers: headers)))
let reqBodyFrame = HTTP2Frame(streamID: clientStreamID, payload: .data(.init(data: .byteBuffer(requestBody), endStream: true)))
let serverStreamID = try self.assertFramesRoundTrip(frames: [reqFrame, reqBodyFrame], sender: self.clientChannel, receiver: self.serverChannel).first!.streamID
// Let's send a quick response back.
let responseHeaders = HPACKHeaders([(":status", "200"), ("content-length", "0")])
let respFrame = HTTP2Frame(streamID: serverStreamID, payload: .headers(.init(headers: responseHeaders, endStream: true)))
try self.assertFramesRoundTrip(frames: [respFrame], sender: self.serverChannel, receiver: self.clientChannel)
XCTAssertNoThrow(try self.clientChannel.finish())
XCTAssertNoThrow(try self.serverChannel.finish())
}
func testBasicRequestResponseWithDynamicPipeline() throws {
// Begin by getting the connection up.
try self.basicHTTP2DynamicPipelineConnection()
// We're now going to try to send a request from the client to the server.
let headers = HPACKHeaders([(":path", "/"), (":method", "POST"), (":scheme", "https"), (":authority", "localhost")])
var requestBody = self.clientChannel.allocator.buffer(capacity: 128)
requestBody.writeStaticString("A simple HTTP/2 request.")
let clientStreamID = HTTP2StreamID(1)
let reqFrame = HTTP2Frame(streamID: clientStreamID, payload: .headers(.init(headers: headers)))
let reqBodyFrame = HTTP2Frame(streamID: clientStreamID, payload: .data(.init(data: .byteBuffer(requestBody), endStream: true)))
let serverStreamID = try self.assertFramesRoundTrip(frames: [reqFrame, reqBodyFrame], sender: self.clientChannel, receiver: self.serverChannel).first!.streamID
// Let's send a quick response back.
let responseHeaders = HPACKHeaders([(":status", "200"), ("content-length", "0")])
let respFrame = HTTP2Frame(streamID: serverStreamID, payload: .headers(.init(headers: responseHeaders, endStream: true)))
try self.assertFramesRoundTrip(frames: [respFrame], sender: self.serverChannel, receiver: self.clientChannel)
XCTAssertNoThrow(try self.clientChannel.finish())
XCTAssertNoThrow(try self.serverChannel.finish())
}
func testManyRequestsAtOnce() throws {
// Begin by getting the connection up.
try self.basicHTTP2Connection()
let requestHeaders = HPACKHeaders([(":path", "/"), (":method", "POST"), (":scheme", "https"), (":authority", "localhost")])
var requestBody = self.clientChannel.allocator.buffer(capacity: 128)
requestBody.writeStaticString("A simple HTTP/2 request.")
// We're going to send three requests before we flush.
var clientStreamIDs = [HTTP2StreamID]()
var headersFrames = [HTTP2Frame]()
var bodyFrames = [HTTP2Frame]()
for id in [1, 3, 5] {
let streamID = HTTP2StreamID(id)
let reqFrame = HTTP2Frame(streamID: streamID, payload: .headers(.init(headers: requestHeaders)))
let reqBodyFrame = HTTP2Frame(streamID: streamID, payload: .data(.init(data: .byteBuffer(requestBody), endStream: true)))
self.clientChannel.write(reqFrame, promise: nil)
self.clientChannel.write(reqBodyFrame, promise: nil)
clientStreamIDs.append(streamID)
headersFrames.append(reqFrame)
bodyFrames.append(reqBodyFrame)
}
self.clientChannel.flush()
self.interactInMemory(self.clientChannel, self.serverChannel)
// We receive the headers frames first, and then the body frames. Additionally, the
// body frames come in no particular order, so we need to guard against that.
for frame in headersFrames {
let receivedFrame = try self.serverChannel.assertReceivedFrame()
receivedFrame.assertFrameMatches(this: frame)
}
var receivedBodyFrames: [HTTP2Frame] = try assertNoThrowWithValue((0..<bodyFrames.count).map { _ in try self.serverChannel.assertReceivedFrame() })
receivedBodyFrames.sort(by: { $0.streamID < $1.streamID })
receivedBodyFrames.assertFramesMatch(bodyFrames)
// There should be no frames here.
self.clientChannel.assertNoFramesReceived()
self.serverChannel.assertNoFramesReceived()
XCTAssertNoThrow(try self.clientChannel.finish())
XCTAssertNoThrow(try self.serverChannel.finish())
}
func testNothingButGoaway() throws {
// A simple connection with a goaway should be no big deal.
try self.basicHTTP2Connection()
let goAwayFrame = HTTP2Frame(streamID: .rootStream, payload: .goAway(lastStreamID: .rootStream, errorCode: .noError, opaqueData: nil))
self.clientChannel.writeAndFlush(goAwayFrame, promise: nil)
self.interactInMemory(self.clientChannel, self.serverChannel)
// The server should have received a GOAWAY. Nothing else should have happened.
let receivedGoawayFrame = try self.serverChannel.assertReceivedFrame()
receivedGoawayFrame.assertFrameMatches(this: goAwayFrame)
// Send the GOAWAY back to the client. Should be safe.
self.serverChannel.writeAndFlush(goAwayFrame, promise: nil)
self.interactInMemory(self.clientChannel, self.serverChannel)
// In some nghttp2 versions the client will receive a GOAWAY, in others
// it will not. There is no meaningful assertion to apply here.
// All should be good.
self.serverChannel.assertNoFramesReceived()
XCTAssertNoThrow(try self.clientChannel.finish())
XCTAssertNoThrow(try self.serverChannel.finish())
}
func testGoAwayWithStreamsUpQuiescing() throws {
// A simple connection with a goaway should be no big deal.
try self.basicHTTP2Connection()
// We're going to send a HEADERS frame from the client to the server.
let headers = HPACKHeaders([(":path", "/"), (":method", "POST"), (":scheme", "https"), (":authority", "localhost")])
let clientStreamID = HTTP2StreamID(1)
let reqFrame = HTTP2Frame(streamID: clientStreamID, payload: .headers(.init(headers: headers)))
let serverStreamID = try self.assertFramesRoundTrip(frames: [reqFrame], sender: self.clientChannel, receiver: self.serverChannel).first!.streamID
// Now the server is going to send a GOAWAY frame with the maximum stream ID. This should quiesce the connection:
// futher frames on stream 1 are allowed, but nothing else.
let serverGoaway = HTTP2Frame(streamID: .rootStream, payload: .goAway(lastStreamID: .maxID, errorCode: .noError, opaqueData: nil))
try self.assertFramesRoundTrip(frames: [serverGoaway], sender: self.serverChannel, receiver: self.clientChannel)
// We should still be able to send DATA frames on stream 1 now.
var requestBody = self.clientChannel.allocator.buffer(capacity: 128)
requestBody.writeStaticString("A simple HTTP/2 request.")
let reqBodyFrame = HTTP2Frame(streamID: clientStreamID, payload: .data(.init(data: .byteBuffer(requestBody), endStream: true)))
try self.assertFramesRoundTrip(frames: [reqBodyFrame], sender: self.clientChannel, receiver: self.serverChannel)
// The server will respond, closing this stream.
let responseHeaders = HPACKHeaders([(":status", "200"), ("content-length", "0")])
let respFrame = HTTP2Frame(streamID: serverStreamID, payload: .headers(.init(headers: responseHeaders, endStream: true)))
try self.assertFramesRoundTrip(frames: [respFrame], sender: self.serverChannel, receiver: self.clientChannel)
// The server can now GOAWAY down to stream 1. We evaluate the bytes here ourselves becuase the client won't see this frame.
let secondServerGoaway = HTTP2Frame(streamID: .rootStream, payload: .goAway(lastStreamID: serverStreamID, errorCode: .noError, opaqueData: nil))
self.serverChannel.writeAndFlush(secondServerGoaway, promise: nil)
guard case .some(.byteBuffer(let bytes)) = try assertNoThrowWithValue(self.serverChannel.readOutbound(as: IOData.self)) else {
XCTFail("No data sent from server")
return
}
// A GOAWAY frame (type 7, 8 bytes long, no flags, on stream 0), with error code 0 and last stream ID 1.
let expectedFrameBytes: [UInt8] = [0, 0, 8, 7, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0]
XCTAssertEqual(bytes.getBytes(at: bytes.readerIndex, length: bytes.readableBytes)!, expectedFrameBytes)
// At this stage, everything is shut down.
self.clientChannel.assertNoFramesReceived()
self.serverChannel.assertNoFramesReceived()
XCTAssertNoThrow(try self.clientChannel.finish())
XCTAssertNoThrow(try self.serverChannel.finish())
}
func testLargeDataFramesAreSplit() throws {
// Big DATA frames get split up.
try self.basicHTTP2Connection()
// Start by opening the stream.
let headers = HPACKHeaders([(":path", "/"), (":method", "POST"), (":scheme", "https"), (":authority", "localhost")])
let clientStreamID = HTTP2StreamID(1)
let reqFrame = HTTP2Frame(streamID: clientStreamID, payload: .headers(.init(headers: headers)))
let serverStreamID = try self.assertFramesRoundTrip(frames: [reqFrame], sender: self.clientChannel, receiver: self.serverChannel).first!.streamID
// Confirm there's no bonus frame sitting around.
self.clientChannel.assertNoFramesReceived()
self.serverChannel.assertNoFramesReceived()
// Now we're going to send in a frame that's just a bit larger than the max frame size of 1<<14.
let frameSize = (1<<14) + 8
var buffer = self.clientChannel.allocator.buffer(capacity: frameSize)
/// To write this in as fast as possible, we're going to fill the buffer one int at a time.
for val in (0..<(frameSize / MemoryLayout<Int>.size)) {
buffer.writeInteger(val)
}
// Now we'll try to send this in a DATA frame.
let dataFrame = HTTP2Frame(streamID: clientStreamID, payload: .data(.init(data: .byteBuffer(buffer), endStream: true)))
self.clientChannel.writeAndFlush(dataFrame, promise: nil)
self.interactInMemory(self.clientChannel, self.serverChannel)
// This should have produced two frames in the server. Both are DATA, one is max frame size and the other
// is not.
let firstFrame = try self.serverChannel.assertReceivedFrame()
firstFrame.assertDataFrame(endStream: false, streamID: serverStreamID, payload: buffer.getSlice(at: 0, length: 1<<14)!)
let secondFrame = try self.serverChannel.assertReceivedFrame()
secondFrame.assertDataFrame(endStream: true, streamID: serverStreamID, payload: buffer.getSlice(at: 1<<14, length: 8)!)
// The client should have got nothing.
self.clientChannel.assertNoFramesReceived()
// Now send a response from the server and shut things down.
let responseHeaders = HPACKHeaders([(":status", "200"), ("content-length", "0")])
let respFrame = HTTP2Frame(streamID: serverStreamID, payload: .headers(.init(headers: responseHeaders, endStream: true)))
try self.assertFramesRoundTrip(frames: [respFrame], sender: self.serverChannel, receiver: self.clientChannel)
XCTAssertNoThrow(try self.clientChannel.finish())
XCTAssertNoThrow(try self.serverChannel.finish())
}
func testSendingDataFrameWithSmallFile() throws {
// Begin by getting the connection up.
try self.basicHTTP2Connection()
// We're now going to try to send a request from the client to the server with a file region for the body.
let bodyContent = "Hello world, this is data from a file!"
try withTemporaryFile(content: bodyContent) { (handle, path) in
let region = try FileRegion(fileHandle: handle)
let headers = HPACKHeaders([(":path", "/"), (":method", "POST"), (":scheme", "https"), (":authority", "localhost")])
let clientStreamID = HTTP2StreamID(1)
let reqFrame = HTTP2Frame(streamID: clientStreamID, payload: .headers(.init(headers: headers)))
let reqBodyFrame = HTTP2Frame(streamID: clientStreamID, payload: .data(.init(data: .fileRegion(region), endStream: true)))
let serverStreamID = try self.assertFramesRoundTrip(frames: [reqFrame, reqBodyFrame], sender: self.clientChannel, receiver: self.serverChannel).first!.streamID
// Let's send a quick response back.
let responseHeaders = HPACKHeaders([(":status", "200"), ("content-length", "0")])
let respFrame = HTTP2Frame(streamID: serverStreamID, payload: .headers(.init(headers: responseHeaders, endStream: true)))
try self.assertFramesRoundTrip(frames: [respFrame], sender: self.serverChannel, receiver: self.clientChannel)
}
XCTAssertNoThrow(try self.clientChannel.finish())
XCTAssertNoThrow(try self.serverChannel.finish())
}
func testSendingDataFrameWithLargeFile() throws {
// Begin by getting the connection up.
// We add the stream multiplexer because it'll emit WINDOW_UPDATE frames, which we need.
let serverHandler = InboundFramePayloadRecorder()
try self.basicHTTP2Connection() { channel in
return channel.pipeline.addHandler(serverHandler)
}
// We're going to create a largish temp file: 3 data frames in size.
var bodyData = self.clientChannel.allocator.buffer(capacity: 1<<14)
for val in (0..<((1<<14) / MemoryLayout<Int>.size)) {
bodyData.writeInteger(val)
}
try withTemporaryFile { (handle, path) in
for _ in (0..<3) {
handle.appendBuffer(bodyData)
}
let region = try FileRegion(fileHandle: handle)
let clientHandler = InboundFramePayloadRecorder()
let childChannelPromise = self.clientChannel.eventLoop.makePromise(of: Channel.self)
try (self.clientChannel.pipeline.context(handlerType: HTTP2StreamMultiplexer.self).wait().handler as! HTTP2StreamMultiplexer).createStreamChannel(promise: childChannelPromise) { channel in
return channel.pipeline.addHandler(clientHandler)
}
(self.clientChannel.eventLoop as! EmbeddedEventLoop).run()
let childChannel = try childChannelPromise.futureResult.wait()
// Start by sending the headers.
let headers = HPACKHeaders([(":path", "/"), (":method", "POST"), (":scheme", "https"), (":authority", "localhost")])
let reqFrame = HTTP2Frame.FramePayload.headers(.init(headers: headers))
childChannel.writeAndFlush(reqFrame, promise: nil)
self.interactInMemory(self.clientChannel, self.serverChannel)
serverHandler.receivedFrames.assertFramePayloadsMatch([reqFrame])
self.clientChannel.assertNoFramesReceived()
self.serverChannel.assertNoFramesReceived()
// Ok, we're gonna send the body here.
let reqBodyFrame = HTTP2Frame.FramePayload.data(.init(data: .fileRegion(region), endStream: true))
childChannel.writeAndFlush(reqBodyFrame, promise: nil)
self.interactInMemory(self.clientChannel, self.serverChannel)
// We now expect 3 frames.
let dataFrames = (0..<3).map { idx in HTTP2Frame.FramePayload.data(.init(data: .byteBuffer(bodyData), endStream: idx == 2)) }
serverHandler.receivedFrames.assertFramePayloadsMatch([reqFrame] + dataFrames)
// The client will have seen a pair of window updates: one on the connection, one on the stream.
try self.clientChannel.assertReceivedFrame().assertWindowUpdateFrame(streamID: 0, windowIncrement: 32768)
clientHandler.receivedFrames.assertFramePayloadsMatch([HTTP2Frame.FramePayload.windowUpdate(windowSizeIncrement: 32768)])
// No frames left.
self.clientChannel.assertNoFramesReceived()
self.serverChannel.assertNoFramesReceived()
}
XCTAssertNoThrow(try self.clientChannel.finish())
XCTAssertNoThrow(try self.serverChannel.finish())
}
func testMoreRequestsThanMaxConcurrentStreamsAtOnce() throws {
// Begin by getting the connection up.
try self.basicHTTP2Connection()
let requestHeaders = HPACKHeaders([(":path", "/"), (":method", "POST"), (":scheme", "https"), (":authority", "localhost")])
var requestBody = self.clientChannel.allocator.buffer(capacity: 128)
requestBody.writeStaticString("A simple HTTP/2 request.")
// We're going to send 101 requests before we flush.
var clientStreamIDs = [HTTP2StreamID]()
var serverStreamIDs = [HTTP2StreamID]()
var headersFrames = [HTTP2Frame]()
for id in stride(from: 1, through: 201, by: 2) {
let streamID = HTTP2StreamID(id)
let reqFrame = HTTP2Frame(streamID: streamID, payload: .headers(.init(headers: requestHeaders)))
self.clientChannel.write(reqFrame, promise: nil)
clientStreamIDs.append(streamID)
headersFrames.append(reqFrame)
}
self.clientChannel.flush()
self.interactInMemory(self.clientChannel, self.serverChannel)
// We expect to see the first 100 headers frames, but nothing more.
for frame in headersFrames.dropLast() {
let receivedFrame = try self.serverChannel.assertReceivedFrame()
receivedFrame.assertFrameMatches(this: frame)
serverStreamIDs.append(receivedFrame.streamID)
}
// There should be no frames here.
self.clientChannel.assertNoFramesReceived()
self.serverChannel.assertNoFramesReceived()
// Let's complete one of the streams by sending data for the first stream on the client, and responding on the server.
let dataFrame = HTTP2Frame(streamID: clientStreamIDs.first!, payload: .data(.init(data: .byteBuffer(requestBody), endStream: true)))
self.clientChannel.writeAndFlush(dataFrame, promise: nil)
let responseHeaders = HPACKHeaders([(":status", "200"), ("content-length", "0")])
let respFrame = HTTP2Frame(streamID: serverStreamIDs.first!, payload: .headers(.init(headers :responseHeaders, endStream: true)))
self.serverChannel.writeAndFlush(respFrame, promise: nil)
// Now we expect the following things to have happened: 1) the client will have seen the server's response,
// 2) the server will have seen the END_STREAM, and 3) the server will have seen another request, making
// 101.
self.interactInMemory(self.clientChannel, self.serverChannel)
try self.clientChannel.assertReceivedFrame().assertFrameMatches(this: respFrame)
try self.serverChannel.assertReceivedFrame().assertFrameMatches(this: dataFrame)
try self.serverChannel.assertReceivedFrame().assertFrameMatches(this: headersFrames.last!)
// There should be no frames here.
self.clientChannel.assertNoFramesReceived()
self.serverChannel.assertNoFramesReceived()
// No need to bother cleaning this up.
XCTAssertNoThrow(try self.clientChannel.finish())
XCTAssertNoThrow(try self.serverChannel.finish())
}
func testOverridingDefaultSettings() throws {
let initialSettings = [
HTTP2Setting(parameter: .maxHeaderListSize, value: 1000),
HTTP2Setting(parameter: .initialWindowSize, value: 100),
HTTP2Setting(parameter: .enablePush, value: 0)
]
XCTAssertNoThrow(try self.clientChannel.pipeline.addHandler(NIOHTTP2Handler(mode: .client, initialSettings: initialSettings)).wait())
XCTAssertNoThrow(try self.serverChannel.pipeline.addHandler(NIOHTTP2Handler(mode: .server)).wait())
try self.assertDoHandshake(client: self.clientChannel, server: self.serverChannel, clientSettings: initialSettings)
// There should be no frames here.
self.clientChannel.assertNoFramesReceived()
self.serverChannel.assertNoFramesReceived()
// No need to bother cleaning this up.
XCTAssertNoThrow(try self.clientChannel.finish())
XCTAssertNoThrow(try self.serverChannel.finish())
}
func testBasicPingFrames() throws {
// Begin by getting the connection up.
try self.basicHTTP2Connection()
// Let's try sending a ping frame.
let pingData = HTTP2PingData(withInteger: 6000)
let pingFrame = HTTP2Frame(streamID: .rootStream, payload: .ping(pingData, ack: false))
self.clientChannel.writeAndFlush(pingFrame, promise: nil)
self.interactInMemory(self.clientChannel, self.serverChannel)
let receivedPingFrame = try self.serverChannel.assertReceivedFrame()
receivedPingFrame.assertFrameMatches(this: pingFrame)
// The client should also see an automatic response without server action.
let receivedFrame = try self.clientChannel.assertReceivedFrame()
receivedFrame.assertPingFrame(ack: true, opaqueData: pingData)
// Clean up
self.clientChannel.assertNoFramesReceived()
self.serverChannel.assertNoFramesReceived()
XCTAssertNoThrow(try self.clientChannel.finish())
XCTAssertNoThrow(try self.serverChannel.finish())
}
func testAutomaticFlowControl() throws {
// Begin by getting the connection up.
// We add the stream multiplexer here because it manages automatic flow control.
try self.basicHTTP2Connection() { channel in
return channel.eventLoop.makeSucceededFuture(())
}
// Now we're going to send a request, including a very large body: 65536 bytes in size. To avoid spending too much
// time initializing buffers, we're going to send the same 1kB data frame 64 times.
let headers = HPACKHeaders([(":path", "/"), (":method", "POST"), (":scheme", "https"), (":authority", "localhost")])
var requestBody = self.clientChannel.allocator.buffer(capacity: 1024)
requestBody.writeBytes(Array(repeating: UInt8(0x04), count: 1024))
// We're going to open a stream and queue up the frames for that stream.
let handler = try self.clientChannel.pipeline.context(handlerType: HTTP2StreamMultiplexer.self).wait().handler as! HTTP2StreamMultiplexer
let childHandler = InboundFramePayloadRecorder()
handler.createStreamChannel(promise: nil) { channel in
let reqFramePayload = HTTP2Frame.FramePayload.headers(.init(headers: headers))
channel.write(reqFramePayload, promise: nil)
// Now prepare the large body.
var reqBodyFramePayload = HTTP2Frame.FramePayload.data(.init(data: .byteBuffer(requestBody)))
for _ in 0..<63 {
channel.write(reqBodyFramePayload, promise: nil)
}
reqBodyFramePayload = .data(.init(data: .byteBuffer(requestBody), endStream: true))
channel.writeAndFlush(reqBodyFramePayload, promise: nil)
return channel.pipeline.addHandler(childHandler)
}
(self.clientChannel.eventLoop as! EmbeddedEventLoop).run()
// Ok, we now want to send this data to the server.
self.interactInMemory(self.clientChannel, self.serverChannel)
// We should also see 4 window update frames on the client side: two for the stream, two for the connection.
try self.clientChannel.assertReceivedFrame().assertWindowUpdateFrame(streamID: 0, windowIncrement: 32768)
try self.clientChannel.assertReceivedFrame().assertWindowUpdateFrame(streamID: 0, windowIncrement: 32768)
let expectedChildFrames = [HTTP2Frame.FramePayload.windowUpdate(windowSizeIncrement: 32768)]
childHandler.receivedFrames.assertFramePayloadsMatch(expectedChildFrames)
// No other frames should be emitted, though the server may have many.
self.clientChannel.assertNoFramesReceived()
XCTAssertNoThrow(try self.clientChannel.finish())
XCTAssertNoThrow(try self.serverChannel.finish())
}
func testPartialFrame() throws {
// Begin by getting the connection up.
try self.basicHTTP2Connection()
// We want to test whether partial frames are well-handled. We do that by just faking up a PING frame and sending it in two halves.
var pingBuffer = self.serverChannel.allocator.buffer(capacity: 17)
pingBuffer.writeInteger(UInt16(0))
pingBuffer.writeInteger(UInt8(8))
pingBuffer.writeInteger(UInt8(6))
pingBuffer.writeInteger(UInt8(0))
pingBuffer.writeInteger(UInt32(0))
pingBuffer.writeInteger(UInt64(0))
XCTAssertNoThrow(try self.serverChannel.writeInbound(pingBuffer.getSlice(at: pingBuffer.readerIndex, length: 8)))
XCTAssertNoThrow(try self.serverChannel.writeInbound(pingBuffer.getSlice(at: pingBuffer.readerIndex + 8, length: 9)))
try self.serverChannel.assertReceivedFrame().assertPingFrame(ack: false, opaqueData: HTTP2PingData(withInteger: 0))
// We should have a PING response. Let's check it.
self.interactInMemory(self.serverChannel, self.clientChannel)
try self.clientChannel.assertReceivedFrame().assertPingFrame(ack: true, opaqueData: HTTP2PingData(withInteger: 0))
// No other frames should be emitted.
self.clientChannel.assertNoFramesReceived()
self.serverChannel.assertNoFramesReceived()
XCTAssertNoThrow(try self.clientChannel.finish())
XCTAssertNoThrow(try self.serverChannel.finish())
}
func testSendingTrailers() throws {
// Begin by getting the connection up.
try self.basicHTTP2Connection()
// We're now going to try to send a request from the client to the server. This request will be one headers frame, one
// data frame, and then another headers frame for trailers.
let headers = HPACKHeaders([(":path", "/"), (":method", "POST"), (":scheme", "https"), (":authority", "localhost")])
let trailers = HPACKHeaders([("x-trailers-field", "true")])
var requestBody = self.clientChannel.allocator.buffer(capacity: 128)
requestBody.writeStaticString("A simple HTTP/2 request.")
let clientStreamID = HTTP2StreamID(1)
let reqFrame = HTTP2Frame(streamID: clientStreamID, payload: .headers(.init(headers: headers)))
let reqBodyFrame = HTTP2Frame(streamID: clientStreamID, payload: .data(.init(data: .byteBuffer(requestBody))))
let trailerFrame = HTTP2Frame(streamID: clientStreamID, payload: .headers(.init(headers: trailers, endStream: true)))
let serverStreamID = try self.assertFramesRoundTrip(frames: [reqFrame, reqBodyFrame, trailerFrame], sender: self.clientChannel, receiver: self.serverChannel).first!.streamID
// Let's send a quick response back. This response should also contain trailers.
let responseHeaders = HPACKHeaders([(":status", "200"), ("content-length", "0")])
let respFrame = HTTP2Frame(streamID: serverStreamID, payload: .headers(.init(headers: responseHeaders)))
let respTrailersFrame = HTTP2Frame(streamID: serverStreamID, payload: .headers(.init(headers: trailers, endStream: true)))
let expectedFrames = [respFrame, respTrailersFrame]
try self.assertFramesRoundTrip(frames: expectedFrames, sender: self.serverChannel, receiver: self.clientChannel)
XCTAssertNoThrow(try self.clientChannel.finish())
XCTAssertNoThrow(try self.serverChannel.finish())
}
func test1XXResponseHeaderFields() throws {
// Begin by getting the connection up.
try self.basicHTTP2Connection()
// We're now going to try to send a simple request from the client.
let headers = HPACKHeaders([(":path", "/"), (":method", "GET"), (":scheme", "https"), (":authority", "localhost")])
let clientStreamID = HTTP2StreamID(1)
let reqFrame = HTTP2Frame(streamID: clientStreamID, payload: .headers(.init(headers: headers, endStream: true)))
let serverStreamID = try self.assertFramesRoundTrip(frames: [reqFrame], sender: self.clientChannel, receiver: self.serverChannel).first!.streamID
// We're going to send 3 150 responses back.
let earlyHeaders = HPACKHeaders([(":status", "150"), ("x-some-data", "is here")])
let earlyFrame = HTTP2Frame(streamID: serverStreamID, payload: .headers(.init(headers: earlyHeaders)))
try self.assertFramesRoundTrip(frames: [earlyFrame, earlyFrame, earlyFrame], sender: self.serverChannel, receiver: self.clientChannel)
// Now we send the final response back.
let responseHeaders = HPACKHeaders([(":status", "200"), ("content-length", "0")])
let respFrame = HTTP2Frame(streamID: serverStreamID, payload: .headers(.init(headers: responseHeaders, endStream: true)))
try self.assertFramesRoundTrip(frames: [respFrame], sender: self.serverChannel, receiver: self.clientChannel)
XCTAssertNoThrow(try self.clientChannel.finish())
XCTAssertNoThrow(try self.serverChannel.finish())
}
func testPriorityFrames() throws {
// Begin by getting the connection up.
try self.basicHTTP2Connection()
let frame = HTTP2Frame(streamID: 1, payload: .priority(.init(exclusive: false, dependency: 0, weight: 30)))
XCTAssertNoThrow(try self.assertFramesRoundTrip(frames: [frame], sender: self.clientChannel, receiver: self.serverChannel))
XCTAssertNoThrow(try self.clientChannel.finish())
XCTAssertNoThrow(try self.serverChannel.finish())
}
func testStreamClosedWithNoError() throws {
// Begin by getting the connection up.
try self.basicHTTP2Connection()
// Now add handlers to record user events.
let clientHandler = UserEventRecorder()
let serverHandler = UserEventRecorder()
try self.clientChannel.pipeline.addHandler(clientHandler).wait()
try self.serverChannel.pipeline.addHandler(serverHandler).wait()
// We're now going to try to send a request from the client to the server and send a server response back. This
// stream will terminate cleanly.
let headers = HPACKHeaders([(":path", "/"), (":method", "POST"), (":scheme", "https"), (":authority", "localhost")])
var requestBody = self.clientChannel.allocator.buffer(capacity: 128)
requestBody.writeStaticString("A simple HTTP/2 request.")
let clientStreamID = HTTP2StreamID(1)
let reqFrame = HTTP2Frame(streamID: clientStreamID, payload: .headers(.init(headers: headers)))
let reqBodyFrame = HTTP2Frame(streamID: clientStreamID, payload: .data(.init(data: .byteBuffer(requestBody), endStream: true)))
let serverStreamID = try self.assertFramesRoundTrip(frames: [reqFrame, reqBodyFrame], sender: self.clientChannel, receiver: self.serverChannel).first!.streamID
// At this stage the stream is still open, both handlers should have seen stream creation events.
XCTAssertEqual(clientHandler.events.count, 3)
XCTAssertEqual(serverHandler.events.count, 3)
XCTAssertEqual(clientHandler.events[0] as? NIOHTTP2StreamCreatedEvent, NIOHTTP2StreamCreatedEvent(streamID: clientStreamID, localInitialWindowSize: 65535, remoteInitialWindowSize: 65535))
XCTAssertEqual(serverHandler.events[0] as? NIOHTTP2StreamCreatedEvent, NIOHTTP2StreamCreatedEvent(streamID: serverStreamID, localInitialWindowSize: 65535, remoteInitialWindowSize: 65535))
// Let's send a quick response back.
let responseHeaders = HPACKHeaders([(":status", "200"), ("content-length", "0")])
let respFrame = HTTP2Frame(streamID: serverStreamID, payload: .headers(.init(headers: responseHeaders, endStream: true)))
try self.assertFramesRoundTrip(frames: [respFrame], sender: self.serverChannel, receiver: self.clientChannel)
// Now the streams are closed, they should have seen user events.
XCTAssertEqual(clientHandler.events.count, 5)
XCTAssertEqual(serverHandler.events.count, 5)
XCTAssertEqual(clientHandler.events[3] as? StreamClosedEvent, StreamClosedEvent(streamID: clientStreamID, reason: nil))
XCTAssertEqual(serverHandler.events[3] as? StreamClosedEvent, StreamClosedEvent(streamID: serverStreamID, reason: nil))
XCTAssertNoThrow(try self.clientChannel.finish())
XCTAssertNoThrow(try self.serverChannel.finish())
}
func testStreamClosedViaRstStream() throws {
// Begin by getting the connection up.
try self.basicHTTP2Connection()
// Now add handlers to record user events.
let clientHandler = UserEventRecorder()
let serverHandler = UserEventRecorder()
try self.clientChannel.pipeline.addHandler(clientHandler).wait()
try self.serverChannel.pipeline.addHandler(serverHandler).wait()
// Initiate a stream from the client. No need to send body data, we don't need it.
let headers = HPACKHeaders([(":path", "/"), (":method", "POST"), (":scheme", "https"), (":authority", "localhost")])
let clientStreamID = HTTP2StreamID(1)
let reqFrame = HTTP2Frame(streamID: clientStreamID, payload: .headers(.init(headers: headers)))
let serverStreamID = try self.assertFramesRoundTrip(frames: [reqFrame], sender: self.clientChannel, receiver: self.serverChannel).first!.streamID
// At this stage the stream is still open, both handlers should have seen stream creation events.
XCTAssertEqual(clientHandler.events.count, 1)
XCTAssertEqual(serverHandler.events.count, 1)
XCTAssertEqual(clientHandler.events[0] as? NIOHTTP2StreamCreatedEvent, NIOHTTP2StreamCreatedEvent(streamID: clientStreamID, localInitialWindowSize: 65535, remoteInitialWindowSize: 65535))
XCTAssertEqual(serverHandler.events[0] as? NIOHTTP2StreamCreatedEvent, NIOHTTP2StreamCreatedEvent(streamID: serverStreamID, localInitialWindowSize: 65535, remoteInitialWindowSize: 65535))
// The server will reset the stream.
let rstStreamFrame = HTTP2Frame(streamID: serverStreamID, payload: .rstStream(.cancel))
try self.assertFramesRoundTrip(frames: [rstStreamFrame], sender: self.serverChannel, receiver: self.clientChannel)
// Now the streams are closed, they should have seen user events.
XCTAssertEqual(clientHandler.events.count, 3)
XCTAssertEqual(serverHandler.events.count, 3)
XCTAssertEqual(clientHandler.events[1] as? StreamClosedEvent, StreamClosedEvent(streamID: clientStreamID, reason: .cancel))
XCTAssertEqual(serverHandler.events[1] as? StreamClosedEvent, StreamClosedEvent(streamID: serverStreamID, reason: .cancel))
XCTAssertNoThrow(try self.clientChannel.finish())
XCTAssertNoThrow(try self.serverChannel.finish())
}
func testStreamClosedViaGoaway() throws {
// Begin by getting the connection up.
try self.basicHTTP2Connection()
// Now add handlers to record user events.
let clientHandler = UserEventRecorder()
let serverHandler = UserEventRecorder()
try self.clientChannel.pipeline.addHandler(clientHandler).wait()
try self.serverChannel.pipeline.addHandler(serverHandler).wait()
// Initiate a stream from the client. No need to send body data, we don't need it.
let headers = HPACKHeaders([(":path", "/"), (":method", "POST"), (":scheme", "https"), (":authority", "localhost")])
let clientStreamID = HTTP2StreamID(1)
let reqFrame = HTTP2Frame(streamID: clientStreamID, payload: .headers(.init(headers: headers)))
let serverStreamID = try self.assertFramesRoundTrip(frames: [reqFrame], sender: self.clientChannel, receiver: self.serverChannel).first!.streamID
// At this stage the stream is still open, both handlers should have seen stream creation events.
XCTAssertEqual(clientHandler.events.count, 1)
XCTAssertEqual(serverHandler.events.count, 1)
XCTAssertEqual(clientHandler.events[0] as? NIOHTTP2StreamCreatedEvent, NIOHTTP2StreamCreatedEvent(streamID: clientStreamID, localInitialWindowSize: 65535, remoteInitialWindowSize: 65535))
XCTAssertEqual(serverHandler.events[0] as? NIOHTTP2StreamCreatedEvent, NIOHTTP2StreamCreatedEvent(streamID: serverStreamID, localInitialWindowSize: 65535, remoteInitialWindowSize: 65535))
// The server will send a GOAWAY.
let goawayFrame = HTTP2Frame(streamID: .rootStream, payload: .goAway(lastStreamID: .rootStream, errorCode: .http11Required, opaqueData: nil))
try self.assertFramesRoundTrip(frames: [goawayFrame], sender: self.serverChannel, receiver: self.clientChannel)
// Now the streams are closed, they should have seen user events.
XCTAssertEqual(clientHandler.events.count, 2)
XCTAssertEqual(serverHandler.events.count, 2)
XCTAssertEqual((clientHandler.events[1] as? StreamClosedEvent)?.streamID, clientStreamID)
XCTAssertEqual((serverHandler.events[1] as? StreamClosedEvent)?.streamID, serverStreamID)
XCTAssertNoThrow(try self.clientChannel.finish())
XCTAssertNoThrow(try self.serverChannel.finish())
}
func testStreamCloseEventForRstStreamFiresAfterFrame() throws {
// Begin by getting the connection up.
try self.basicHTTP2Connection()
// Initiate a stream from the client. No need to send body data, we don't need it.
let clientStreamID = HTTP2StreamID(1)
let headers = HPACKHeaders([(":path", "/"), (":method", "POST"), (":scheme", "https"), (":authority", "localhost")])
let reqFrame = HTTP2Frame(streamID: clientStreamID, payload: .headers(.init(headers: headers)))
let serverStreamID = try self.assertFramesRoundTrip(frames: [reqFrame], sender: self.clientChannel, receiver: self.serverChannel).first!.streamID
// Add handler to record stream closed event.
let handler = ClosedEventVsFrameOrderingHandler(targetStreamID: serverStreamID)
try self.serverChannel.pipeline.addHandler(handler).wait()
// The client will reset the stream.
let rstStreamFrame = HTTP2Frame(streamID: serverStreamID, payload: .rstStream(.cancel))
try self.assertFramesRoundTrip(frames: [rstStreamFrame], sender: self.clientChannel, receiver: self.serverChannel)
// Check we saw the frame and the event.
XCTAssertTrue(handler.seenEvent)
XCTAssertTrue(handler.seenFrame)
XCTAssertNoThrow(try self.clientChannel.finish())
XCTAssertNoThrow(try self.serverChannel.finish())
}
func testStreamCloseEventForGoawayFiresAfterFrame() throws {
// Begin by getting the connection up.
try self.basicHTTP2Connection()
// Initiate a stream from the client. No need to send body data, we don't need it.
let clientStreamID = HTTP2StreamID(1)
let headers = HPACKHeaders([(":path", "/"), (":method", "POST"), (":scheme", "https"), (":authority", "localhost")])
let reqFrame = HTTP2Frame(streamID: clientStreamID, payload: .headers(.init(headers: headers)))
try self.assertFramesRoundTrip(frames: [reqFrame], sender: self.clientChannel, receiver: self.serverChannel)
// Add handler to record stream closed event.
let handler = ClosedEventVsFrameOrderingHandler(targetStreamID: clientStreamID)
try self.clientChannel.pipeline.addHandler(handler).wait()
// The server will send GOAWAY.
let goawayFrame = HTTP2Frame(streamID: .rootStream, payload: .goAway(lastStreamID: .rootStream, errorCode: .http11Required, opaqueData: nil))
try self.assertFramesRoundTrip(frames: [goawayFrame], sender: self.serverChannel, receiver: self.clientChannel)
// Check we saw the frame and the event.
XCTAssertTrue(handler.seenEvent)
XCTAssertTrue(handler.seenFrame)
XCTAssertNoThrow(try self.clientChannel.finish())
XCTAssertNoThrow(try self.serverChannel.finish())
}
func testManyConcurrentInactiveStreams() throws {
// Begin by getting the connection up.
try self.basicHTTP2Connection()
// Obtain some request data.
let requestHeaders = HPACKHeaders([(":path", "/"), (":method", "POST"), (":scheme", "https"), (":authority", "localhost")])
var requestBody = self.clientChannel.allocator.buffer(capacity: 128)
requestBody.writeStaticString("A simple HTTP/2 request.")
let responseHeaders = HPACKHeaders([(":status", "200"), ("content-length", "0")])
// We're going to initiate and then close lots of streams.
// Nothing bad should happen here.
for id in stride(from: 1, through: 256, by: 2) {
// We're now going to try to send a request from the client to the server.
let clientStreamID = HTTP2StreamID(id)
let reqFrame = HTTP2Frame(streamID: clientStreamID, payload: .headers(.init(headers: requestHeaders)))
let reqBodyFrame = HTTP2Frame(streamID: clientStreamID, payload: .data(.init(data: .byteBuffer(requestBody), endStream: true)))
let serverStreamID = try self.assertFramesRoundTrip(frames: [reqFrame, reqBodyFrame], sender: self.clientChannel, receiver: self.serverChannel).first!.streamID
// Let's send a quick response back.
let respFrame = HTTP2Frame(streamID: serverStreamID, payload: .headers(.init(headers: responseHeaders, endStream: true)))
try self.assertFramesRoundTrip(frames: [respFrame], sender: self.serverChannel, receiver: self.clientChannel)
}
XCTAssertNoThrow(try self.clientChannel.finish())
XCTAssertNoThrow(try self.serverChannel.finish())
}
func testBadClientMagic() throws {
class WaitForErrorHandler: ChannelInboundHandler {
typealias InboundIn = Never
private var errorSeenPromise: EventLoopPromise<Error>?
init(errorSeenPromise: EventLoopPromise<Error>) {
self.errorSeenPromise = errorSeenPromise
}
func channelRead(context: ChannelHandlerContext, data: NIOAny) {
XCTFail("shouldnt' have received \(data)")
}
func errorCaught(context: ChannelHandlerContext, error: Error) {
if let errorSeenPromise = self.errorSeenPromise {
errorSeenPromise.succeed(error)
} else {
XCTFail("extra error \(error) received")
}
}
}
let errorSeenPromise: EventLoopPromise<Error> = self.clientChannel.eventLoop.makePromise()
XCTAssertNoThrow(try self.serverChannel.pipeline.addHandler(NIOHTTP2Handler(mode: .server)).wait())
XCTAssertNoThrow(try self.serverChannel.pipeline.addHandler(WaitForErrorHandler(errorSeenPromise: errorSeenPromise)).wait())
XCTAssertNoThrow(try self.clientChannel?.connect(to: SocketAddress(unixDomainSocketPath: "ignored")).wait())
XCTAssertNoThrow(try self.serverChannel?.connect(to: SocketAddress(unixDomainSocketPath: "ignored")).wait())
var buffer = self.clientChannel.allocator.buffer(capacity: 16)
buffer.writeStaticString("GET / HTTP/1.1\r\nHost: apple.com\r\n\r\n")
XCTAssertNoThrow(try self.clientChannel.writeAndFlush(buffer).wait())
self.interactInMemory(self.clientChannel, self.serverChannel)
XCTAssertNoThrow(try XCTAssertEqual(NIOHTTP2Errors.badClientMagic(),
errorSeenPromise.futureResult.wait() as? NIOHTTP2Errors.BadClientMagic))
// The client will get two frames: a SETTINGS frame, and a GOAWAY frame. We don't want to decode these, so we
// just check their bytes match the expected payloads.
if var settingsFrame: ByteBuffer = try assertNoThrowWithValue(self.clientChannel.readInbound()) {
let settingsBytes: [UInt8] = [0, 0, 12, 4, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 100, 0, 6, 0, 0, 64, 0]
XCTAssertEqual(settingsFrame.readBytes(length: settingsFrame.readableBytes), settingsBytes)
} else {
XCTFail("No settings frame")
}
if var goawayFrame: ByteBuffer = try assertNoThrowWithValue(self.clientChannel.readInbound()) {
let goawayBytes: [UInt8] = [0, 0, 8, 7, 0, 0, 0, 0, 0, 0x7f, 0xff, 0xff, 0xff, 0, 0, 0, 1]
XCTAssertEqual(goawayFrame.readBytes(length: goawayFrame.readableBytes), goawayBytes)
} else {
XCTFail("No Goaway frame")
}
XCTAssertNoThrow(try XCTAssertTrue(self.clientChannel.finish().isClean))
XCTAssertNoThrow(try XCTAssertTrue(self.serverChannel.finish().isClean))
}
func testOpeningWindowsViaSettingsInitialWindowSize() throws {
try self.basicHTTP2Connection()
// Start by having the client shrink the server's initial window size to 0. We should get an ACK as well.
try self.assertSettingsUpdateWithAck([HTTP2Setting(parameter: .initialWindowSize, value: 0)], sender: self.clientChannel, receiver: self.serverChannel)
self.clientChannel.assertNoFramesReceived()
self.serverChannel.assertNoFramesReceived()
// Now open a stream.
let headers = HPACKHeaders([(":path", "/"), (":method", "POST"), (":scheme", "https"), (":authority", "localhost")])
let clientStreamID = HTTP2StreamID(1)
let reqFrame = HTTP2Frame(streamID: clientStreamID, payload: .headers(.init(headers: headers, endStream: true)))
try self.assertFramesRoundTrip(frames: [reqFrame], sender: self.clientChannel, receiver: self.serverChannel)
// Confirm there's no bonus frame sitting around.
self.clientChannel.assertNoFramesReceived()
self.serverChannel.assertNoFramesReceived()
// The server can respond with a headers frame and a DATA frame.
let serverHeaders = HPACKHeaders([(":status", "200")])
let respFrame = HTTP2Frame(streamID: clientStreamID, payload: .headers(.init(headers: serverHeaders)))
try self.assertFramesRoundTrip(frames: [respFrame], sender: self.serverChannel, receiver: self.clientChannel)
// Confirm there's no bonus frame sitting around.
self.clientChannel.assertNoFramesReceived()
self.serverChannel.assertNoFramesReceived()
// Now we're going to send in a DATA frame. This will not be sent, as the window size is 0.
var buffer = self.clientChannel.allocator.buffer(capacity: 5)
buffer.writeStaticString("hello")
let dataFrame = HTTP2Frame(streamID: clientStreamID, payload: .data(.init(data: .byteBuffer(buffer), endStream: true)))
self.serverChannel.writeAndFlush(dataFrame, promise: nil)
self.interactInMemory(self.clientChannel, self.serverChannel)
// No frames should be produced.
self.clientChannel.assertNoFramesReceived()
self.serverChannel.assertNoFramesReceived()
// Now the client will send a new SETTINGS frame. This will produce a SETTINGS ACK, and widen the flow control window a bit.
// We make this one a bit tricky to confirm that we do the math properly: we set the window size to 5, then to 3. The new value
// should be 3.
try self.assertSettingsUpdateWithAck([HTTP2Setting(parameter: .initialWindowSize, value: 5), HTTP2Setting(parameter: .initialWindowSize, value: 3)], sender: self.clientChannel, receiver: self.serverChannel)
try self.clientChannel.assertReceivedFrame().assertFrameMatches(this: HTTP2Frame(streamID: clientStreamID, payload: .data(.init(data: .byteBuffer(buffer.readSlice(length: 3)!)))))
self.clientChannel.assertNoFramesReceived()
self.serverChannel.assertNoFramesReceived()
// Sending the same SETTINGS frame again does not produce more data.
try self.assertSettingsUpdateWithAck([HTTP2Setting(parameter: .initialWindowSize, value: 3)], sender: self.clientChannel, receiver: self.serverChannel)
self.clientChannel.assertNoFramesReceived()
self.serverChannel.assertNoFramesReceived()
// Now we can widen the window again, and get the rest of the frame.
try self.assertSettingsUpdateWithAck([HTTP2Setting(parameter: .initialWindowSize, value: 6)], sender: self.clientChannel, receiver: self.serverChannel)
try self.clientChannel.assertReceivedFrame().assertFrameMatches(this: HTTP2Frame(streamID: clientStreamID, payload: .data(.init(data: .byteBuffer(buffer.readSlice(length: 2)!), endStream: true))))
self.clientChannel.assertNoFramesReceived()
self.serverChannel.assertNoFramesReceived()
XCTAssertNoThrow(try self.clientChannel.finish())
XCTAssertNoThrow(try self.serverChannel.finish())
}
func testSettingsAckNotifiesAboutChangedFlowControl() throws {
// Begin by getting the connection up.
try self.basicHTTP2Connection()
let recorder = UserEventRecorder()
XCTAssertNoThrow(try self.clientChannel.pipeline.addHandler(recorder).wait())
// Let's open a few streams.
let headers = HPACKHeaders([(":path", "/"), (":method", "GET"), (":scheme", "https"), (":authority", "localhost")])
let frames = [HTTP2StreamID(1), HTTP2StreamID(3), HTTP2StreamID(5)].map { HTTP2Frame(streamID: $0, payload: .headers(.init(headers: headers))) }
try self.assertFramesRoundTrip(frames: frames, sender: self.clientChannel, receiver: self.serverChannel)
// We will have some user events here, none should be a SETTINGS_INITIAL_WINDOW_SIZE change.
XCTAssertFalse(recorder.events.contains(where: { $0 is NIOHTTP2BulkStreamWindowChangeEvent }))
// Now the client will send, and get acknowledged, a new settings with a different stream window size.
// For fanciness, we change it twice.
try self.assertSettingsUpdateWithAck([HTTP2Setting(parameter: .initialWindowSize, value: 60000), HTTP2Setting(parameter: .initialWindowSize, value: 50000)], sender: self.clientChannel, receiver: self.serverChannel)
let events = recorder.events.compactMap { $0 as? NIOHTTP2BulkStreamWindowChangeEvent }
XCTAssertEqual(events, [NIOHTTP2BulkStreamWindowChangeEvent(delta: -15535)])
// Let's do it again, just to prove it isn't a fluke.
try self.assertSettingsUpdateWithAck([HTTP2Setting(parameter: .initialWindowSize, value: 65535)], sender: self.clientChannel, receiver: self.serverChannel)
let newEvents = recorder.events.compactMap { $0 as? NIOHTTP2BulkStreamWindowChangeEvent }
XCTAssertEqual(newEvents, [NIOHTTP2BulkStreamWindowChangeEvent(delta: -15535), NIOHTTP2BulkStreamWindowChangeEvent(delta: 15535)])
XCTAssertNoThrow(try self.clientChannel.finish())
XCTAssertNoThrow(try self.serverChannel.finish())
}
func testStreamMultiplexerAcknowledgesSettingsBasedFlowControlChanges() throws {
// This test verifies that the stream multiplexer pays attention to notifications about settings changes to flow
// control windows. It can't do that by *raising* the flow control window, as that information is duplicated in the
// stream flow control change notifications sent by receiving data frames. So it must do it by *shrinking* the window.
// Begin by getting the connection up and add a stream multiplexer.
try self.basicHTTP2Connection()
XCTAssertNoThrow(try self.serverChannel.pipeline.addHandler(HTTP2StreamMultiplexer(mode: .server, channel: self.serverChannel, inboundStreamInitializer: nil)).wait())
var largeBuffer = self.clientChannel.allocator.buffer(capacity: 32767)
largeBuffer.writeBytes(repeatElement(UInt8(0xFF), count: 32767))
// Let's open a stream, and write a DATA frame that consumes slightly less than half the window.
let headers = HPACKHeaders([(":path", "/"), (":method", "GET"), (":scheme", "https"), (":authority", "localhost")])
let headersFrame = HTTP2Frame(streamID: 1, payload: .headers(.init(headers: headers)))
let bodyFrame = HTTP2Frame(streamID: 1, payload: .data(.init(data: .byteBuffer(largeBuffer))))
self.clientChannel.write(headersFrame, promise: nil)
self.clientChannel.writeAndFlush(bodyFrame, promise: nil)
self.interactInMemory(self.clientChannel, self.serverChannel)
// No window update frame should be emitted.
self.clientChannel.assertNoFramesReceived()
self.serverChannel.assertNoFramesReceived()
// Now have the server shrink the client's flow control window.
// When it does this, the stream multiplexer will be told, and the stream will set its new expected maintained window size accordingly.
// However, the new *actual* window size will now be small enough to emit a window update for. Note that the connection will not have a window
// update frame sent as well maintain its size.
try self.assertSettingsUpdateWithAck([(HTTP2Setting(parameter: .initialWindowSize, value: 32768))], sender: self.serverChannel, receiver: self.clientChannel)
try self.clientChannel.assertReceivedFrame().assertWindowUpdateFrame(streamID: 1, windowIncrement: 32767)
self.clientChannel.assertNoFramesReceived()
self.serverChannel.assertNoFramesReceived()
// Shrink it further. We shouldn't emit another window update.
try self.assertSettingsUpdateWithAck([(HTTP2Setting(parameter: .initialWindowSize, value: 16384))], sender: self.serverChannel, receiver: self.clientChannel)
self.clientChannel.assertNoFramesReceived()
self.serverChannel.assertNoFramesReceived()
// And resize up. No window update either.
try self.assertSettingsUpdateWithAck([(HTTP2Setting(parameter: .initialWindowSize, value: 65535))], sender: self.serverChannel, receiver: self.clientChannel)
self.clientChannel.assertNoFramesReceived()
self.serverChannel.assertNoFramesReceived()
XCTAssertNoThrow(try self.clientChannel.finish())
XCTAssertNoThrow(try self.serverChannel.finish())
}
func testChangingMaxFrameSize() throws {
// Begin by getting the connection up.
try self.basicHTTP2Connection()
// We're now going to try to send a request from the client to the server.
let headers = HPACKHeaders([(":path", "/"), (":method", "POST"), (":scheme", "https"), (":authority", "localhost")])
let clientStreamID = HTTP2StreamID(1)
let reqFrame = HTTP2Frame(streamID: clientStreamID, payload: .headers(.init(headers: headers)))
try self.assertFramesRoundTrip(frames: [reqFrame], sender: self.clientChannel, receiver: self.serverChannel)
// Now the server is going to change SETTINGS_MAX_FRAME_SIZE. We set this twice to confirm we do this properly.
try self.assertSettingsUpdateWithAck([HTTP2Setting(parameter: .maxFrameSize, value: 1<<15), HTTP2Setting(parameter: .maxFrameSize, value: 1<<16)], sender: self.serverChannel, receiver: self.clientChannel)
// Now the client will send a very large DATA frame. It must be passed through as a single entity, and accepted by the remote peer.
var buffer = self.clientChannel.allocator.buffer(capacity: 65535)
buffer.writeBytes(repeatElement(UInt8(0xFF), count: 65535))
let bodyFrame = HTTP2Frame(streamID: clientStreamID, payload: .data(.init(data: .byteBuffer(buffer))))
try self.assertFramesRoundTrip(frames: [bodyFrame], sender: self.clientChannel, receiver: self.serverChannel)
XCTAssertNoThrow(try self.clientChannel.finish())
XCTAssertNoThrow(try self.serverChannel.finish())
}
func testStreamErrorOnSelfDependentPriorityFrames() throws {
// Begin by getting the connection up.
try self.basicHTTP2Connection()
// Send a PRIORITY frame that has a self-dependency. Note that we aren't policing these outbound:
// as we can't detect cycles generally without maintaining a bunch of state, we simply don't. That
// allows us to emit this.
let frame = HTTP2Frame(streamID: 1, payload: .priority(.init(exclusive: false, dependency: 1, weight: 32)))
self.clientChannel.writeAndFlush(frame, promise: nil)
// We treat this as a connection error.
guard let frameData = try assertNoThrowWithValue(self.clientChannel.readOutbound(as: ByteBuffer.self)) else {
XCTFail("Did not receive frame")
return
}
XCTAssertThrowsError(try self.serverChannel.writeInbound(frameData)) { error in
XCTAssertEqual(error as? NIOHTTP2Errors.PriorityCycle, NIOHTTP2Errors.priorityCycle(streamID: 1))
}
guard let responseFrame = try assertNoThrowWithValue(self.serverChannel.readOutbound(as: ByteBuffer.self)) else {
XCTFail("Did not receive response frame")
return
}
XCTAssertNoThrow(try self.clientChannel.writeInbound(responseFrame))
try self.clientChannel.assertReceivedFrame().assertGoAwayFrame(lastStreamID: .maxID, errorCode: UInt32(http2ErrorCode: .protocolError), opaqueData: nil)
XCTAssertNoThrow(XCTAssertTrue(try self.clientChannel.finish().isClean))
_ = try? self.serverChannel.finish()
}
func testStreamErrorOnSelfDependentHeadersFrames() throws {
// Begin by getting the connection up.
try self.basicHTTP2Connection()
// Send a HEADERS frame that has a self-dependency. Note that we aren't policing these outbound:
// as we can't detect cycles generally without maintaining a bunch of state, we simply don't. That
// allows us to emit this.
let headers = HPACKHeaders([(":path", "/"), (":method", "POST"), (":scheme", "https"), (":authority", "localhost")])
let frame = HTTP2Frame(streamID: 1, payload: .headers(.init(headers: headers, priorityData: .init(exclusive: true, dependency: 1, weight: 64))))
self.clientChannel.writeAndFlush(frame, promise: nil)
// We treat this as a connection error.
guard let frameData = try assertNoThrowWithValue(self.clientChannel.readOutbound(as: ByteBuffer.self)) else {
XCTFail("Did not receive frame")
return
}
XCTAssertThrowsError(try self.serverChannel.writeInbound(frameData)) { error in
XCTAssertEqual(error as? NIOHTTP2Errors.PriorityCycle, NIOHTTP2Errors.priorityCycle(streamID: 1))
}
guard let responseFrame = try assertNoThrowWithValue(self.serverChannel.readOutbound(as: ByteBuffer.self)) else {
XCTFail("Did not receive response frame")
return
}
XCTAssertNoThrow(try self.clientChannel.writeInbound(responseFrame))
try self.clientChannel.assertReceivedFrame().assertGoAwayFrame(lastStreamID: .maxID, errorCode: UInt32(http2ErrorCode: .protocolError), opaqueData: nil)
XCTAssertNoThrow(XCTAssertTrue(try self.clientChannel.finish().isClean))
_ = try? self.serverChannel.finish()
}
func testInvalidRequestHeaderBlockAllowsRstStream() throws {
XCTAssertNoThrow(try self.clientChannel.pipeline.addHandler(NIOHTTP2Handler(mode: .client, headerBlockValidation: .disabled)).wait())
XCTAssertNoThrow(try self.serverChannel.pipeline.addHandler(NIOHTTP2Handler(mode: .server)).wait())
try self.assertDoHandshake(client: self.clientChannel, server: self.serverChannel)
// We're going to send some invalid HTTP/2 request headers. The client has validation disabled, and will allow it, but the server will not.
let headers = HPACKHeaders([(":path", "/"), (":method", "POST"), (":scheme", "https"), (":authority", "localhost"), ("UPPERCASE", "not allowed")])
let frame = HTTP2Frame(streamID: 1, payload: .headers(.init(headers: headers)))
self.clientChannel.writeAndFlush(frame, promise: nil)
// We treat this as a stream error.
guard let frameData = try assertNoThrowWithValue(self.clientChannel.readOutbound(as: ByteBuffer.self)) else {
XCTFail("Did not receive frame")
return
}
XCTAssertThrowsError(try self.serverChannel.writeInbound(frameData)) { error in
XCTAssertEqual(error as? NIOHTTP2Errors.InvalidHTTP2HeaderFieldName, NIOHTTP2Errors.invalidHTTP2HeaderFieldName("UPPERCASE"))
}
guard let responseFrame = try assertNoThrowWithValue(self.serverChannel.readOutbound(as: ByteBuffer.self)) else {
XCTFail("Did not receive response frame")
return
}
XCTAssertNoThrow(try self.clientChannel.writeInbound(responseFrame))
try self.clientChannel.assertReceivedFrame().assertRstStreamFrame(streamID: 1, errorCode: .protocolError)
XCTAssertNoThrow(XCTAssertTrue(try self.clientChannel.finish().isClean))
_ = try? self.serverChannel.finish()
}
func testClientConnectionErrorCorrectlyReported() throws {
// Begin by getting the connection up.
try self.basicHTTP2Connection()
// Now we're going to try to trigger a connection error in the client. We'll do it by sending a weird SETTINGS frame that isn't valid.
let weirdSettingsFrame: [UInt8] = [
0x00, 0x00, 0x06, // 3-byte payload length (6 bytes)
0x04, // 1-byte frame type (SETTINGS)
0x00, // 1-byte flags (none)
0x00, 0x00, 0x00, 0x00, // 4-byte stream identifier
0x00, 0x02, // SETTINGS_ENABLE_PUSH
0x00, 0x00, 0x00, 0x03, // = 3, an invalid value
]
var settingsBuffer = self.clientChannel.allocator.buffer(capacity: 128)
settingsBuffer.writeBytes(weirdSettingsFrame)
XCTAssertThrowsError(try self.clientChannel.writeInbound(settingsBuffer)) { error in
XCTAssertEqual(error as? NIOHTTP2Errors.InvalidSetting, NIOHTTP2Errors.invalidSetting(setting: HTTP2Setting(parameter: .enablePush, value: 3)))
}
guard let goAwayFrame = try assertNoThrowWithValue(self.clientChannel.readOutbound(as: ByteBuffer.self)) else {
XCTFail("Did not receive GOAWAY frame")
return
}
XCTAssertNoThrow(try self.serverChannel.writeInbound(goAwayFrame))
try self.serverChannel.assertReceivedFrame().assertGoAwayFrame(lastStreamID: .maxID, errorCode: 0x01, opaqueData: nil)
XCTAssertNoThrow(XCTAssertTrue(try self.serverChannel.finish().isClean))
_ = try? self.clientChannel.finish()
}
func testChangingMaxConcurrentStreams() throws {
// Begin by getting the connection up.
try self.basicHTTP2Connection()
// We're now going to try to send a request from the client to the server.
let headers = HPACKHeaders([(":path", "/"), (":method", "GET"), (":scheme", "https"), (":authority", "localhost")])
let clientStreamID = HTTP2StreamID(1)
let reqFrame = HTTP2Frame(streamID: clientStreamID, payload: .headers(.init(headers: headers, endStream: true)))
try self.assertFramesRoundTrip(frames: [reqFrame], sender: self.clientChannel, receiver: self.serverChannel)
// Now the server is going to change SETTINGS_MAX_CONCURRENT_STREAMS. We set this twice to confirm we do this properly.
try self.assertSettingsUpdateWithAck([HTTP2Setting(parameter: .maxConcurrentStreams, value: 50), HTTP2Setting(parameter: .maxConcurrentStreams, value: 1)], sender: self.serverChannel, receiver: self.clientChannel)
// Now the client will attempt to open another stream. This should buffer.
let reqFrame2 = HTTP2Frame(streamID: 3, payload: .headers(.init(headers: headers, endStream: true)))
self.clientChannel.writeAndFlush(reqFrame2, promise: nil)
XCTAssertNoThrow(try XCTAssertNil(self.clientChannel.readOutbound(as: ByteBuffer.self)))
// The server will now complete the first stream, which should lead to the second stream being emitted.
let responseHeaders = HPACKHeaders([(":status", "200")])
let respFrame = HTTP2Frame(streamID: clientStreamID, payload: .headers(.init(headers: responseHeaders, endStream: true)))
self.serverChannel.writeAndFlush(respFrame, promise: nil)
self.interactInMemory(self.serverChannel, self.clientChannel)
// The client should have seen the server response.
guard let response = try assertNoThrowWithValue(self.clientChannel.readInbound(as: HTTP2Frame.self)) else {
XCTFail("Did not receive server HEADERS frame")
return
}
response.assertFrameMatches(this: respFrame)
// The server should have seen the new client request.
guard let request = try assertNoThrowWithValue(self.serverChannel.readInbound(as: HTTP2Frame.self)) else {
XCTFail("Did not receive client HEADERS frame")
return
}
request.assertFrameMatches(this: reqFrame2)
XCTAssertNoThrow(try self.clientChannel.finish())
XCTAssertNoThrow(try self.serverChannel.finish())
}
func testFailsPromisesForBufferedWrites() throws {
// Begin by getting the connection up.
try self.basicHTTP2Connection()
// We're going to queue some frames in the client, but not flush them. The HEADERS frame will pass
// right through, but the DATA ones won't.
let headers = HPACKHeaders([(":path", "/"), (":method", "POST"), (":scheme", "https"), (":authority", "localhost")])
let clientStreamID = HTTP2StreamID(1)
let reqFrame = HTTP2Frame(streamID: clientStreamID, payload: .headers(.init(headers: headers, endStream: false)))
var promiseResults: [Bool?] = Array(repeatElement(nil as Bool?, count: 5))
self.clientChannel.write(reqFrame, promise: nil)
let bodyFrame = HTTP2Frame(streamID: clientStreamID, payload: .data(.init(data: .byteBuffer(ByteBufferAllocator().buffer(capacity: 0)))))
for index in promiseResults.indices {
self.clientChannel.write(bodyFrame).map {
promiseResults[index] = true
}.whenFailure {
XCTAssertEqual($0 as? ChannelError, ChannelError.ioOnClosedChannel)
promiseResults[index] = false
}
}
XCTAssertEqual(promiseResults, [nil, nil, nil, nil, nil])
// Close the channel.
self.clientChannel.close(promise: nil)
self.clientChannel.embeddedEventLoop.run()
// The promises should be succeeded.
XCTAssertEqual(promiseResults, [false, false, false, false, false])
XCTAssertNoThrow(try self.serverChannel.finish())
}
func testAllowPushPromiseBeforeReceivingHeadersNoBody() throws {
// Begin by getting the connection up.
try self.basicHTTP2Connection()
// We're now going to try to send a request from the client to the server.
let headers = HPACKHeaders([(":path", "/"), (":method", "GET"), (":scheme", "https"), (":authority", "localhost")])
let clientStreamID = HTTP2StreamID(1)
let reqFrame = HTTP2Frame(streamID: clientStreamID, payload: .headers(.init(headers: headers, endStream: true)))
XCTAssertNoThrow(try self.assertFramesRoundTrip(frames: [reqFrame], sender: self.clientChannel, receiver: self.serverChannel))
// The server will push.
let pushFrame = HTTP2Frame(streamID: clientStreamID, payload: .pushPromise(.init(pushedStreamID: 2, headers: headers)))
XCTAssertNoThrow(try self.assertFramesRoundTrip(frames: [pushFrame], sender: self.serverChannel, receiver: self.clientChannel))
XCTAssertNoThrow(try self.clientChannel.finish())
XCTAssertNoThrow(try self.serverChannel.finish())
}
func testAllowPushPromiseBeforeReceivingHeadersWithPossibleBody() throws {
// This is the same as the test above but we don't set END_STREAM on our initial HEADERS, leading to a different stream state.
// Begin by getting the connection up.
try self.basicHTTP2Connection()
// We're now going to try to send a request from the client to the server.
let headers = HPACKHeaders([(":path", "/"), (":method", "GET"), (":scheme", "https"), (":authority", "localhost")])
let clientStreamID = HTTP2StreamID(1)
let reqFrame = HTTP2Frame(streamID: clientStreamID, payload: .headers(.init(headers: headers, endStream: false)))
XCTAssertNoThrow(try self.assertFramesRoundTrip(frames: [reqFrame], sender: self.clientChannel, receiver: self.serverChannel))
// The server will push.
let pushFrame = HTTP2Frame(streamID: clientStreamID, payload: .pushPromise(.init(pushedStreamID: 2, headers: headers)))
XCTAssertNoThrow(try self.assertFramesRoundTrip(frames: [pushFrame], sender: self.serverChannel, receiver: self.clientChannel))
XCTAssertNoThrow(try self.clientChannel.finish())
XCTAssertNoThrow(try self.serverChannel.finish())
}
func testSequentialEmptyDataFramesIsForbidden() throws {
try self.basicHTTP2Connection()
// We're going to open a few streams.
let headers = HPACKHeaders([(":path", "/"), (":method", "POST"), (":scheme", "https"), (":authority", "localhost")])
let streamIDs = [HTTP2StreamID(1), HTTP2StreamID(3)]
let headersFrames = streamIDs.map { HTTP2Frame(streamID: $0, payload: .headers(.init(headers: headers, endStream: false))) }
XCTAssertNoThrow(try self.assertFramesRoundTrip(frames: headersFrames, sender: self.clientChannel, receiver: self.serverChannel))
// Now we're going to send 2 empty data frames.
let emptyBuffer = self.clientChannel.allocator.buffer(capacity: 2)
let dataFrames = streamIDs.map { HTTP2Frame(streamID: $0, payload: .data(.init(data: .byteBuffer(emptyBuffer), endStream: false))) }
// First we send 1 without drama.
XCTAssertNoThrow(try self.assertFramesRoundTrip(frames: [dataFrames.first!], sender: self.clientChannel, receiver: self.serverChannel))
// Now we try to send the second.
self.clientChannel.writeAndFlush(dataFrames.last!, promise: nil)
guard let bytes = try assertNoThrowWithValue(self.clientChannel.readOutbound(as: ByteBuffer.self)) else {
XCTFail("Did not write client bytes")
return
}
// The server should have errored.
XCTAssertThrowsError(try self.serverChannel.writeInbound(bytes)) { error in
XCTAssertEqual(error as? NIOHTTP2Errors.ExcessiveEmptyDataFrames, NIOHTTP2Errors.excessiveEmptyDataFrames())
}
guard let serverBytes = try assertNoThrowWithValue(self.serverChannel.readOutbound(as: ByteBuffer.self)) else {
XCTFail("Did not write server bytes")
return
}
XCTAssertNoThrow(XCTAssertNil(try self.serverChannel.readOutbound(as: ByteBuffer.self)))
XCTAssertNoThrow(try self.clientChannel.writeInbound(serverBytes))
// The client should have seen a GOAWAY.
guard let goaway = try assertNoThrowWithValue(self.clientChannel.readInbound(as: HTTP2Frame.self)) else {
XCTFail("Did not receive server GOAWAY frame")
return
}
goaway.assertGoAwayFrame(lastStreamID: .maxID, errorCode: UInt32(HTTP2ErrorCode.enhanceYourCalm.networkCode), opaqueData: nil)
XCTAssertNoThrow(try self.clientChannel.finish())
}
func testSequentialEmptyDataFramesLimitIsConfigurable() throws {
XCTAssertNoThrow(try self.clientChannel.pipeline.addHandler(NIOHTTP2Handler(mode: .client)).wait())
XCTAssertNoThrow(try self.serverChannel.pipeline.addHandler(NIOHTTP2Handler(mode: .server, maximumSequentialEmptyDataFrames: 5)).wait())
XCTAssertNoThrow(try self.assertDoHandshake(client: self.clientChannel, server: self.serverChannel))
// We're going to open a few streams.
let headers = HPACKHeaders([(":path", "/"), (":method", "POST"), (":scheme", "https"), (":authority", "localhost")])
let streamIDs = [HTTP2StreamID(1), HTTP2StreamID(3)]
let headersFrames = streamIDs.map { HTTP2Frame(streamID: $0, payload: .headers(.init(headers: headers, endStream: false))) }
XCTAssertNoThrow(try self.assertFramesRoundTrip(frames: headersFrames, sender: self.clientChannel, receiver: self.serverChannel))
// Now we're going to send 6 empty data frames.
let emptyBuffer = self.clientChannel.allocator.buffer(capacity: 2)
let twoDataFrames = streamIDs.map { HTTP2Frame(streamID: $0, payload: .data(.init(data: .byteBuffer(emptyBuffer), endStream: false))) }
let dataFrames = repeatElement(twoDataFrames, count: 3).flatMap { $0 }
XCTAssertEqual(dataFrames.count, 6)
// First we send 5 without drama.
for frame in dataFrames.prefix(5) {
XCTAssertNoThrow(try self.assertFramesRoundTrip(frames: [frame], sender: self.clientChannel, receiver: self.serverChannel))
}
// Now we try to send the sixth.
self.clientChannel.writeAndFlush(dataFrames.last!, promise: nil)
guard let bytes = try assertNoThrowWithValue(self.clientChannel.readOutbound(as: ByteBuffer.self)) else {
XCTFail("Did not write client bytes")
return
}
// The server should have errored.
XCTAssertThrowsError(try self.serverChannel.writeInbound(bytes)) { error in
XCTAssertEqual(error as? NIOHTTP2Errors.ExcessiveEmptyDataFrames, NIOHTTP2Errors.excessiveEmptyDataFrames())
}
guard let serverBytes = try assertNoThrowWithValue(self.serverChannel.readOutbound(as: ByteBuffer.self)) else {
XCTFail("Did not write server bytes")
return
}
XCTAssertNoThrow(XCTAssertNil(try self.serverChannel.readOutbound(as: ByteBuffer.self)))
XCTAssertNoThrow(try self.clientChannel.writeInbound(serverBytes))
// The client should have seen a GOAWAY.
guard let goaway = try assertNoThrowWithValue(self.clientChannel.readInbound(as: HTTP2Frame.self)) else {
XCTFail("Did not receive server GOAWAY frame")
return
}
goaway.assertGoAwayFrame(lastStreamID: .maxID, errorCode: UInt32(HTTP2ErrorCode.enhanceYourCalm.networkCode), opaqueData: nil)
XCTAssertNoThrow(try self.clientChannel.finish())
}
func testDenialOfServiceViaPing() throws {
let maximimBufferedControlFrames = 50
// Begin by getting the connection up.
try self.basicHTTP2Connection(maximumBufferedControlFrames: maximimBufferedControlFrames)
// Now mark the server's channel as non-writable.
self.serverChannel.isWritable = false
self.serverChannel.pipeline.fireChannelWritabilityChanged()
// Now we want to send many PING frames. The server should not be writing any out,
// as the channel isn't writable.
let pingFrame = HTTP2Frame(streamID: .rootStream, payload: .ping(HTTP2PingData(withInteger: 0), ack: false))
let frames = Array(repeatElement(pingFrame, count: maximimBufferedControlFrames))
try self.assertFramesRoundTrip(frames: frames, sender: self.clientChannel, receiver: self.serverChannel)
// Ok, now send one more ping frame. This should cause an error
XCTAssertNoThrow(try XCTAssertTrue(self.clientChannel.writeOutbound(pingFrame).isFull))
guard let pingBytes = try assertNoThrowWithValue(self.clientChannel.readOutbound(as: ByteBuffer.self)) else {
XCTFail("Did not receive PING frame bytes")
return
}
XCTAssertThrowsError(try self.serverChannel.writeInbound(pingBytes)) { error in
XCTAssertEqual(error as? NIOHTTP2Errors.ExcessiveOutboundFrameBuffering, NIOHTTP2Errors.excessiveOutboundFrameBuffering())
}
XCTAssertNoThrow(try self.clientChannel.finish())
}
func testDenialOfServiceViaSettings() throws {
let maximimBufferedControlFrames = 50
// Begin by getting the connection up.
try self.basicHTTP2Connection(maximumBufferedControlFrames: maximimBufferedControlFrames)
// Now mark the server's channel as non-writable.
self.serverChannel.isWritable = false
self.serverChannel.pipeline.fireChannelWritabilityChanged()
// Now we want to send many empty SETTINGS frames. The server should not be writing any out,
// as the channel isn't writable.
let settingsFrame = HTTP2Frame(streamID: .rootStream, payload: .settings(.settings([])))
let frames = Array(repeatElement(settingsFrame, count: maximimBufferedControlFrames))
try self.assertFramesRoundTrip(frames: frames, sender: self.clientChannel, receiver: self.serverChannel)
// Ok, now send one more settings frame. This should cause connection teardown.
XCTAssertNoThrow(try XCTAssertTrue(self.clientChannel.writeOutbound(settingsFrame).isFull))
guard let settingsBytes = try assertNoThrowWithValue(self.clientChannel.readOutbound(as: ByteBuffer.self)) else {
XCTFail("Did not receive SETTINGS frame bytes")
return
}
XCTAssertThrowsError(try self.serverChannel.writeInbound(settingsBytes)) { error in
XCTAssertEqual(error as? NIOHTTP2Errors.ExcessiveOutboundFrameBuffering, NIOHTTP2Errors.excessiveOutboundFrameBuffering())
}
XCTAssertNoThrow(try self.clientChannel.finish())
}
func testFramesArentWrittenWhenChannelIsntWritable() throws {
// Begin by getting the connection up.
try self.basicHTTP2Connection()
let headers = HPACKHeaders([(":path", "/"), (":method", "POST"), (":scheme", "https"), (":authority", "localhost")])
var requestBody = self.clientChannel.allocator.buffer(capacity: 128)
requestBody.writeStaticString("A simple HTTP/2 request.")
// The client opens a streeam
try self.assertFramesRoundTrip(frames: [HTTP2Frame(streamID: 1, payload: .headers(.init(headers: headers, endStream: false)))], sender: self.clientChannel, receiver: self.serverChannel)
// Now the client loses writability.
self.clientChannel.isWritable = false
self.clientChannel.pipeline.fireChannelWritabilityChanged()
// Now the client is going to try to write a bunch of data on stream 1.
let dataFrames = Array(repeatElement(HTTP2Frame(streamID: 1, payload: .data(.init(data: .byteBuffer(requestBody), endStream: false))), count: 100))
for frame in dataFrames {
self.clientChannel.writeAndFlush(frame, promise: nil)
}
XCTAssertNoThrow(try self.clientChannel.throwIfErrorCaught())
// Also the client is going to try to initiate 100 more streams. This would normally violate SETTINGS_MAX_CONCURRENT_STREAMS, but in this case they should all
// be buffered locally.
let bonusStreams = stride(from: HTTP2StreamID(3), to: HTTP2StreamID(203), by: 2).map { HTTP2Frame(streamID: $0, payload: .headers(.init(headers: headers, endStream: true))) }
for frame in bonusStreams {
self.clientChannel.writeAndFlush(frame, promise: nil)
}
XCTAssertNoThrow(try self.clientChannel.throwIfErrorCaught())
// The client shouldn't have written any of these.
XCTAssertNoThrow(try XCTAssertNil(self.clientChannel.readOutbound(as: ByteBuffer.self)))
// Now make the channel readable.
self.clientChannel.isWritable = true
self.clientChannel.pipeline.fireChannelWritabilityChanged()
// All but 1 of the HEADERS frames should now come out, followed by the DATA frames.
self.interactInMemory(self.clientChannel, self.serverChannel)
var receivedFrames = Array<HTTP2Frame>()
while let frame = try assertNoThrowWithValue(self.serverChannel.readInbound(as: HTTP2Frame.self)) {
receivedFrames.append(frame)
}
receivedFrames.assertFramesMatch(Array(bonusStreams.dropLast()) + dataFrames)
// Now we close stream a stream on the server side.
let responseHeaders = HPACKHeaders([(":status", "200")])
let responseFrame = HTTP2Frame(streamID: 3, payload: .headers(.init(headers: responseHeaders, endStream: true)))
XCTAssertNoThrow(try self.serverChannel.writeOutbound(responseFrame))
self.interactInMemory(self.clientChannel, self.serverChannel)
// This should get the last HEADERS frame out.
try self.clientChannel.readInbound(as: HTTP2Frame.self)!.assertFrameMatches(this: responseFrame)
try self.serverChannel.readInbound(as: HTTP2Frame.self)!.assertFrameMatches(this: bonusStreams.last!)
XCTAssertNoThrow(try self.clientChannel.finish())
XCTAssertNoThrow(try self.serverChannel.finish())
}
func testEnforcingMaxHeaderListSize() throws {
// Begin by getting the connection up.
try self.basicHTTP2Connection()
// The server is going to shrink its value for max header list size.
let newSettings = [HTTP2Setting(parameter: .maxHeaderListSize, value: 225)]
try self.assertSettingsUpdateWithAck(newSettings, sender: self.serverChannel, receiver: self.clientChannel)
// Ok, first let's send something safe. This size is calculated as 32 bytes per entry, plus the octet length
// of the name and value. The below block is 225 bytes, as shown below.
let goodHeaders = HPACKHeaders([
(":path", "/"), // 32 byte overhead + 5 byte name + one byte value == 38 bytes, total is 38
(":method", "GET"), // 32 byte overhead + 7 byte name + 3 byte value == 42 bytes, total is 80
(":authority", "localhost"), // 32 byte overhead + 10 byte name + 9 byte value == 51 bytes, total is 131
(":scheme", "https"), // 32 byte overhead + 7 byte name + 5 byte value == 44 bytes, total is 175
("user-agent", "swiftnio"), // 32 byte overhead + 10 byte name + 8 byte value == 50 bytes, total is 225
])
let firstRequestFrame = HTTP2Frame(streamID: 1, payload: .headers(.init(headers: goodHeaders)))
try self.assertFramesRoundTrip(frames: [firstRequestFrame], sender: self.clientChannel, receiver: self.serverChannel)
// Ok, we'll create some new headers that are bad by adding one byte to the last header field.
let badHeaders = HPACKHeaders([
(":path", "/"), // 32 byte overhead + 5 byte name + one byte value == 38 bytes, total is 38
(":method", "GET"), // 32 byte overhead + 7 byte name + 3 byte value == 42 bytes, total is 80
(":authority", "localhost"), // 32 byte overhead + 10 byte name + 9 byte value == 51 bytes, total is 131
(":scheme", "https"), // 32 byte overhead + 7 byte name + 5 byte value == 44 bytes, total is 175
("user-agent", "swiftnio2"), // 32 byte overhead + 10 byte name + 9 byte value == 51 bytes, total is 226
])
// These should be forbidden. This is a connection error, as we do not promise to have decoded all the headers.
let secondRequestFrame = HTTP2Frame(streamID: 3, payload: .headers(.init(headers: badHeaders)))
self.clientChannel.writeAndFlush(secondRequestFrame, promise: nil)
guard let frameData = try assertNoThrowWithValue(self.clientChannel.readOutbound(as: ByteBuffer.self)) else {
XCTFail("Did not receive frame")
return
}
XCTAssertThrowsError(try self.serverChannel.writeInbound(frameData)) { error in
XCTAssertEqual(error as? NIOHTTP2Errors.UnableToParseFrame, NIOHTTP2Errors.unableToParseFrame())
}
guard let responseFrame = try assertNoThrowWithValue(self.serverChannel.readOutbound(as: ByteBuffer.self)) else {
XCTFail("Did not receive response frame")
return
}
XCTAssertNoThrow(try self.clientChannel.writeInbound(responseFrame))
try self.clientChannel.assertReceivedFrame().assertGoAwayFrame(lastStreamID: .maxID, errorCode: UInt32(HTTP2ErrorCode.compressionError.networkCode), opaqueData: nil)
}
func testForbidsExceedingMaxHeaderListSizeBeforeDecoding() throws {
// Begin by getting the connection up.
try self.basicHTTP2Connection()
// The server is going to shrink its value for max header list size.
let newSettings = [HTTP2Setting(parameter: .maxHeaderListSize, value: 225)]
try self.assertSettingsUpdateWithAck(newSettings, sender: self.serverChannel, receiver: self.clientChannel)
// This test will validate that the server will not allow the HPACK block to exceed the set max header list size
// even before the header block is complete. To do that, we're going to send a HEADERS frame and then a sequence of
// CONTINUATION frames. These will never decompress to a valid block, but we don't expect them to get that far.
let weirdHeadersFrame: [UInt8] = [
0x00, 0x00, 0x01, // 3-byte payload length (1 bytes)
0x01, // 1-byte frame type (HEADERS)
0x00, // 1-byte flags (none)
0x00, 0x00, 0x00, 0x01, // 4-byte stream identifier
0x82, // payload
]
let weirdContinuationFrame: [UInt8] = [
0x00, 0x00, 0x01, // 3-byte payload length (1 bytes)
0x09, // 1-byte frame type (CONTINUATION)
0x00, // 1-byte flags (none)
0x00, 0x00, 0x00, 0x01, // 4-byte stream identifier
0x82, // payload
]
// Each byte of payload is accompanied by 9 bytes of overhead, so we need to allocate enough space to send 255 bytes of payload.
var firstBuffer = self.serverChannel.allocator.buffer(capacity: 10 * 225)
firstBuffer.writeBytes(weirdHeadersFrame)
for _ in 0..<224 {
firstBuffer.writeBytes(weirdContinuationFrame)
}
// Sending this should not result in an error.
XCTAssertNoThrow(try self.serverChannel.writeInbound(firstBuffer))
XCTAssertNoThrow(XCTAssertNil(try self.serverChannel.readOutbound(as: ByteBuffer.self)))
// But if we send one more frame, that will be treated as a violation of SETTINGS_MAX_HEADER_LIST_SIZE.
XCTAssertThrowsError(try self.serverChannel.writeInbound(firstBuffer.getSlice(at: firstBuffer.writerIndex - 10, length: 10)!)) { error in
XCTAssertEqual(error as? NIOHTTP2Errors.ExcessivelyLargeHeaderBlock, NIOHTTP2Errors.excessivelyLargeHeaderBlock())
}
guard let responseFrame = try assertNoThrowWithValue(self.serverChannel.readOutbound(as: ByteBuffer.self)) else {
XCTFail("Did not receive response frame")
return
}
XCTAssertNoThrow(try self.clientChannel.writeInbound(responseFrame))
try self.clientChannel.assertReceivedFrame().assertGoAwayFrame(lastStreamID: .maxID, errorCode: UInt32(HTTP2ErrorCode.protocolError.networkCode), opaqueData: nil)
}
func testForbidsExceedingMaxHeaderListSizeBeforeDecodingSingleFrame() throws {
// Begin by getting the connection up.
try self.basicHTTP2Connection()
// The server is going to shrink its value for max header list size.
let newSettings = [HTTP2Setting(parameter: .maxHeaderListSize, value: 225)]
try self.assertSettingsUpdateWithAck(newSettings, sender: self.serverChannel, receiver: self.clientChannel)
// This test will validate that the server will not allow the HPACK block to exceed the set max header list size
// even before the header block is complete. To do that, we're going to send a HEADERS frame that is itself too long to expect
// to decode.
let weirdHeadersFrame: [UInt8] = [
0x00, 0x00, 0xE2, // 3-byte payload length (226 bytes)
0x01, // 1-byte frame type (HEADERS)
0x00, // 1-byte flags (none)
0x00, 0x00, 0x00, 0x01, // 4-byte stream identifier
]
// We don't even need the body, we shouldn't get that far.
var buffer = self.serverChannel.allocator.buffer(capacity: 9)
buffer.writeBytes(weirdHeadersFrame)
// This frame will be treated as a violation of SETTINGS_MAX_HEADER_LIST_SIZE.
XCTAssertThrowsError(try self.serverChannel.writeInbound(buffer)) { error in
XCTAssertEqual(error as? NIOHTTP2Errors.ExcessivelyLargeHeaderBlock, NIOHTTP2Errors.excessivelyLargeHeaderBlock())
}
guard let responseFrame = try assertNoThrowWithValue(self.serverChannel.readOutbound(as: ByteBuffer.self)) else {
XCTFail("Did not receive response frame")
return
}
XCTAssertNoThrow(try self.clientChannel.writeInbound(responseFrame))
try self.clientChannel.assertReceivedFrame().assertGoAwayFrame(lastStreamID: .maxID, errorCode: UInt32(HTTP2ErrorCode.protocolError.networkCode), opaqueData: nil)
}
func testNoStreamWindowUpdateOnEndStreamFrameFromServer() throws {
let maxFrameSize = (1 << 24) - 1 // Max value of SETTINGS_MAX_FRAME_SIZE is 2^24-1.
let clientSettings = nioDefaultSettings + [HTTP2Setting(parameter: .maxFrameSize, value: maxFrameSize)]
// Begin by getting the connection up.
// We add the stream multiplexer here because it manages automatic flow control, and because we want the server
// to correctly confirm we don't receive a frame for the child stream.
let childHandler = InboundFramePayloadRecorder()
try self.basicHTTP2Connection(clientSettings: clientSettings) { channel in
// Here we send a large response: 65535 bytes in size.
let responseHeaders = HPACKHeaders([(":status", "200"), ("content-length", "65535")])
var responseBody = self.clientChannel.allocator.buffer(capacity: 65535)
responseBody.writeBytes(Array(repeating: UInt8(0x04), count: 65535))
let respFramePayload = HTTP2Frame.FramePayload.headers(.init(headers: responseHeaders))
channel.write(respFramePayload, promise: nil)
// Now prepare the large body.
let respBodyFramePayload = HTTP2Frame.FramePayload.data(.init(data: .byteBuffer(responseBody), endStream: true))
channel.writeAndFlush(respBodyFramePayload, promise: nil)
return channel.pipeline.addHandler(childHandler)
}
// Now we're going to send a small request.
let headers = HPACKHeaders([(":path", "/"), (":method", "POST"), (":scheme", "https"), (":authority", "localhost")])
// We're going to open a stream and queue up the frames for that stream.
let handler = try self.clientChannel.pipeline.handler(type: HTTP2StreamMultiplexer.self).wait()
var reqFrame: HTTP2Frame.FramePayload? = nil
handler.createStreamChannel(promise: nil) { channel in
// We need END_STREAM set here, because that will force the stream to be closed on the response.
reqFrame = HTTP2Frame.FramePayload.headers(.init(headers: headers, endStream: true))
channel.writeAndFlush(reqFrame, promise: nil)
return channel.eventLoop.makeSucceededFuture(())
}
self.clientChannel.embeddedEventLoop.run()
// Ok, we now want to send this data to the server.
self.interactInMemory(self.clientChannel, self.serverChannel)
// The server should have seen 1 window update frame for the connection only.
try self.serverChannel.assertReceivedFrame().assertWindowUpdateFrame(streamID: 0, windowIncrement: 65535)
// And only the request frame frame for the child stream, as there was no need to open its stream window.
childHandler.receivedFrames.assertFramePayloadsMatch([reqFrame!])
// No other frames should be emitted, though the client may have many in a child stream.
self.serverChannel.assertNoFramesReceived()
XCTAssertNoThrow(XCTAssertTrue(try self.clientChannel.finish().isClean))
XCTAssertNoThrow(XCTAssertTrue(try self.serverChannel.finish().isClean))
}
func testNoStreamWindowUpdateOnEndStreamFrameFromClient() throws {
let maxFrameSize = (1 << 24) - 1 // Max value of SETTINGS_MAX_FRAME_SIZE is 2^24-1.
let serverSettings = nioDefaultSettings + [HTTP2Setting(parameter: .maxFrameSize, value: maxFrameSize)]
// Begin by getting the connection up.
// We add the stream multiplexer here because it manages automatic flow control, and because we want the server
// to correctly confirm we don't receive a frame for the child stream.
let childHandler = FrameRecorderHandler()
try self.basicHTTP2Connection(serverSettings: serverSettings) { channel in
return channel.eventLoop.makeSucceededFuture(())
}
// Now we're going to send a large request: 65535 bytes in size
let headers = HPACKHeaders([(":path", "/"), (":method", "POST"), (":scheme", "https"), (":authority", "localhost")])
// We're going to open a stream and queue up the frames for that stream.
let handler = try self.clientChannel.pipeline.handler(type: HTTP2StreamMultiplexer.self).wait()
handler.createStreamChannel(promise: nil) { channel in
let reqFrame = HTTP2Frame.FramePayload.headers(.init(headers: headers))
channel.write(reqFrame, promise: nil)
var requestBody = self.clientChannel.allocator.buffer(capacity: 65535)
requestBody.writeBytes(Array(repeating: UInt8(0x04), count: 65535))
// Now prepare the large body. We need END_STREAM set.
let reqBodyFrame = HTTP2Frame.FramePayload.data(.init(data: .byteBuffer(requestBody), endStream: true))
channel.writeAndFlush(reqBodyFrame, promise: nil)
return channel.pipeline.addHandler(childHandler)
}
self.clientChannel.embeddedEventLoop.run()
// Ok, we now want to send this data to the server.
self.interactInMemory(self.clientChannel, self.serverChannel)
// The client should have seen a window update on the connection.
try self.clientChannel.assertReceivedFrame().assertWindowUpdateFrame(streamID: 0, windowIncrement: 65535)
// And nothing for the child stream, as there was no need to open its stream window.
childHandler.receivedFrames.assertFramesMatch([])
// No other frames should be emitted, though the server may have many in a child stream.
self.clientChannel.assertNoFramesReceived()
XCTAssertNoThrow(XCTAssertTrue(try self.clientChannel.finish().isClean))
XCTAssertNoThrow(XCTAssertTrue(try self.serverChannel.finish().isClean))
}
func testGreasedSettingsAreTolerated() throws {
let settings = nioDefaultSettings + [HTTP2Setting(parameter: .init(extensionSetting: 0xfafa), value: 0xf0f0f0f0)]
XCTAssertNoThrow(try self.basicHTTP2Connection(clientSettings: settings))
}
func testStreamCreationOrder() throws {
try self.basicHTTP2Connection()
let multiplexer = HTTP2StreamMultiplexer(mode: .client, channel: self.clientChannel, inboundStreamInitializer: nil)
XCTAssertNoThrow(try self.clientChannel.pipeline.addHandler(multiplexer).wait())
let streamAPromise = self.clientChannel.eventLoop.makePromise(of: Channel.self)
multiplexer.createStreamChannel(promise: streamAPromise) { channel in
return channel.eventLoop.makeSucceededFuture(())
}
self.clientChannel.embeddedEventLoop.run()
let streamA = try assertNoThrowWithValue(try streamAPromise.futureResult.wait())
let streamBPromise = self.clientChannel.eventLoop.makePromise(of: Channel.self)
multiplexer.createStreamChannel(promise: streamBPromise) { channel in
return channel.eventLoop.makeSucceededFuture(())
}
self.clientChannel.embeddedEventLoop.run()
let streamB = try assertNoThrowWithValue(try streamBPromise.futureResult.wait())
let headers = HPACKHeaders([(":path", "/"), (":method", "GET"), (":authority", "localhost"), (":scheme", "https")])
let headersFramePayload = HTTP2Frame.FramePayload.headers(.init(headers: headers, endStream: false))
// Write on 'B' first.
XCTAssertNoThrow(try streamB.writeAndFlush(headersFramePayload).wait())
XCTAssertEqual(try streamB.getOption(HTTP2StreamChannelOptions.streamID).wait(), HTTP2StreamID(1))
// Now write on stream 'A'. This would fail on frame-based stream channel.
XCTAssertNoThrow(try streamA.writeAndFlush(headersFramePayload).wait())
XCTAssertEqual(try streamA.getOption(HTTP2StreamChannelOptions.streamID).wait(), HTTP2StreamID(3))
}
func testStreamClosedInvalidRequestHeaders() throws {
// Begin by getting the connection up.
try self.basicHTTP2Connection()
// We're now going to try to send a request from the client to the server. This request
// contains an invalid header ("transfer-encoding", "chunked"), which will trigger an error.
// We'll confirm that the error notifies that this stream was created and then closed.
let headers = HPACKHeaders([
(":path", "/"), (":method", "POST"), (":scheme", "https"), (":authority", "localhost"), ("transfer-encoding", "chunked")
])
let clientStreamID = HTTP2StreamID(1)
let reqFrame = HTTP2Frame(streamID: clientStreamID, payload: .headers(.init(headers: headers)))
XCTAssertThrowsError(try self.clientChannel.writeAndFlush(reqFrame).wait()) { error in
XCTAssertEqual(
error as? NIOHTTP2Errors.ForbiddenHeaderField,
NIOHTTP2Errors.forbiddenHeaderField(name: "transfer-encoding", value: "chunked")
)
}
XCTAssertThrowsError(try self.clientChannel.throwIfErrorCaught()) { error in
guard let streamError = error as? NIOHTTP2Errors.StreamError else {
XCTFail("Unexpected error kind: \(error)")
return
}
XCTAssertEqual(streamError.streamID, 1)
XCTAssertEqual(
streamError.baseError as? NIOHTTP2Errors.ForbiddenHeaderField,
NIOHTTP2Errors.forbiddenHeaderField(name: "transfer-encoding", value: "chunked")
)
}
XCTAssertNoThrow(try self.clientChannel.finish())
XCTAssertNoThrow(try self.serverChannel.finish())
}
func testHTTP2HandlerDoesNotFlushExcessively() throws {
try self.basicHTTP2Connection()
class FlushCounter: ChannelOutboundHandler {
typealias OutboundIn = Never
var flushCount = 0
func flush(context: ChannelHandlerContext) {
self.flushCount += 1
context.flush()
}
}
let counter = FlushCounter()
XCTAssertNoThrow(try self.clientChannel.pipeline.syncOperations.addHandler(counter, position: .first))
// 'channelReadComplete' should cause the HTTP2Handler to emit a flush if any frames have
// been written. No frames have been written, so no flush should be emitted.
self.clientChannel.pipeline.fireChannelReadComplete()
XCTAssertEqual(counter.flushCount, 0)
}
func testHTTPHandlerIgnoresInboundAltServiceFrames() throws {
try self.basicHTTP2Connection()
let h2ClientHandler = try self.clientChannel.pipeline.syncOperations.handler(type: NIOHTTP2Handler.self)
let h2FrameRecorder = FrameRecorderHandler()
try self.clientChannel.pipeline.syncOperations.addHandler(h2FrameRecorder, position: .after(h2ClientHandler))
let altServiceFrameBytes: [UInt8] = [
0x00, 0x00, 0x15, // 3-byte payload length (21 bytes)
0x0a, // 1-byte frame type (ALTSVC)
0x00, // 1-byte flags (none)
0x00, 0x00, 0x00, 0x00, // 4-byte stream identifier
0x00, 0x09, // 2-byte origin size ("apple.com"; 9 bytes)
]
var buffer = self.clientChannel.allocator.buffer(bytes: altServiceFrameBytes)
buffer.writeString("apple.com")
buffer.writeString("h2=\":8000\"")
XCTAssertEqual(buffer.readableBytes, 30) // 9 (header) + 21 (origin, field)
XCTAssertNoThrow(try self.clientChannel.writeInbound(buffer))
// Frame should be dropped.
XCTAssert(h2FrameRecorder.receivedFrames.isEmpty)
}
func testHTTPHandlerIgnoresInboundOriginFrames() throws {
try self.basicHTTP2Connection()
let h2ClientHandler = try self.clientChannel.pipeline.syncOperations.handler(type: NIOHTTP2Handler.self)
let h2FrameRecorder = FrameRecorderHandler()
try self.clientChannel.pipeline.syncOperations.addHandler(h2FrameRecorder, position: .after(h2ClientHandler))
let originFrameBytes: [UInt8] = [
0x00, 0x00, 0x2a, // 3-byte payload length (42 bytes)
0x0c, // 1-byte frame type (ORIGIN)
0x00, // 1-byte flags (none)
0x00, 0x00, 0x00, 0x00 // 4-byte stream identifier,
]
var buffer = self.clientChannel.allocator.buffer(bytes: originFrameBytes)
var originBytesWritten = 0
for origin in ["apple.com", "www.apple.com", "www2.apple.com"] {
originBytesWritten += try buffer.writeLengthPrefixed(as: UInt16.self) {
$0.writeString(origin)
}
}
XCTAssertEqual(originBytesWritten, 42)
XCTAssertEqual(buffer.readableBytes, 51)
XCTAssertNoThrow(try self.clientChannel.writeInbound(buffer))
// Frame should be dropped.
XCTAssert(h2FrameRecorder.receivedFrames.isEmpty)
}
}
| apache-2.0 | 0b1e24c8696b77121183b3e1eac5dc1f | 54.040646 | 222 | 0.685941 | 5.021131 | false | false | false | false |
lorentey/swift | test/Constraints/if_expr.swift | 3 | 3039 | // RUN: %target-typecheck-verify-swift
func useInt(_ x: Int) {}
func useDouble(_ x: Double) {}
class B {
init() {}
}
class D1 : B {
override init() { super.init() }
}
class D2 : B {
override init() { super.init() }
}
func useB(_ x: B) {}
func useD1(_ x: D1) {}
func useD2(_ x: D2) {}
var a = true ? 1 : 0 // should infer Int
var b : Double = true ? 1 : 0 // should infer Double
var c = true ? 1 : 0.0 // should infer Double
var d = true ? 1.0 : 0 // should infer Double
useInt(a)
useDouble(b)
useDouble(c)
useDouble(d)
var z = true ? a : b // expected-error{{result values in '? :' expression have mismatching types 'Int' and 'Double'}}
var _ = a ? b : b // expected-error{{cannot convert value of type 'Int' to expected condition type 'Bool'}}
var e = true ? B() : B() // should infer B
var f = true ? B() : D1() // should infer B
var g = true ? D1() : B() // should infer B
var h = true ? D1() : D1() // should infer D1
var i = true ? D1() : D2() // should infer B
useB(e)
useD1(e) // expected-error{{cannot convert value of type 'B' to expected argument type 'D1'}}
useB(f)
useD1(f) // expected-error{{cannot convert value of type 'B' to expected argument type 'D1'}}
useB(g)
useD1(g) // expected-error{{cannot convert value of type 'B' to expected argument type 'D1'}}
useB(h)
useD1(h)
useB(i)
useD1(i) // expected-error{{cannot convert value of type 'B' to expected argument type 'D1'}}
useD2(i) // expected-error{{cannot convert value of type 'B' to expected argument type 'D2'}}
var x = true ? 1 : 0
var y = 22 ? 1 : 0 // expected-error{{cannot convert value of type 'Int' to expected condition type 'Bool'}}
_ = x ? x : x // expected-error {{cannot convert value of type 'Int' to expected condition type 'Bool'}}
_ = true ? x : 1.2 // expected-error {{result values in '? :' expression have mismatching types 'Int' and 'Double'}}
_ = (x: true) ? true : false // expected-error {{cannot convert value of type '(x: Bool)' to expected condition type 'Bool'}}
_ = (x: 1) ? true : false // expected-error {{cannot convert value of type '(x: Int)' to expected condition type 'Bool'}}
let ib: Bool! = false
let eb: Bool? = .some(false)
let conditional = ib ? "Broken" : "Heart" // should infer Bool!
let conditional = eb ? "Broken" : "Heart" // expected-error {{value of optional type 'Bool?' must be unwrapped}}
// expected-note@-1{{coalesce using '??' to provide a default when the optional value contains 'nil'}}
// expected-note@-2{{force-unwrap using '!' to abort execution if the optional value contains 'nil'}}
// <rdar://problem/39586166> - crash when IfExpr has UnresolvedType in condition
struct Delegate {
var shellTasks: [ShellTask]
}
extension Array {
subscript(safe safe: Int) -> Element? {
get { }
set { }
}
}
struct ShellTask {
var commandLine: [String]
}
let delegate = Delegate(shellTasks: [])
_ = delegate.shellTasks[safe: 0]?.commandLine.compactMap({ $0.asString.hasPrefix("") ? $0 : nil }).count ?? 0
// expected-error@-1 {{value of type 'String' has no member 'asString'}}
| apache-2.0 | 5c15ee56bc715b2aed8f4529238244af | 33.931034 | 125 | 0.651201 | 3.24333 | false | false | false | false |
ddrccw/CCCircleSpinLayer-swift | CCCircleSpinLayer-swift/CCCircleSpinLayer.swift | 1 | 11237 | //
// CCCircleSpinLayer.swift
// Demo
//
// Created by ccw on 14-8-11.
// Copyright (c) 2014年 ccw. All rights reserved.
//
import Foundation
import UIKit
import QuartzCore
func degreesToRadians(angle: Float) -> Float {
return (angle / 180.0 * Float(M_PI))
}
private func cirlePositionOnCircle(angleInDegrees: Float, radius: Float, offset: Float) -> CGPoint
{
let radians: Float = degreesToRadians(angleInDegrees - 90)
return CGPointMake(CGFloat(radius * cos(radians) + offset),
CGFloat(radius * sin(radians) + offset))
}
let kNumberOfCircle: Int = 8
let kCircleShownKey = "kCircleShownKey"
let kCircleShowHideDuration = 0.5
class CCCircleSpinLayer: CALayer {
var offsetIndex: Int = 0
var isAnimating: Bool = false
var color: UIColor!
var circles: [CALayer]!
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
convenience init(size: CGSize, color: UIColor, animated: Bool) {
self.init(size: size, circleRadius:0, color: color, animated: animated)
}
init(size: CGSize, circleRadius: Float, color: UIColor, animated: Bool)
{
super.init()
self.backgroundColor = UIColor(red: 0.1529, green: 0.6824, blue: 0.3765, alpha: 1).CGColor
self.bounds = CGRectMake(0, 0, size.width, size.height)
let beginTime = CACurrentMediaTime()
let outterRadius = Float(min(size.width, size.height) / 2.0)
assert(circleRadius <= outterRadius / 2.0, "circleRaidus should be less than a quarter of size")
var circleRadius_: Float = 0.0
if circleRadius <= 0 {
circleRadius_ = outterRadius / 4
}
else {
circleRadius_ = circleRadius
}
let innerRadius: Float = outterRadius - circleRadius_
let angleInDegrees: Float = 360.0 / Float(kNumberOfCircle)
offsetIndex = Int.min
isAnimating = animated
var arr: [CALayer] = Array()
for var i = 0; i < kNumberOfCircle; ++i {
let circle = CALayer()
circle.bounds = CGRectMake(0, 0, CGFloat(circleRadius_), CGFloat(circleRadius_))
circle.backgroundColor = color.CGColor
circle.cornerRadius = CGRectGetHeight(circle.bounds) * 0.5
circle.setValue(false, forKey: kCircleShownKey)
circle.position = cirlePositionOnCircle(angleInDegrees * Float(i), innerRadius, outterRadius)
circle.opacity = 0
if animated {
let anim = circleScaleAnimationAtIndex(i, beginTime: beginTime)
circle.addAnimation(anim, forKey: "scale-anim")
}
self.addSublayer(circle)
arr.append(circle)
}
self.circles = arr
}
func showInProgress(progress: Float) {
if -1 <= progress && progress <= 1 {
let offsetIndex = Int(ceilf(progress * Float(kNumberOfCircle)))
if self.offsetIndex == offsetIndex { return }
var layer: CALayer!
var animGroup: CAAnimationGroup!
var shown = false
if progress >= 0 {
//show
for var i = 0; i < abs(offsetIndex); ++i {
layer = self.circles[i]
shown = layer.valueForKey(kCircleShownKey).boolValue
if !shown {
animGroup = self.circleShowAnimationGroup()
layer.addAnimation(animGroup, forKey: "show-anim")
layer.setValue(true, forKey: kCircleShownKey)
}
}
}
else {
//hide
for var i = kNumberOfCircle - 1; i > abs(offsetIndex) - 1; --i {
layer = self.circles[i]
shown = layer.valueForKey(kCircleShownKey).boolValue
if shown {
animGroup = self.circleHideAnimationGroup()
layer.addAnimation(animGroup, forKey: "hide-anim")
layer.setValue(false, forKey: kCircleShownKey)
}
}
}
self.offsetIndex = offsetIndex
}
else {
self.resetLayersAndAnimated(false)
}
}
func startAnimating() {
if !self.isAnimating {
self.resetLayersAndAnimated(true)
self.resumeLayers()
self.isAnimating = true
}
}
func stopAnimating() {
if self.isAnimating == true {
self.resetLayersAndAnimated(false)
self.isAnimating = false
}
}
////////////////////////////////////////////////////////////////////////////
// MARK: - private method
private func circleHideAnimationGroup() -> CAAnimationGroup {
let scaleAnim = CAKeyframeAnimation(keyPath: "transform")
scaleAnim.keyTimes = [0, 0.1, 0.3, 1]
scaleAnim.values = [
NSValue(CATransform3D: CATransform3DScale(CATransform3DIdentity, 1, 1, 1)),
NSValue(CATransform3D: CATransform3DScale(CATransform3DIdentity, 1.1, 1.1, 1)),
NSValue(CATransform3D: CATransform3DScale(CATransform3DIdentity, 1, 1, 1)),
NSValue(CATransform3D: CATransform3DScale(CATransform3DIdentity, 0, 0, 1))
]
let opacityAnim = CAKeyframeAnimation(keyPath: "opacity")
opacityAnim.keyTimes = [0, 0.1, 0.3, 1]
opacityAnim.values = [1, 1, 1, 0]
let animGroup = CAAnimationGroup()
animGroup.duration = kCircleShowHideDuration
animGroup.animations = [scaleAnim, opacityAnim]
animGroup.fillMode = kCAFillModeForwards
animGroup.removedOnCompletion = false
animGroup.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
return animGroup
}
private func circleShowAnimationGroup() -> CAAnimationGroup {
let scaleAnim = CAKeyframeAnimation(keyPath: "transform")
scaleAnim.keyTimes = [0, 0.7, 0.9, 1]
scaleAnim.values = [
NSValue(CATransform3D: CATransform3DScale(CATransform3DIdentity, 0, 0, 1)),
NSValue(CATransform3D: CATransform3DScale(CATransform3DIdentity, 1, 1, 1)),
NSValue(CATransform3D: CATransform3DScale(CATransform3DIdentity, 1.1, 1.1, 1)),
NSValue(CATransform3D: CATransform3DScale(CATransform3DIdentity, 1, 1, 1))
]
let opacityAnim = CAKeyframeAnimation(keyPath: "opacity")
opacityAnim.keyTimes = [0, 0.7, 0.9, 1]
opacityAnim.values = [0, 1, 1, 1]
let animGroup = CAAnimationGroup()
animGroup.duration = kCircleShowHideDuration
animGroup.animations = [scaleAnim, opacityAnim]
animGroup.fillMode = kCAFillModeForwards
animGroup.removedOnCompletion = false
animGroup.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
return animGroup
}
private func circleScaleAnimationAtIndex(index: Int, beginTime: CFTimeInterval)
-> CAAnimationGroup
{
let opacityAnim = CABasicAnimation(keyPath: "opacity")
opacityAnim.fromValue = 1
opacityAnim.toValue = 1
opacityAnim.removedOnCompletion = false
opacityAnim.fillMode = kCAFillModeForwards
opacityAnim.beginTime = 0
let scaleAnim = CAKeyframeAnimation(keyPath: "transform")
scaleAnim.removedOnCompletion = false
scaleAnim.fillMode = kCAFillModeForwards
scaleAnim.beginTime = 0
let multiple: Double = 1;
scaleAnim.duration = CFTimeInterval(kNumberOfCircle) / 7.0 * multiple
var keyTimes: [CFTimeInterval] = Array()
var values: [NSValue] = Array()
var timeFunctions: [CAMediaTimingFunction] = Array()
keyTimes.append(0)
var keyTime: CFTimeInterval = 0.0
var t = CATransform3DIdentity
var scale: Float = 0.0
var mid: Int = (kNumberOfCircle - 2) / 2
var midOffset = mid + 1
for var i = 1; i < kNumberOfCircle + 1; ++i {
keyTime = CFTimeInterval(scaleAnim.duration / multiple) / CFTimeInterval(kNumberOfCircle) * CFTimeInterval(i)
keyTime = min(keyTime, 1)
keyTimes.append(keyTime)
if i == 1 || i == kNumberOfCircle {
scale = 0
}
else if i <= midOffset {
scale = min(1.0 / Float(mid) * (Float(i - 1)), 1)
}
else {
scale = min(1.0 / Float(mid) * (Float(kNumberOfCircle - i)), 1)
}
t = CATransform3DScale(CATransform3DIdentity, CGFloat(scale), CGFloat(scale), 1)
values.append(NSValue(CATransform3D: t))
timeFunctions.append(CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut))
}
scaleAnim.keyTimes = keyTimes
scaleAnim.values = values
scaleAnim.timingFunctions = timeFunctions
let animGroup = CAAnimationGroup()
animGroup.duration = scaleAnim.duration
animGroup.beginTime = beginTime - Double(65536 * scaleAnim.duration)
animGroup.beginTime += Double(index) * (scaleAnim.duration / Double(kNumberOfCircle))
animGroup.repeatCount = HUGE
animGroup.animations = [opacityAnim, scaleAnim]
animGroup.removedOnCompletion = false
animGroup.fillMode = kCAFillModeForwards
animGroup.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
return animGroup
}
private func resetLayersAndAnimated(animated: Bool) {
let currentTime = CACurrentMediaTime()
let currentTimeInSuperLayer = self.convertTime(currentTime, fromLayer: nil)
var anim: CAAnimationGroup!
var circle: CALayer!
for var i = 0; i < self.circles.count; ++i {
circle = self.circles[i]
circle.removeAllAnimations()
circle.opacity = 0
circle.setValue(false, forKey: kCircleShownKey)
if animated {
let currentTimeInCircle = circle.convertTime(currentTimeInSuperLayer, fromLayer: self)
anim = self.circleScaleAnimationAtIndex(i, beginTime: currentTimeInCircle)
circle.addAnimation(anim, forKey: "scale-anim")
}
}
if animated {
self.pauseLayersAtTime(currentTime)
}
else {
self.speed = 1
self.timeOffset = 0
self.beginTime = 0
}
}
private func pauseLayersAtTime(time: CFTimeInterval) {
let pausedTime = self.convertTime(time, fromLayer: nil)
self.speed = 0
self.timeOffset = pausedTime
}
private func resumeLayers() {
let pausedTime = self.timeOffset
self.speed = 1
self.timeOffset = 0
self.beginTime = 0
let timeSincePause = self.convertTime(CACurrentMediaTime(), fromLayer: nil) - pausedTime
self.beginTime = timeSincePause
}
}
| bsd-2-clause | d2f45519e28c376236bba674236ce179 | 34.44164 | 121 | 0.594393 | 4.96904 | false | false | false | false |
vector-im/vector-ios | RiotSwiftUI/Modules/Room/RoomAccess/RoomAccessTypeChooser/Coordinator/RoomAccessTypeChooserCoordinator.swift | 1 | 3156 | //
// Copyright 2021 New Vector Ltd
//
// 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 SwiftUI
struct RoomAccessTypeChooserCoordinatorParameters {
let roomId: String
let allowsRoomUpgrade: Bool
let session: MXSession
}
final class RoomAccessTypeChooserCoordinator: Coordinator, Presentable {
// MARK: - Properties
// MARK: Private
private let parameters: RoomAccessTypeChooserCoordinatorParameters
private let roomAccessTypeChooserHostingController: UIViewController
private var roomAccessTypeChooserViewModel: RoomAccessTypeChooserViewModelProtocol
// MARK: Public
// Must be used only internally
var childCoordinators: [Coordinator] = []
var callback: ((RoomAccessTypeChooserCoordinatorAction) -> Void)?
// MARK: - Setup
@available(iOS 14.0, *)
init(parameters: RoomAccessTypeChooserCoordinatorParameters) {
self.parameters = parameters
let viewModel = RoomAccessTypeChooserViewModel(roomAccessTypeChooserService: RoomAccessTypeChooserService(roomId: parameters.roomId, allowsRoomUpgrade: parameters.allowsRoomUpgrade, session: parameters.session))
let room = parameters.session.room(withRoomId: parameters.roomId)
let view = RoomAccessTypeChooser(viewModel: viewModel.context, roomName: room?.displayName ?? "")
roomAccessTypeChooserViewModel = viewModel
roomAccessTypeChooserHostingController = VectorHostingController(rootView: view)
}
// MARK: - Public
func start() {
MXLog.debug("[RoomAccessTypeChooserCoordinator] did start.")
roomAccessTypeChooserViewModel.callback = { [weak self] result in
MXLog.debug("[RoomAccessTypeChooserCoordinator] RoomAccessTypeChooserViewModel did complete with result \(result).")
guard let self = self else { return }
switch result {
case .spaceSelection(let roomId, let accessType):
self.callback?(.spaceSelection(roomId, accessType))
case .done(let roomId):
self.callback?(.done(roomId))
case .cancel(let roomId):
self.callback?(.cancel(roomId))
case .roomUpgradeNeeded(let roomId, let versionOverride):
self.callback?(.roomUpgradeNeeded(roomId, versionOverride))
}
}
}
func toPresentable() -> UIViewController {
return self.roomAccessTypeChooserHostingController
}
func handleRoomUpgradeResult(_ result: RoomUpgradeCoordinatorResult) {
self.roomAccessTypeChooserViewModel.handleRoomUpgradeResult(result)
}
}
| apache-2.0 | 9d4b5bf7355f29595892d4dabf6614e0 | 38.45 | 219 | 0.707224 | 5.517483 | false | false | false | false |
oisinlavery/HackingWithSwift | project14-oisin/project14-oisin/GameScene.swift | 1 | 4083 | //
// GameScene.swift
// project14-oisin
//
// Created by Oisín Lavery on 12/2/15.
// Copyright (c) 2015 Google. All rights reserved.
//
import SpriteKit
import GameKit
class GameScene: SKScene {
var slots = [WhackSlot]()
var gameScore: SKLabelNode!
var score: Int = 0 {
didSet {
gameScore.text = "Score: \(score)"
}
}
var popupTime = 0.85
var numRounds = 0
override func didMoveToView(view: SKView) {
let background = SKSpriteNode(imageNamed: "whackBackground")
background.position = CGPoint(x: 512, y: 384)
background.blendMode = .Replace
background.zPosition = -1
addChild(background)
gameScore = SKLabelNode(fontNamed: "Chalkduster")
gameScore.text = "Score: 0"
gameScore.position = CGPoint(x: 8, y: 8)
gameScore.horizontalAlignmentMode = .Left
gameScore.fontSize = 48
addChild(gameScore)
for i in 0 ..< 5 { createSlotAt(CGPoint(x: 100 + (i * 170), y: 410)) }
for i in 0 ..< 4 { createSlotAt(CGPoint(x: 180 + (i * 170), y: 320)) }
for i in 0 ..< 5 { createSlotAt(CGPoint(x: 100 + (i * 170), y: 230)) }
for i in 0 ..< 4 { createSlotAt(CGPoint(x: 180 + (i * 170), y: 140)) }
RunAfterDelay(1.0, block: { [unowned self] in
self.createEnemy()
})
}
func createEnemy() {
++numRounds
if numRounds >= 30 {
for slot in slots {
slot.hide()
}
let gameOver = SKSpriteNode(imageNamed: "gameOver")
gameOver.position = CGPoint(x: 512, y: 384)
gameOver.zPosition = 1
addChild(gameOver)
return
}
popupTime *= 0.991
slots = GKRandomSource.sharedRandom().arrayByShufflingObjectsInArray(slots) as! [WhackSlot]
slots[0].show(hideTime: popupTime)
if RandomInt(min: 0, max: 12) > 4 { slots[1].show(hideTime: popupTime) }
if RandomInt(min: 0, max: 12) > 8 { slots[2].show(hideTime: popupTime) }
if RandomInt(min: 0, max: 12) > 10 { slots[3].show(hideTime: popupTime) }
if RandomInt(min: 0, max: 12) > 11 { slots[4].show(hideTime: popupTime) }
let minDelay = popupTime / 2.0
let maxDelay = popupTime * 2
RunAfterDelay(RandomDouble(min: minDelay, max: maxDelay)) { [unowned self] in
self.createEnemy()
}
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
if let touch = touches.first {
let location = touch.locationInNode(self)
let nodes = nodesAtPoint(location)
for node in nodes {
if node.name == "charFriend" {
let whackSlot = node.parent!.parent as! WhackSlot
if !whackSlot.visible { continue }
if whackSlot.isHit { continue }
whackSlot.hit()
score -= 5
runAction(SKAction.playSoundFileNamed("whackBad.caf", waitForCompletion:false))
} else if node.name == "charEnemy" {
let whackSlot = node.parent!.parent as! WhackSlot
if !whackSlot.visible { continue }
if whackSlot.isHit { continue }
whackSlot.charNode.xScale = 0.85
whackSlot.charNode.yScale = 0.85
whackSlot.hit()
++score
runAction(SKAction.playSoundFileNamed("whack.caf", waitForCompletion:false))
}
}
}
}
func createSlotAt(pos: CGPoint) {
let slot = WhackSlot()
slot.configureAtPosition(pos)
addChild(slot)
slots.append(slot)
}
override func update(currentTime: CFTimeInterval) {
/* Called before each frame is rendered */
}
}
| unlicense | 30259a770438172f5ddb20101df86697 | 30.643411 | 99 | 0.530377 | 4.638636 | false | false | false | false |
ibari/ios-yelp | Yelp/BusinessCell.swift | 1 | 1738 | //
// BusinessCell.swift
// Yelp
//
// Created by Ian on 5/13/15.
// Copyright (c) 2015 Ian Bari. All rights reserved.
//
import UIKit
class BusinessCell: UITableViewCell {
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var thumbImageView: UIImageView!
@IBOutlet weak var distanceLabel: UILabel!
@IBOutlet weak var ratingImageView: UIImageView!
@IBOutlet weak var reviewsCountLabel: UILabel!
@IBOutlet weak var addressLabel: UILabel!
@IBOutlet weak var categoriesLabel: UILabel!
var business: Business! {
didSet {
nameLabel.text = business.name
thumbImageView.setImageWithURL(business.imageURL)
distanceLabel.text = business.distance
ratingImageView.setImageWithURL(business.ratingImageURL)
reviewsCountLabel.text = "\(business.reviewCount!) Reviews"
addressLabel.text = business.address
categoriesLabel.text = business.categories
}
}
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
thumbImageView.layer.cornerRadius = 5
thumbImageView.clipsToBounds = true
nameLabel.preferredMaxLayoutWidth = nameLabel.frame.size.width
addressLabel.preferredMaxLayoutWidth = addressLabel.frame.size.width
categoriesLabel.preferredMaxLayoutWidth = categoriesLabel.frame.size.width
}
override func layoutSubviews() {
super.layoutSubviews()
nameLabel.preferredMaxLayoutWidth = nameLabel.frame.size.width
addressLabel.preferredMaxLayoutWidth = addressLabel.frame.size.width
categoriesLabel.preferredMaxLayoutWidth = categoriesLabel.frame.size.width
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
}
}
| gpl-2.0 | 470b7f50a5ace36fcb8e850efe297e51 | 30.6 | 78 | 0.743959 | 4.994253 | false | false | false | false |
nathawes/swift | test/SILGen/indirect_enum.swift | 12 | 25615 |
// RUN: %target-swift-emit-silgen -module-name indirect_enum -Xllvm -sil-print-debuginfo %s | %FileCheck %s
indirect enum TreeA<T> {
case Nil
case Leaf(T)
case Branch(left: TreeA<T>, right: TreeA<T>)
}
// CHECK-LABEL: sil hidden [ossa] @$s13indirect_enum11TreeA_cases_1l1ryx_AA0C1AOyxGAGtlF : $@convention(thin) <T> (@in_guaranteed T, @guaranteed TreeA<T>, @guaranteed TreeA<T>) -> () {
func TreeA_cases<T>(_ t: T, l: TreeA<T>, r: TreeA<T>) {
// CHECK: bb0([[ARG1:%.*]] : $*T, [[ARG2:%.*]] : @guaranteed $TreeA<T>, [[ARG3:%.*]] : @guaranteed $TreeA<T>):
// CHECK: [[METATYPE:%.*]] = metatype $@thin TreeA<T>.Type
// CHECK-NEXT: [[NIL:%.*]] = enum $TreeA<T>, #TreeA.Nil!enumelt
// CHECK-NOT: destroy_value [[NIL]]
let _ = TreeA<T>.Nil
// CHECK-NEXT: [[METATYPE:%.*]] = metatype $@thin TreeA<T>.Type
// CHECK-NEXT: [[T_BUF:%.*]] = alloc_stack $T
// CHECK-NEXT: copy_addr [[ARG1]] to [initialization] [[T_BUF]] : $*T
// CHECK-NEXT: [[BOX:%.*]] = alloc_box $<τ_0_0> { var τ_0_0 } <T>
// CHECK-NEXT: [[PB:%.*]] = project_box [[BOX]]
// CHECK-NEXT: copy_addr [take] [[T_BUF]] to [initialization] [[PB]]
// CHECK-NEXT: [[LEAF:%.*]] = enum $TreeA<T>, #TreeA.Leaf!enumelt, [[BOX]]
// CHECK-NEXT: destroy_value [[LEAF]]
// CHECK-NEXT: dealloc_stack [[T_BUF]] : $*T
let _ = TreeA<T>.Leaf(t)
// CHECK-NEXT: [[METATYPE:%.*]] = metatype $@thin TreeA<T>.Type
// CHECK-NEXT: [[ARG2_COPY:%.*]] = copy_value [[ARG2]]
// CHECK-NEXT: [[ARG3_COPY:%.*]] = copy_value [[ARG3]]
// CHECK-NEXT: [[BOX:%.*]] = alloc_box $<τ_0_0> { var (left: TreeA<τ_0_0>, right: TreeA<τ_0_0>) } <T>
// CHECK-NEXT: [[PB:%.*]] = project_box [[BOX]]
// CHECK-NEXT: [[LEFT:%.*]] = tuple_element_addr [[PB]] : $*(left: TreeA<T>, right: TreeA<T>), 0
// CHECK-NEXT: [[RIGHT:%.*]] = tuple_element_addr [[PB]] : $*(left: TreeA<T>, right: TreeA<T>), 1
// CHECK-NEXT: store [[ARG2_COPY]] to [init] [[LEFT]]
// CHECK-NEXT: store [[ARG3_COPY]] to [init] [[RIGHT]]
// CHECK-NEXT: [[BRANCH:%.*]] = enum $TreeA<T>, #TreeA.Branch!enumelt, [[BOX]]
// CHECK-NEXT: destroy_value [[BRANCH]]
let _ = TreeA<T>.Branch(left: l, right: r)
}
// CHECK: // end sil function '$s13indirect_enum11TreeA_cases_1l1ryx_AA0C1AOyxGAGtlF'
// CHECK-LABEL: sil hidden [ossa] @$s13indirect_enum16TreeA_reabstractyyS2icF : $@convention(thin) (@guaranteed @callee_guaranteed (Int) -> Int) -> () {
func TreeA_reabstract(_ f: @escaping (Int) -> Int) {
// CHECK: bb0([[ARG:%.*]] : @guaranteed $@callee_guaranteed (Int) -> Int):
// CHECK: [[METATYPE:%.*]] = metatype $@thin TreeA<(Int) -> Int>.Type
// CHECK-NEXT: [[ARG_COPY:%.*]] = copy_value [[ARG]]
// CHECK-NEXT: [[BOX:%.*]] = alloc_box $<τ_0_0> { var τ_0_0 } <(Int) -> Int>
// CHECK-NEXT: [[PB:%.*]] = project_box [[BOX]]
// CHECK: [[THUNK:%.*]] = function_ref @$sS2iIegyd_S2iIegnr_TR
// CHECK-NEXT: [[FN:%.*]] = partial_apply [callee_guaranteed] [[THUNK]]([[ARG_COPY]])
// CHECK-NEXT: [[FNC:%.*]] = convert_function [[FN]]
// CHECK-NEXT: store [[FNC]] to [init] [[PB]]
// CHECK-NEXT: [[LEAF:%.*]] = enum $TreeA<(Int) -> Int>, #TreeA.Leaf!enumelt, [[BOX]]
// CHECK-NEXT: destroy_value [[LEAF]]
// CHECK: return
let _ = TreeA<(Int) -> Int>.Leaf(f)
}
// CHECK: } // end sil function '$s13indirect_enum16TreeA_reabstractyyS2icF'
enum TreeB<T> {
case Nil
case Leaf(T)
indirect case Branch(left: TreeB<T>, right: TreeB<T>)
}
// CHECK-LABEL: sil hidden [ossa] @$s13indirect_enum11TreeB_cases_1l1ryx_AA0C1BOyxGAGtlF
func TreeB_cases<T>(_ t: T, l: TreeB<T>, r: TreeB<T>) {
// CHECK: [[METATYPE:%.*]] = metatype $@thin TreeB<T>.Type
// CHECK: [[NIL:%.*]] = alloc_stack $TreeB<T>
// CHECK-NEXT: inject_enum_addr [[NIL]] : $*TreeB<T>, #TreeB.Nil!enumelt
// CHECK-NEXT: destroy_addr [[NIL]]
// CHECK-NEXT: dealloc_stack [[NIL]]
let _ = TreeB<T>.Nil
// CHECK-NEXT: [[METATYPE:%.*]] = metatype $@thin TreeB<T>.Type
// CHECK-NEXT: [[T_BUF:%.*]] = alloc_stack $T
// CHECK-NEXT: copy_addr %0 to [initialization] [[T_BUF]]
// CHECK-NEXT: [[LEAF:%.*]] = alloc_stack $TreeB<T>
// CHECK-NEXT: [[PAYLOAD:%.*]] = init_enum_data_addr [[LEAF]] : $*TreeB<T>, #TreeB.Leaf!enumelt
// CHECK-NEXT: copy_addr [take] [[T_BUF]] to [initialization] [[PAYLOAD]]
// CHECK-NEXT: inject_enum_addr [[LEAF]] : $*TreeB<T>, #TreeB.Leaf!enumelt
// CHECK-NEXT: destroy_addr [[LEAF]]
// CHECK-NEXT: dealloc_stack [[LEAF]]
// CHECK-NEXT: dealloc_stack [[T_BUF]]
let _ = TreeB<T>.Leaf(t)
// CHECK-NEXT: [[METATYPE:%.*]] = metatype $@thin TreeB<T>.Type
// CHECK-NEXT: [[ARG1_COPY:%.*]] = alloc_stack $TreeB<T>
// CHECK-NEXT: copy_addr %1 to [initialization] [[ARG1_COPY]] : $*TreeB<T>
// CHECK-NEXT: [[ARG2_COPY:%.*]] = alloc_stack $TreeB<T>
// CHECK-NEXT: copy_addr %2 to [initialization] [[ARG2_COPY]] : $*TreeB<T>
// CHECK-NEXT: [[BOX:%.*]] = alloc_box $<τ_0_0> { var (left: TreeB<τ_0_0>, right: TreeB<τ_0_0>) } <T>
// CHECK-NEXT: [[PB:%.*]] = project_box [[BOX]]
// CHECK-NEXT: [[LEFT:%.*]] = tuple_element_addr [[PB]]
// CHECK-NEXT: [[RIGHT:%.*]] = tuple_element_addr [[PB]]
// CHECK-NEXT: copy_addr [take] [[ARG1_COPY]] to [initialization] [[LEFT]] : $*TreeB<T>
// CHECK-NEXT: copy_addr [take] [[ARG2_COPY]] to [initialization] [[RIGHT]] : $*TreeB<T>
// CHECK-NEXT: [[BRANCH:%.*]] = alloc_stack $TreeB<T>
// CHECK-NEXT: [[PAYLOAD:%.*]] = init_enum_data_addr [[BRANCH]]
// CHECK-NEXT: store [[BOX]] to [init] [[PAYLOAD]]
// CHECK-NEXT: inject_enum_addr [[BRANCH]] : $*TreeB<T>, #TreeB.Branch!enumelt
// CHECK-NEXT: destroy_addr [[BRANCH]]
// CHECK-NEXT: dealloc_stack [[BRANCH]]
// CHECK-NEXT: dealloc_stack [[ARG2_COPY]]
// CHECK-NEXT: dealloc_stack [[ARG1_COPY]]
let _ = TreeB<T>.Branch(left: l, right: r)
// CHECK: return
}
// CHECK-LABEL: sil hidden [ossa] @$s13indirect_enum13TreeInt_cases_1l1rySi_AA0cD0OAFtF : $@convention(thin) (Int, @guaranteed TreeInt, @guaranteed TreeInt) -> ()
func TreeInt_cases(_ t: Int, l: TreeInt, r: TreeInt) {
// CHECK: bb0([[ARG1:%.*]] : $Int, [[ARG2:%.*]] : @guaranteed $TreeInt, [[ARG3:%.*]] : @guaranteed $TreeInt):
// CHECK: [[METATYPE:%.*]] = metatype $@thin TreeInt.Type
// CHECK-NEXT: [[NIL:%.*]] = enum $TreeInt, #TreeInt.Nil!enumelt
// CHECK-NOT: destroy_value [[NIL]]
let _ = TreeInt.Nil
// CHECK-NEXT: [[METATYPE:%.*]] = metatype $@thin TreeInt.Type
// CHECK-NEXT: [[LEAF:%.*]] = enum $TreeInt, #TreeInt.Leaf!enumelt, [[ARG1]]
// CHECK-NOT: destroy_value [[LEAF]]
let _ = TreeInt.Leaf(t)
// CHECK-NEXT: [[METATYPE:%.*]] = metatype $@thin TreeInt.Type
// CHECK-NEXT: [[ARG2_COPY:%.*]] = copy_value [[ARG2]] : $TreeInt
// CHECK-NEXT: [[ARG3_COPY:%.*]] = copy_value [[ARG3]] : $TreeInt
// CHECK-NEXT: [[BOX:%.*]] = alloc_box ${ var (left: TreeInt, right: TreeInt) }
// CHECK-NEXT: [[PB:%.*]] = project_box [[BOX]]
// CHECK-NEXT: [[LEFT:%.*]] = tuple_element_addr [[PB]]
// CHECK-NEXT: [[RIGHT:%.*]] = tuple_element_addr [[PB]]
// CHECK-NEXT: store [[ARG2_COPY]] to [init] [[LEFT]]
// CHECK-NEXT: store [[ARG3_COPY]] to [init] [[RIGHT]]
// CHECK-NEXT: [[BRANCH:%.*]] = enum $TreeInt, #TreeInt.Branch!enumelt, [[BOX]]
// CHECK-NEXT: destroy_value [[BRANCH]]
let _ = TreeInt.Branch(left: l, right: r)
}
// CHECK: } // end sil function '$s13indirect_enum13TreeInt_cases_1l1rySi_AA0cD0OAFtF'
enum TreeInt {
case Nil
case Leaf(Int)
indirect case Branch(left: TreeInt, right: TreeInt)
}
enum TrivialButIndirect {
case Direct(Int)
indirect case Indirect(Int)
}
func a() {}
func b<T>(_ x: T) {}
func c<T>(_ x: T, _ y: T) {}
func d() {}
// CHECK-LABEL: sil hidden [ossa] @$s13indirect_enum11switchTreeAyyAA0D1AOyxGlF : $@convention(thin) <T> (@guaranteed TreeA<T>) -> () {
func switchTreeA<T>(_ x: TreeA<T>) {
// CHECK: bb0([[ARG:%.*]] : @guaranteed $TreeA<T>):
// -- x +0
// CHECK: switch_enum [[ARG]] : $TreeA<T>,
// CHECK: case #TreeA.Nil!enumelt: [[NIL_CASE:bb1]],
// CHECK: case #TreeA.Leaf!enumelt: [[LEAF_CASE:bb2]],
// CHECK: case #TreeA.Branch!enumelt: [[BRANCH_CASE:bb3]],
switch x {
// CHECK: [[NIL_CASE]]:
// CHECK: function_ref @$s13indirect_enum1ayyF
// CHECK: br [[OUTER_CONT:bb[0-9]+]]
case .Nil:
a()
// CHECK: [[LEAF_CASE]]([[LEAF_BOX:%.*]] : @guaranteed $<τ_0_0> { var τ_0_0 } <T>):
// CHECK: [[VALUE:%.*]] = project_box [[LEAF_BOX]]
// CHECK: copy_addr [[VALUE]] to [initialization] [[X:%.*]] : $*T
// CHECK: function_ref @$s13indirect_enum1b{{[_0-9a-zA-Z]*}}F
// CHECK: destroy_addr [[X]]
// CHECK: dealloc_stack [[X]]
// -- x +0
// CHECK: br [[OUTER_CONT]]
case .Leaf(let x):
b(x)
// CHECK: [[BRANCH_CASE]]([[NODE_BOX:%.*]] : @guaranteed $<τ_0_0> { var (left: TreeA<τ_0_0>, right: TreeA<τ_0_0>) } <T>):
// CHECK: [[TUPLE_ADDR:%.*]] = project_box [[NODE_BOX]]
// CHECK: [[TUPLE:%.*]] = load_borrow [[TUPLE_ADDR]]
// CHECK: ([[LEFT:%.*]], [[RIGHT:%.*]]) = destructure_tuple [[TUPLE]]
// CHECK: switch_enum [[LEFT]] : $TreeA<T>,
// CHECK: case #TreeA.Leaf!enumelt: [[LEAF_CASE_LEFT:bb[0-9]+]],
// CHECK: default [[FAIL_LEFT:bb[0-9]+]]
// CHECK: [[LEAF_CASE_LEFT]]([[LEFT_LEAF_BOX:%.*]] : @guaranteed $<τ_0_0> { var τ_0_0 } <T>):
// CHECK: [[LEFT_LEAF_VALUE:%.*]] = project_box [[LEFT_LEAF_BOX]]
// CHECK: switch_enum [[RIGHT]] : $TreeA<T>,
// CHECK: case #TreeA.Leaf!enumelt: [[LEAF_CASE_RIGHT:bb[0-9]+]],
// CHECK: default [[FAIL_RIGHT:bb[0-9]+]]
// CHECK: [[LEAF_CASE_RIGHT]]([[RIGHT_LEAF_BOX:%.*]] : @guaranteed $<τ_0_0> { var τ_0_0 } <T>):
// CHECK: [[RIGHT_LEAF_VALUE:%.*]] = project_box [[RIGHT_LEAF_BOX]]
// CHECK: copy_addr [[LEFT_LEAF_VALUE]]
// CHECK: copy_addr [[RIGHT_LEAF_VALUE]]
// -- x +1
// CHECK: br [[OUTER_CONT]]
// CHECK: [[FAIL_RIGHT]]([[DEFAULT_VAL:%.*]] : @guaranteed
// CHECK: br [[DEFAULT:bb[0-9]+]]
// CHECK: [[FAIL_LEFT]]([[DEFAULT_VAL:%.*]] : @guaranteed
// CHECK: br [[DEFAULT]]
case .Branch(.Leaf(let x), .Leaf(let y)):
c(x, y)
// CHECK: [[DEFAULT]]:
// -- x +0
default:
d()
}
// CHECK: [[OUTER_CONT:%.*]]:
// -- x +0
}
// CHECK: } // end sil function '$s13indirect_enum11switchTreeAyyAA0D1AOyxGlF'
// CHECK-LABEL: sil hidden [ossa] @$s13indirect_enum11switchTreeB{{[_0-9a-zA-Z]*}}F
func switchTreeB<T>(_ x: TreeB<T>) {
// CHECK: copy_addr %0 to [initialization] [[SCRATCH:%.*]] :
// CHECK: switch_enum_addr [[SCRATCH]]
switch x {
// CHECK: bb{{.*}}:
// CHECK: function_ref @$s13indirect_enum1ayyF
// CHECK: destroy_addr [[SCRATCH]]
// CHECK: dealloc_stack [[SCRATCH]]
// CHECK: br [[OUTER_CONT:bb[0-9]+]]
case .Nil:
a()
// CHECK: bb{{.*}}:
// CHECK: copy_addr [[SCRATCH]] to [initialization] [[LEAF_COPY:%.*]] :
// CHECK: [[LEAF_ADDR:%.*]] = unchecked_take_enum_data_addr [[LEAF_COPY]]
// CHECK: copy_addr [take] [[LEAF_ADDR]] to [initialization] [[LEAF:%.*]] :
// CHECK: function_ref @$s13indirect_enum1b{{[_0-9a-zA-Z]*}}F
// CHECK: destroy_addr [[LEAF]]
// CHECK: dealloc_stack [[LEAF]]
// CHECK-NOT: destroy_addr [[LEAF_COPY]]
// CHECK: dealloc_stack [[LEAF_COPY]]
// CHECK: destroy_addr [[SCRATCH]]
// CHECK: dealloc_stack [[SCRATCH]]
// CHECK: br [[OUTER_CONT]]
case .Leaf(let x):
b(x)
// CHECK: bb{{.*}}:
// CHECK: copy_addr [[SCRATCH]] to [initialization] [[TREE_COPY:%.*]] :
// CHECK: [[TREE_ADDR:%.*]] = unchecked_take_enum_data_addr [[TREE_COPY]]
// -- box +1 immutable
// CHECK: [[BOX:%.*]] = load [take] [[TREE_ADDR]]
// CHECK: [[TUPLE:%.*]] = project_box [[BOX]]
// CHECK: [[LEFT:%.*]] = tuple_element_addr [[TUPLE]]
// CHECK: [[RIGHT:%.*]] = tuple_element_addr [[TUPLE]]
// CHECK: switch_enum_addr [[LEFT]] {{.*}}, default [[LEFT_FAIL:bb[0-9]+]]
// CHECK: bb{{.*}}:
// CHECK: copy_addr [[LEFT]] to [initialization] [[LEFT_COPY:%.*]] :
// CHECK: [[LEFT_LEAF:%.*]] = unchecked_take_enum_data_addr [[LEFT_COPY]] : $*TreeB<T>, #TreeB.Leaf
// CHECK: switch_enum_addr [[RIGHT]] {{.*}}, default [[RIGHT_FAIL:bb[0-9]+]]
// CHECK: bb{{.*}}:
// CHECK: copy_addr [[RIGHT]] to [initialization] [[RIGHT_COPY:%.*]] :
// CHECK: [[RIGHT_LEAF:%.*]] = unchecked_take_enum_data_addr [[RIGHT_COPY]] : $*TreeB<T>, #TreeB.Leaf
// CHECK: copy_addr [take] [[LEFT_LEAF]] to [initialization] [[X:%.*]] :
// CHECK: copy_addr [take] [[RIGHT_LEAF]] to [initialization] [[Y:%.*]] :
// CHECK: function_ref @$s13indirect_enum1c{{[_0-9a-zA-Z]*}}F
// CHECK: destroy_addr [[Y]]
// CHECK: dealloc_stack [[Y]]
// CHECK: destroy_addr [[X]]
// CHECK: dealloc_stack [[X]]
// CHECK-NOT: destroy_addr [[RIGHT_COPY]]
// CHECK: dealloc_stack [[RIGHT_COPY]]
// CHECK-NOT: destroy_addr [[LEFT_COPY]]
// CHECK: dealloc_stack [[LEFT_COPY]]
// -- box +0
// CHECK: destroy_value [[BOX]]
// CHECK-NOT: destroy_addr [[TREE_COPY]]
// CHECK: dealloc_stack [[TREE_COPY]]
// CHECK: destroy_addr [[SCRATCH]]
// CHECK: dealloc_stack [[SCRATCH]]
case .Branch(.Leaf(let x), .Leaf(let y)):
c(x, y)
// CHECK: [[RIGHT_FAIL]]:
// CHECK: destroy_addr [[LEFT_LEAF]]
// CHECK-NOT: destroy_addr [[LEFT_COPY]]
// CHECK: dealloc_stack [[LEFT_COPY]]
// CHECK: destroy_value [[BOX]]
// CHECK-NOT: destroy_addr [[TREE_COPY]]
// CHECK: dealloc_stack [[TREE_COPY]]
// CHECK: br [[INNER_CONT:bb[0-9]+]]
// CHECK: [[LEFT_FAIL]]:
// CHECK: destroy_value [[BOX]]
// CHECK-NOT: destroy_addr [[TREE_COPY]]
// CHECK: dealloc_stack [[TREE_COPY]]
// CHECK: br [[INNER_CONT:bb[0-9]+]]
// CHECK: [[INNER_CONT]]:
// CHECK: function_ref @$s13indirect_enum1dyyF
// CHECK: destroy_addr [[SCRATCH]]
// CHECK: dealloc_stack [[SCRATCH]]
// CHECK: br [[OUTER_CONT]]
default:
d()
}
// CHECK: [[OUTER_CONT]]:
// CHECK: return
}
// Make sure that switchTreeInt obeys ownership invariants.
//
// CHECK-LABEL: sil hidden [ossa] @$s13indirect_enum13switchTreeInt{{[_0-9a-zA-Z]*}}F
func switchTreeInt(_ x: TreeInt) {
switch x {
case .Nil:
a()
case .Leaf(let x):
b(x)
case .Branch(.Leaf(let x), .Leaf(let y)):
c(x, y)
default:
d()
}
}
// CHECK: } // end sil function '$s13indirect_enum13switchTreeInt{{[_0-9a-zA-Z]*}}F'
// CHECK-LABEL: sil hidden [ossa] @$s13indirect_enum10guardTreeA{{[_0-9a-zA-Z]*}}F
func guardTreeA<T>(_ tree: TreeA<T>) {
// CHECK: bb0([[ARG:%.*]] : @guaranteed $TreeA<T>):
do {
// CHECK: [[ARG_COPY:%.*]] = copy_value [[ARG]]
// CHECK: switch_enum [[ARG_COPY]] : $TreeA<T>, case #TreeA.Nil!enumelt: [[YES:bb[0-9]+]], default [[NO1:bb[0-9]+]]
// CHECK: [[YES]]:
guard case .Nil = tree else { return }
// CHECK: [[X:%.*]] = alloc_stack $T
// CHECK: [[ARG_COPY:%.*]] = copy_value [[ARG]]
// CHECK: switch_enum [[ARG_COPY]] : $TreeA<T>, case #TreeA.Leaf!enumelt: [[YES:bb[0-9]+]], default [[NO2:bb[0-9]+]]
// CHECK: [[YES]]([[BOX:%.*]] : @owned $<τ_0_0> { var τ_0_0 } <T>):
// CHECK: [[VALUE_ADDR:%.*]] = project_box [[BOX]]
// CHECK: [[TMP:%.*]] = alloc_stack
// CHECK: copy_addr [[VALUE_ADDR]] to [initialization] [[TMP]]
// CHECK: copy_addr [take] [[TMP]] to [initialization] [[X]]
// CHECK: destroy_value [[BOX]]
guard case .Leaf(let x) = tree else { return }
// CHECK: [[ARG_COPY:%.*]] = copy_value [[ARG]]
// CHECK: switch_enum [[ARG_COPY]] : $TreeA<T>, case #TreeA.Branch!enumelt: [[YES:bb[0-9]+]], default [[NO3:bb[0-9]+]]
// CHECK: [[YES]]([[BOX:%.*]] : @owned $<τ_0_0> { var (left: TreeA<τ_0_0>, right: TreeA<τ_0_0>) } <T>):
// CHECK: [[VALUE_ADDR:%.*]] = project_box [[BOX]]
// CHECK: [[TUPLE:%.*]] = load_borrow [[VALUE_ADDR]]
// CHECK: [[TUPLE_COPY:%.*]] = copy_value [[TUPLE]]
// CHECK: end_borrow [[TUPLE]]
// CHECK: ([[L:%.*]], [[R:%.*]]) = destructure_tuple [[TUPLE_COPY]]
// CHECK: destroy_value [[BOX]]
guard case .Branch(left: let l, right: let r) = tree else { return }
// CHECK: destroy_value [[R]]
// CHECK: destroy_value [[L]]
// CHECK: destroy_addr [[X]]
}
do {
// CHECK: [[ARG_COPY:%.*]] = copy_value [[ARG]]
// CHECK: switch_enum [[ARG_COPY]] : $TreeA<T>, case #TreeA.Nil!enumelt: [[YES:bb[0-9]+]], default [[NO4:bb[0-9]+]]
// CHECK: [[NO4]]([[ORIGINAL_VALUE:%.*]] : @owned $TreeA<T>):
// CHECK: destroy_value [[ORIGINAL_VALUE]]
// CHECK: [[YES]]:
// CHECK: br
if case .Nil = tree { }
// CHECK: [[X:%.*]] = alloc_stack $T
// CHECK: [[ARG_COPY:%.*]] = copy_value [[ARG]]
// CHECK: switch_enum [[ARG_COPY]] : $TreeA<T>, case #TreeA.Leaf!enumelt: [[YES:bb[0-9]+]], default [[NO5:bb[0-9]+]]
// CHECK: [[NO5]]([[ORIGINAL_VALUE:%.*]] : @owned $TreeA<T>):
// CHECK: destroy_value [[ORIGINAL_VALUE]]
// CHECK: [[YES]]([[BOX:%.*]] : @owned $<τ_0_0> { var τ_0_0 } <T>):
// CHECK: [[VALUE_ADDR:%.*]] = project_box [[BOX]]
// CHECK: [[TMP:%.*]] = alloc_stack
// CHECK: copy_addr [[VALUE_ADDR]] to [initialization] [[TMP]]
// CHECK: copy_addr [take] [[TMP]] to [initialization] [[X]]
// CHECK: destroy_value [[BOX]]
// CHECK: destroy_addr [[X]]
if case .Leaf(let x) = tree { }
// CHECK: [[ARG_COPY:%.*]] = copy_value [[ARG]]
// CHECK: switch_enum [[ARG_COPY]] : $TreeA<T>, case #TreeA.Branch!enumelt: [[YES:bb[0-9]+]], default [[NO:bb[0-9]+]]
// CHECK: [[NO]]([[ORIGINAL_VALUE:%.*]] : @owned $TreeA<T>):
// CHECK: destroy_value [[ORIGINAL_VALUE]]
// CHECK: [[YES]]([[BOX:%.*]] : @owned $<τ_0_0> { var (left: TreeA<τ_0_0>, right: TreeA<τ_0_0>) } <T>):
// CHECK: [[VALUE_ADDR:%.*]] = project_box [[BOX]]
// CHECK: [[TUPLE:%.*]] = load_borrow [[VALUE_ADDR]]
// CHECK: [[TUPLE_COPY:%.*]] = copy_value [[TUPLE]]
// CHECK: end_borrow [[TUPLE]]
// CHECK: ([[L:%.*]], [[R:%.*]]) = destructure_tuple [[TUPLE_COPY]]
// CHECK: destroy_value [[BOX]]
// CHECK: destroy_value [[R]]
// CHECK: destroy_value [[L]]
if case .Branch(left: let l, right: let r) = tree { }
}
// CHECK: [[NO3]]([[ORIGINAL_VALUE:%.*]] : @owned $TreeA<T>):
// CHECK: destroy_value [[ORIGINAL_VALUE]]
// CHECK: [[NO2]]([[ORIGINAL_VALUE:%.*]] : @owned $TreeA<T>):
// CHECK: destroy_value [[ORIGINAL_VALUE]]
// CHECK: [[NO1]]([[ORIGINAL_VALUE:%.*]] : @owned $TreeA<T>):
// CHECK: destroy_value [[ORIGINAL_VALUE]]
}
// CHECK-LABEL: sil hidden [ossa] @$s13indirect_enum10guardTreeB{{[_0-9a-zA-Z]*}}F
func guardTreeB<T>(_ tree: TreeB<T>) {
do {
// CHECK: copy_addr %0 to [initialization] [[TMP1:%.*]] :
// CHECK: switch_enum_addr [[TMP1]] : $*TreeB<T>, case #TreeB.Nil!enumelt: [[YES:bb[0-9]+]], default [[NO2:bb[0-9]+]]
// CHECK: [[YES]]:
// CHECK: destroy_addr [[TMP1]]
guard case .Nil = tree else { return }
// CHECK: [[X:%.*]] = alloc_stack $T
// CHECK: copy_addr %0 to [initialization] [[TMP2:%.*]] :
// CHECK: switch_enum_addr [[TMP2]] : $*TreeB<T>, case #TreeB.Leaf!enumelt: [[YES:bb[0-9]+]], default [[NO2:bb[0-9]+]]
// CHECK: [[YES]]:
// CHECK: [[VALUE:%.*]] = unchecked_take_enum_data_addr [[TMP2]]
// CHECK: copy_addr [take] [[VALUE]] to [initialization] [[X]]
// CHECK: dealloc_stack [[TMP2]]
guard case .Leaf(let x) = tree else { return }
// CHECK: [[L:%.*]] = alloc_stack $TreeB
// CHECK: [[R:%.*]] = alloc_stack $TreeB
// CHECK: copy_addr %0 to [initialization] [[TMP3:%.*]] :
// CHECK: switch_enum_addr [[TMP3]] : $*TreeB<T>, case #TreeB.Branch!enumelt: [[YES:bb[0-9]+]], default [[NO3:bb[0-9]+]]
// CHECK: [[YES]]:
// CHECK: [[BOX_ADDR:%.*]] = unchecked_take_enum_data_addr [[TMP3]]
// CHECK: [[BOX:%.*]] = load [take] [[BOX_ADDR]]
// CHECK: [[TUPLE_ADDR:%.*]] = project_box [[BOX]]
// CHECK: copy_addr [[TUPLE_ADDR]] to [initialization] [[TUPLE_COPY:%.*]] :
// CHECK: [[L_COPY:%.*]] = tuple_element_addr [[TUPLE_COPY]]
// CHECK: copy_addr [take] [[L_COPY]] to [initialization] [[L]]
// CHECK: [[R_COPY:%.*]] = tuple_element_addr [[TUPLE_COPY]]
// CHECK: copy_addr [take] [[R_COPY]] to [initialization] [[R]]
// CHECK: destroy_value [[BOX]]
guard case .Branch(left: let l, right: let r) = tree else { return }
// CHECK: destroy_addr [[R]]
// CHECK: destroy_addr [[L]]
// CHECK: destroy_addr [[X]]
}
do {
// CHECK: copy_addr %0 to [initialization] [[TMP:%.*]] :
// CHECK: switch_enum_addr [[TMP]] : $*TreeB<T>, case #TreeB.Nil!enumelt: [[YES:bb[0-9]+]], default [[NO:bb[0-9]+]]
// CHECK: [[NO]]:
// CHECK: destroy_addr [[TMP]]
// CHECK: [[YES]]:
// CHECK: destroy_addr [[TMP]]
if case .Nil = tree { }
// CHECK: [[X:%.*]] = alloc_stack $T
// CHECK: copy_addr %0 to [initialization] [[TMP:%.*]] :
// CHECK: switch_enum_addr [[TMP]] : $*TreeB<T>, case #TreeB.Leaf!enumelt: [[YES:bb[0-9]+]], default [[NO:bb[0-9]+]]
// CHECK: [[NO]]:
// CHECK: destroy_addr [[TMP]]
// CHECK: [[YES]]:
// CHECK: [[VALUE:%.*]] = unchecked_take_enum_data_addr [[TMP]]
// CHECK: copy_addr [take] [[VALUE]] to [initialization] [[X]]
// CHECK: dealloc_stack [[TMP]]
// CHECK: destroy_addr [[X]]
if case .Leaf(let x) = tree { }
// CHECK: [[L:%.*]] = alloc_stack $TreeB
// CHECK: [[R:%.*]] = alloc_stack $TreeB
// CHECK: copy_addr %0 to [initialization] [[TMP:%.*]] :
// CHECK: switch_enum_addr [[TMP]] : $*TreeB<T>, case #TreeB.Branch!enumelt: [[YES:bb[0-9]+]], default [[NO:bb[0-9]+]]
// CHECK: [[NO]]:
// CHECK: destroy_addr [[TMP]]
// CHECK: [[YES]]:
// CHECK: [[BOX_ADDR:%.*]] = unchecked_take_enum_data_addr [[TMP]]
// CHECK: [[BOX:%.*]] = load [take] [[BOX_ADDR]]
// CHECK: [[TUPLE_ADDR:%.*]] = project_box [[BOX]]
// CHECK: copy_addr [[TUPLE_ADDR]] to [initialization] [[TUPLE_COPY:%.*]] :
// CHECK: [[L_COPY:%.*]] = tuple_element_addr [[TUPLE_COPY]]
// CHECK: copy_addr [take] [[L_COPY]] to [initialization] [[L]]
// CHECK: [[R_COPY:%.*]] = tuple_element_addr [[TUPLE_COPY]]
// CHECK: copy_addr [take] [[R_COPY]] to [initialization] [[R]]
// CHECK: destroy_value [[BOX]]
// CHECK: destroy_addr [[R]]
// CHECK: destroy_addr [[L]]
if case .Branch(left: let l, right: let r) = tree { }
}
// CHECK: [[NO3]]:
// CHECK: destroy_addr [[TMP3]]
// CHECK: [[NO2]]:
// CHECK: destroy_addr [[TMP2]]
// CHECK: [[NO1]]:
// CHECK: destroy_addr [[TMP1]]
}
// Just run guardTreeInt through the ownership verifier
//
// CHECK-LABEL: sil hidden [ossa] @$s13indirect_enum12guardTreeInt{{[_0-9a-zA-Z]*}}F
func guardTreeInt(_ tree: TreeInt) {
do {
guard case .Nil = tree else { return }
guard case .Leaf(let x) = tree else { return }
guard case .Branch(left: let l, right: let r) = tree else { return }
}
do {
if case .Nil = tree { }
if case .Leaf(let x) = tree { }
if case .Branch(left: let l, right: let r) = tree { }
}
}
// SEMANTIC ARC TODO: This test needs to be made far more comprehensive.
// CHECK-LABEL: sil hidden [ossa] @$s13indirect_enum35dontDisableCleanupOfIndirectPayloadyyAA010TrivialButG0OF : $@convention(thin) (@guaranteed TrivialButIndirect) -> () {
func dontDisableCleanupOfIndirectPayload(_ x: TrivialButIndirect) {
// CHECK: bb0([[ARG:%.*]] : @guaranteed $TrivialButIndirect):
// CHECK: [[ARG_COPY:%.*]] = copy_value [[ARG]]
// CHECK: switch_enum [[ARG_COPY]] : $TrivialButIndirect, case #TrivialButIndirect.Direct!enumelt: [[YES:bb[0-9]+]], case #TrivialButIndirect.Indirect!enumelt: [[NO:bb[0-9]+]]
//
guard case .Direct(let foo) = x else { return }
// CHECK: [[YES]]({{%.*}} : $Int):
// CHECK: [[ARG_COPY:%.*]] = copy_value [[ARG]]
// CHECK: switch_enum [[ARG_COPY]] : $TrivialButIndirect, case #TrivialButIndirect.Indirect!enumelt: [[YES:bb[0-9]+]], case #TrivialButIndirect.Direct!enumelt: [[NO2:bb[0-9]+]]
// CHECK: [[YES]]([[BOX:%.*]] : @owned ${ var Int }):
// CHECK: destroy_value [[BOX]]
// CHECK: [[NO2]]({{%.*}} : $Int):
// CHECK-NOT: destroy_value
// CHECK: [[NO]]([[PAYLOAD:%.*]] : @owned ${ var Int }):
// CHECK: destroy_value [[PAYLOAD]]
guard case .Indirect(let bar) = x else { return }
}
// CHECK: } // end sil function '$s13indirect_enum35dontDisableCleanupOfIndirectPayloadyyAA010TrivialButG0OF'
// Make sure that in these cases we do not break any ownership invariants.
class Box<T> {
var value: T
init(_ inputValue: T) { value = inputValue }
}
enum ValueWithInlineStorage<T> {
case inline(T)
indirect case box(Box<T>)
}
func switchValueWithInlineStorage<U>(v: ValueWithInlineStorage<U>) {
switch v {
case .inline:
return
case .box(let box):
return
}
}
func guardValueWithInlineStorage<U>(v: ValueWithInlineStorage<U>) {
do {
guard case .inline = v else { return }
guard case .box(let box) = v else { return }
}
do {
if case .inline = v { return }
if case .box(let box) = v { return }
}
}
| apache-2.0 | 5a4b14f8765ce4b5424cef5eafb2c75c | 42.662116 | 184 | 0.547018 | 3.085997 | false | false | false | false |
per-dalsgaard/20-apps-in-20-weeks | App 18 - DevslopesTutorials/DevslopesTutorials/AboutViewController.swift | 1 | 891 | //
// AboutViewController.swift
// DevslopesTutorials
//
// Created by Per Kristensen on 21/05/2017.
// Copyright © 2017 Per Dalsgaard. All rights reserved.
//
import UIKit
import MapKit
class AboutViewController: UIViewController {
@IBOutlet weak var mapView: MKMapView!
override func viewDidLoad() {
super.viewDidLoad()
let annotation = MKPointAnnotation()
let addressCoordinate = CLLocationCoordinate2D(latitude: 55.71961, longitude:12.3924643)
annotation.coordinate = addressCoordinate
annotation.title = "Come visit us"
annotation.subtitle = ":D"
mapView.addAnnotation(annotation)
let span = MKCoordinateSpan(latitudeDelta: 1, longitudeDelta: 1)
let region = MKCoordinateRegion(center: addressCoordinate, span: span)
mapView.setRegion(region, animated: true)
}
}
| mit | d84d4032c95ed4b975985db657dc9243 | 28.666667 | 96 | 0.685393 | 4.611399 | false | false | false | false |
FlowDK/FlowDK | FlowDK/Core/Classes/Utilities/LoadingSet.swift | 1 | 1469 |
enum LoadingState: Int {
case initial, loading, loaded, failed, cancelled
}
class Loader: NSObject {
weak var loaderSet: LoaderSet?
var state: LoadingState = .initial {
didSet {
loaderSet?.loaderDidChange(loader: self)
}
}
// Convenience
func remove() {
loaderSet?.removeLoader(self)
}
}
class LoaderSet {
private var loaders = [Loader]()
// Callbacks
var didChange: ((LoaderSet)->())?
var loaderDidChange: ((Loader)->())?
// Calculated
var loadingCount: Int {
var total = 0
for loader in loaders {
if loader.state == .loading {
total += 1
}
}
return total
}
var isLoading: Bool {
return loadingCount > 0
}
var isAllLoaded: Bool {
for loader in loaders {
if loader.state != .loaded {
return false
}
}
return true
}
// Factory
// Triggers did change
func addLoader() -> Loader {
let loader = Loader()
loaders.append(loader)
loader.loaderSet = self
didChange?(self)
return loader
}
// Triggers did change
@discardableResult
func removeLoader(_ loader: Loader) -> Loader {
if let index = loaders.index(of: loader) {
let loader = loaders.remove(at: index)
if loader.state == .loading {
loader.state = .cancelled
}
loader.loaderSet = nil
didChange?(self)
}
return loader
}
func loaderDidChange(loader: Loader) {
loaderDidChange?(loader)
}
}
| mit | a26cbb8b1e0f2ef9c63df66eccbb51d8 | 17.3625 | 50 | 0.607216 | 4.138028 | false | false | false | false |
soapyigu/LeetCode_Swift | Math/IntegerToRoman.swift | 1 | 1458 | /**
* Question Link: https://leetcode.com/problems/integer-to-roman/
* Primary idea: Add symbols from big to small, minus relative number as well
* Time Complexity: O(n), Space Complexity: O(1)
*
*/
class IntegerToRoman {
func intToRoman(_ num: Int) -> String {
guard num > 0 else {
return ""
}
let nums = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1]
let symbols = ["M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"]
var res = ""
var digit = 0
var number = num
while number > 0 {
let current = number / nums[digit]
for _ in 0..<current {
res += symbols[digit]
}
number -= current * nums[digit]
digit += 1
}
return res
}
}
// Alternate solution
class IntegerToRomanWithDictionaries {
func intToRoman(_ num: Int) -> String {
guard num > 0 else { return "" }
let thousands = ["", "M", "MM", "MMM"]
let hundreds = ["", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"]
let tens = ["", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"]
let ones = ["", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"]
return thousands[num / 1000] + hundreds[num % 1000 / 100] + tens[num % 100 / 10] + ones[num % 10]
}
}
| mit | 2a199e4c1212649d47aa413a2dcc370a | 30.021277 | 105 | 0.453361 | 3.454976 | false | false | false | false |
shridharmalimca/iOSDev | iOS/Components/MusicTransition/Pods/SRKUtility/SRKUtility-Source/Camera/SRKCamera.swift | 2 | 5381 | //
// SRKKCamera.swift
// Sagar R. Kothari
//
// Created by sagar kothari
// Copyright © 2016 sagar kothari. All rights reserved.
//
import UIKit
//import SRKImagePicker
public enum SRKCameraResponse {
case success(UIImage)
case cancelled
}
public struct SRKCamera {
fileprivate static let shared = SRKCameraViewController()
fileprivate static let sharedCrop = SRKCropCamera()
public static func openCameraController(_ viewController: UIViewController,
sourceType: UIImagePickerControllerSourceType = .photoLibrary,
cameraDevice: UIImagePickerControllerCameraDevice = .front,
canEditImage: Bool = true,
handler: @escaping ((SRKCameraResponse) -> Void)
) {
SRKCamera.shared.sourceType = sourceType
SRKCamera.shared.cameraDevice = cameraDevice
SRKCamera.shared.canEditImage = canEditImage
SRKCamera.shared.handler = handler
SRKCamera.shared.hasAppeared = false
viewController.present(SRKCamera.shared, animated: false, completion: nil)
}
public static func openCropCameraController(_ viewController: UIViewController,
sourceType: UIImagePickerControllerSourceType = .photoLibrary,
cameraDevice: UIImagePickerControllerCameraDevice = .front,
cropSize: CGSize = CGSize(width: 400, height: 400),
allowResize: Bool = false,
handler: @escaping ((SRKCameraResponse) -> Void)
) {
SRKCamera.sharedCrop.cropCam.cropSize = cropSize
SRKCamera.sharedCrop.handler = handler
if TARGET_OS_SIMULATOR != 0 {
if sourceType == .camera {
SRKCamera.sharedCrop.cropCam.imagePickerController.sourceType = .photoLibrary
} else {
SRKCamera.sharedCrop.cropCam.imagePickerController.sourceType = sourceType
}
} else {
SRKCamera.sharedCrop.cropCam.imagePickerController.sourceType = sourceType
SRKCamera.sharedCrop.cropCam.imagePickerController.cameraDevice = cameraDevice
}
SRKCamera.sharedCrop.cropCam.resizeableCropArea = allowResize
SRKCamera.sharedCrop.cropCam.delegate = SRKCamera.sharedCrop
viewController.present(SRKCamera.sharedCrop.cropCam.imagePickerController, animated: false, completion: nil)
}
}
@objc class SRKCropCamera: NSObject, SRKImagePickerDelegate {
var cropCam = SRKImagePicker(sourceType: UIImagePickerControllerSourceType.photoLibrary)!
var handler: ((SRKCameraResponse) -> Void)?
func imagePickerDidCancel(_ imagePicker: SRKImagePicker!) {
self.cropCam.imagePickerController.dismiss(animated: false)
self.handler?(SRKCameraResponse.cancelled)
}
func imagePicker(_ imagePicker: SRKImagePicker!, pickedImage image: UIImage!) {
self.cropCam.imagePickerController.dismiss(animated: false)
self.handler?(SRKCameraResponse.success(image))
}
}
@objc class SRKCameraViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
var canEditImage = true
var sourceType: UIImagePickerControllerSourceType = .photoLibrary
var cameraDevice: UIImagePickerControllerCameraDevice = .front
var handler: ((SRKCameraResponse) -> Void)?
var hasAppeared: Bool = false
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
if self.hasAppeared == false {
self.hasAppeared = true
self.presentCamera()
}
}
func presentCamera() {
if self.handler == nil {
self.dismiss(animated: false, completion: nil)
print("Please pass handler")
return
}
if let _ = Bundle.main.infoDictionary?["NSPhotoLibraryUsageDescription"], let _ = Bundle.main.infoDictionary?["NSCameraUsageDescription"] {
let imagePicker = UIImagePickerController()
imagePicker.delegate = self
if TARGET_OS_SIMULATOR != 0 {
if self.sourceType == .camera {
imagePicker.sourceType = .photoLibrary
} else {
imagePicker.sourceType = self.sourceType
}
} else {
imagePicker.sourceType = self.sourceType
imagePicker.cameraDevice = cameraDevice
}
imagePicker.allowsEditing = canEditImage
self.present(imagePicker, animated: false, completion: nil)
} else {
self.handler?(SRKCameraResponse.cancelled)
self.dismiss(animated: false, completion: nil)
print("Please add following key-value to info.plist\nNSCameraUsageDescription\nNSPhotoLibraryUsageDescription")
}
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
let selectedPhoto: UIImage
if canEditImage {
selectedPhoto = info[UIImagePickerControllerEditedImage] as! UIImage
}
else {
selectedPhoto = info[UIImagePickerControllerOriginalImage] as! UIImage
}
self.handler?(SRKCameraResponse.success(selectedPhoto))
picker.dismiss(animated: false) {
self.dismiss(animated: false, completion: nil)
}
}
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
self.handler?(SRKCameraResponse.cancelled)
picker.dismiss(animated: false) {
self.dismiss(animated: false, completion: nil)
}
}
}
| apache-2.0 | 9eb35e8450b1eeefd9ed0d10e26f1d69 | 37.156028 | 141 | 0.70316 | 4.949402 | false | false | false | false |
luosheng/OpenSim | OpenSim/DeviceManager.swift | 1 | 605 | //
// DeviceMapping.swift
// SimPholders
//
// Created by Luo Sheng on 11/9/15.
// Copyright © 2015 Luo Sheng. All rights reserved.
//
import Foundation
final class DeviceManager {
static let devicesKey = "DefaultDevices"
static let deviceRuntimePrefix = "com.apple.CoreSimulator.SimRuntime"
static let defaultManager = DeviceManager()
var runtimes = [Runtime]()
func reload(callback: @escaping ([Runtime]) -> ()) {
SimulatorController.listDevices { (runtimes) in
self.runtimes = runtimes
callback(runtimes)
}
}
}
| mit | 3814b874729e1dc62b24e0223423ea0d | 22.230769 | 73 | 0.637417 | 4.223776 | false | false | false | false |
mattrubin/SwiftGit2 | SwiftGit2/References.swift | 1 | 5578 | //
// References.swift
// SwiftGit2
//
// Created by Matt Diephouse on 1/2/15.
// Copyright (c) 2015 GitHub, Inc. All rights reserved.
//
import libgit2
/// A reference to a git object.
public protocol ReferenceType {
/// The full name of the reference (e.g., `refs/heads/master`).
var longName: String { get }
/// The short human-readable name of the reference if one exists (e.g., `master`).
var shortName: String? { get }
/// The OID of the referenced object.
var oid: OID { get }
}
public extension ReferenceType {
static func == (lhs: Self, rhs: Self) -> Bool {
return lhs.longName == rhs.longName
&& lhs.oid == rhs.oid
}
func hash(into hasher: inout Hasher) {
hasher.combine(longName)
hasher.combine(oid)
}
}
/// Create a Reference, Branch, or TagReference from a libgit2 `git_reference`.
internal func referenceWithLibGit2Reference(_ pointer: OpaquePointer) -> ReferenceType {
if git_reference_is_branch(pointer) != 0 || git_reference_is_remote(pointer) != 0 {
return Branch(pointer)!
} else if git_reference_is_tag(pointer) != 0 {
return TagReference(pointer)!
} else {
return Reference(pointer)
}
}
/// A generic reference to a git object.
public struct Reference: ReferenceType, Hashable {
/// The full name of the reference (e.g., `refs/heads/master`).
public let longName: String
/// The short human-readable name of the reference if one exists (e.g., `master`).
public let shortName: String?
/// The OID of the referenced object.
public let oid: OID
/// Create an instance with a libgit2 `git_reference` object.
public init(_ pointer: OpaquePointer) {
let shorthand = String(validatingUTF8: git_reference_shorthand(pointer))!
longName = String(validatingUTF8: git_reference_name(pointer))!
shortName = (shorthand == longName ? nil : shorthand)
oid = OID(git_reference_target(pointer).pointee)
}
}
/// A git branch.
public struct Branch: ReferenceType, Hashable {
/// The full name of the reference (e.g., `refs/heads/master`).
public let longName: String
/// The short human-readable name of the branch (e.g., `master`).
public let name: String
/// A pointer to the referenced commit.
public let commit: PointerTo<Commit>
// MARK: Derived Properties
/// The short human-readable name of the branch (e.g., `master`).
///
/// This is the same as `name`, but is declared with an Optional type to adhere to
/// `ReferenceType`.
public var shortName: String? { return name }
/// The OID of the referenced object.
///
/// This is the same as `commit.oid`, but is declared here to adhere to `ReferenceType`.
public var oid: OID { return commit.oid }
/// Whether the branch is a local branch.
public var isLocal: Bool { return longName.hasPrefix("refs/heads/") }
/// Whether the branch is a remote branch.
public var isRemote: Bool { return longName.hasPrefix("refs/remotes/") }
/// Create an instance with a libgit2 `git_reference` object.
///
/// Returns `nil` if the pointer isn't a branch.
public init?(_ pointer: OpaquePointer) {
var namePointer: UnsafePointer<Int8>? = nil
let success = git_branch_name(&namePointer, pointer)
guard success == GIT_OK.rawValue else {
return nil
}
name = String(validatingUTF8: namePointer!)!
longName = String(validatingUTF8: git_reference_name(pointer))!
var oid: OID
if git_reference_type(pointer).rawValue == GIT_REF_SYMBOLIC.rawValue {
var resolved: OpaquePointer? = nil
let success = git_reference_resolve(&resolved, pointer)
guard success == GIT_OK.rawValue else {
return nil
}
oid = OID(git_reference_target(resolved).pointee)
git_reference_free(resolved)
} else {
oid = OID(git_reference_target(pointer).pointee)
}
commit = PointerTo<Commit>(oid)
}
}
/// A git tag reference, which can be either a lightweight tag or a Tag object.
public enum TagReference: ReferenceType, Hashable {
/// A lightweight tag, which is just a name and an OID.
case lightweight(String, OID)
/// An annotated tag, which points to a Tag object.
case annotated(String, Tag)
/// The full name of the reference (e.g., `refs/tags/my-tag`).
public var longName: String {
switch self {
case let .lightweight(name, _):
return name
case let .annotated(name, _):
return name
}
}
/// The short human-readable name of the branch (e.g., `master`).
public var name: String {
return String(longName["refs/tags/".endIndex...])
}
/// The OID of the target object.
///
/// If this is an annotated tag, the OID will be the tag's target.
public var oid: OID {
switch self {
case let .lightweight(_, oid):
return oid
case let .annotated(_, tag):
return tag.target.oid
}
}
// MARK: Derived Properties
/// The short human-readable name of the branch (e.g., `master`).
///
/// This is the same as `name`, but is declared with an Optional type to adhere to
/// `ReferenceType`.
public var shortName: String? { return name }
/// Create an instance with a libgit2 `git_reference` object.
///
/// Returns `nil` if the pointer isn't a branch.
public init?(_ pointer: OpaquePointer) {
if git_reference_is_tag(pointer) == 0 {
return nil
}
let name = String(validatingUTF8: git_reference_name(pointer))!
let repo = git_reference_owner(pointer)
var oid = git_reference_target(pointer).pointee
var pointer: OpaquePointer? = nil
let result = git_object_lookup(&pointer, repo, &oid, GIT_OBJ_TAG)
if result == GIT_OK.rawValue {
self = .annotated(name, Tag(pointer!))
} else {
self = .lightweight(name, OID(oid))
}
git_object_free(pointer)
}
}
| mit | 6f9ac90c4905d6b56a98930032424664 | 28.513228 | 89 | 0.689315 | 3.44321 | false | false | false | false |
danthorpe/FX | Tests/Shared/FXOpenExchangeRatesTests.swift | 1 | 4575 | //
// FXOpenExchangeRatesTests.swift
// Money
//
// Created by Daniel Thorpe on 04/11/2015.
//
//
import XCTest
import Result
import DVR
import SwiftyJSON
import Money
@testable import MoneyFX
struct MyOpenExchangeRatesAppID: OpenExchangeRatesAppID {
static let app_id = "this_is_not_the_app_id_youre_looking_for"
}
class OpenExchangeRates<Base: MoneyType, Counter: MoneyType>: _OpenExchangeRates<Base, Counter, MyOpenExchangeRatesAppID> { }
class FreeOpenExchangeRates<Counter: MoneyType>: _ForeverFreeOpenExchangeRates<Counter, MyOpenExchangeRatesAppID> { }
class FXPaidOpenExchangeRatesTests: FXProviderTests {
typealias Provider = OpenExchangeRates<GBP,JPY>
func test__name() {
XCTAssertEqual(Provider.name(), "OpenExchangeRates.org GBPJPY")
}
func test__base_currency() {
XCTAssertEqual(Provider.BaseMoney.Currency.code, Currency.GBP.code)
}
func test__request__url_does_contain_base() {
guard let url = Provider.request().URL else {
XCTFail("Request did not return a URL")
return
}
XCTAssertTrue(url.absoluteString.containsString("&base=GBP"))
}
}
class FXFreeOpenExchangeRatesTests: FXProviderTests {
typealias Provider = FreeOpenExchangeRates<EUR>
typealias TestableProvider = TestableFXRemoteProvider<Provider>
typealias FaultyProvider = FaultyFXRemoteProvider<Provider>
func test__name() {
XCTAssertEqual(Provider.name(), "OpenExchangeRates.org USDEUR")
}
func test__session() {
XCTAssertEqual(Provider.session(), NSURLSession.sharedSession())
}
func test__base_currency() {
XCTAssertEqual(Provider.BaseMoney.Currency.code, Currency.USD.code)
}
func test__request__url_does_not_contain_base() {
guard let url = Provider.request().URL else {
XCTFail("Request did not return a URL")
return
}
XCTAssertFalse(url.absoluteString.containsString("&base="))
}
func test__quote_adaptor__with_network_error() {
let error = NSError(domain: NSURLErrorDomain, code: NSURLError.BadServerResponse.rawValue, userInfo: nil)
let network: Result<(NSData?, NSURLResponse?), NSError> = Result(error: error)
let quote = Provider.quoteFromNetworkResult(network)
XCTAssertEqual(quote.error!, FXError.NetworkError(error))
}
func test__quote_adaptor__with_no_data() {
let network: Result<(NSData?, NSURLResponse?), NSError> = Result(value: (.None, .None))
let quote = Provider.quoteFromNetworkResult(network)
XCTAssertEqual(quote.error!, FXError.NoData)
}
func test__quote_adaptor__with_garbage_data() {
let data = createGarbageData()
let network: Result<(NSData?, NSURLResponse?), NSError> = Result(value: (data, .None))
let quote = Provider.quoteFromNetworkResult(network)
XCTAssertEqual(quote.error!, FXError.InvalidData(data))
}
func test__quote_adaptor__with_missing_rate() {
var json = dvrJSONFromCassette(Provider.name())!
var rates: Dictionary<String, JSON> = json["rates"].dictionary!
rates.removeValueForKey("EUR")
json["rates"] = JSON(rates)
let data = try! json.rawData()
let network: Result<(NSData?, NSURLResponse?), NSError> = Result(value: (data, .None))
let quote = Provider.quoteFromNetworkResult(network)
XCTAssertEqual(quote.error!, FXError.RateNotFound(Provider.name()))
}
func test__faulty_provider() {
let expectation = expectationWithDescription("Test: \(#function)")
FaultyProvider.fx(100) { result in
guard let error = result.error else {
XCTFail("Should have received a network error.")
return
}
switch error {
case .NetworkError(_):
break // This is the success path.
default:
XCTFail("Returned \(error), should be a .NetworkError")
}
expectation.fulfill()
}
waitForExpectationsWithTimeout(1, handler: nil)
}
func test__fx() {
let expectation = expectationWithDescription("Test: \(#function)")
TestableProvider.fx(100) { result in
if let usd = result.value {
XCTAssertEqual(usd, 92.09)
}
else {
XCTFail("Received error: \(result.error!).")
}
expectation.fulfill()
}
waitForExpectationsWithTimeout(1, handler: nil)
}
}
| mit | 7e3f0f3d88d4ba4c5cebb90a6ec49168 | 32.152174 | 125 | 0.645902 | 4.639959 | false | true | false | false |
nethergrim/xpolo | XPolo/Pods/BFKit-Swift/Sources/BFKit/Linux/BFKit/BFApp.swift | 1 | 6801 | //
// BFApp.swift
// BFKit
//
// The MIT License (MIT)
//
// Copyright (c) 2015 - 2017 Fabrizio Brancati. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
import Foundation
#if os(iOS)
import UIKit
#endif
// MARK: - Global variables
#if os(iOS)
/// Get AppDelegate. To use it, cast to AppDelegate with "as! AppDelegate".
public let appDelegate: UIApplicationDelegate? = UIApplication.shared.delegate
#endif
#if !os(Linux)
// MARK: - Global functions
/// NSLocalizedString without comment parameter.
///
/// - Parameter key: The key of the localized string.
/// - Returns: Returns a localized string.
public func NSLocalizedString(_ key: String) -> String {
return NSLocalizedString(key, comment: "")
}
#endif
// MARK: - BFApp struct
/// This class adds some useful functions for the App.
public struct BFApp {
// MARK: - Variables
/// Used to store the BFHasBeenOpened in defaults.
private static let BFAppHasBeenOpened = "BFAppHasBeenOpened"
// MARK: - Functions
/// Executes a block only if in DEBUG mode.
///
/// More info on how to use it [here](http://stackoverflow.com/questions/26890537/disabling-nslog-for-production-in-swift-project/26891797#26891797).
///
/// - Parameter block: The block to be executed.
public static func debug(_ block: () -> Void) {
#if DEBUG
block()
#endif
}
/// Executes a block only if NOT in DEBUG mode.
///
/// More info on how to use it [here](http://stackoverflow.com/questions/26890537/disabling-nslog-for-production-in-swift-project/26891797#26891797).
///
/// - Parameter block: The block to be executed.
public static func release(_ block: () -> Void) {
#if !DEBUG
block()
#endif
}
/// If version is set returns if is first start for that version,
/// otherwise returns if is first start of the App.
///
/// - Parameter version: Version to be checked, you can use the variable BFApp.version to pass the current App version.
/// - Returns: Returns if is first start of the App or for custom version.
public static func isFirstStart(version: String = "") -> Bool {
let key: String = BFAppHasBeenOpened + "\(version)"
let defaults = UserDefaults.standard
let hasBeenOpened: Bool = defaults.bool(forKey: key)
return !hasBeenOpened
}
/// Executes a block on first start of the App, if version is set it will be for given version.
///
/// Remember to execute UI instuctions on main thread.
///
/// - Parameters:
/// - version: Version to be checked, you can use the variable BFApp.version to pass the current App version.
/// - block: The block to execute, returns isFirstStart.
public static func onFirstStart(version: String = "", block: (_ isFirstStart: Bool) -> Void) {
let key: String
if version == "" {
key = BFAppHasBeenOpened
} else {
key = BFAppHasBeenOpened + "\(version)"
}
let defaults = UserDefaults.standard
let hasBeenOpened: Bool = defaults.bool(forKey: key)
if hasBeenOpened != true {
defaults.set(true, forKey: key)
}
block(!hasBeenOpened)
}
#if !os(Linux) && !os(macOS)
/// Set the App setting for a given object and key. The file will be saved in the Library directory.
///
/// - Parameters:
/// - object: Object to set.
/// - objectKey: Key to set the object.
/// - Returns: Returns true if the operation was successful, otherwise false.
@discardableResult
public static func setAppSetting(object: Any, forKey objectKey: String) -> Bool {
return FileManager.default.setSettings(filename: BFApp.name, object: object, forKey: objectKey)
}
/// Get the App setting for a given key.
///
/// - Parameter objectKey: Key to get the object.
/// - Returns: Returns the object for the given key.
public static func getAppSetting(objectKey: String) -> Any? {
return FileManager.default.getSettings(filename: BFApp.name, forKey: objectKey)
}
#endif
}
// MARK: - BFApp extension
/// Extends BFApp with project infos.
public extension BFApp {
// MARK: - Variables
/// Return the App name.
public static var name: String = {
return BFApp.stringFromInfoDictionary(forKey: "CFBundleDisplayName")
}()
/// Returns the App version.
public static var version: String = {
return BFApp.stringFromInfoDictionary(forKey: "CFBundleShortVersionString")
}()
/// Returns the App build.
public static var build: String = {
return BFApp.stringFromInfoDictionary(forKey: "CFBundleVersion")
}()
/// Returns the App executable.
public static var executable: String = {
return BFApp.stringFromInfoDictionary(forKey: "CFBundleExecutable")
}()
/// Returns the App bundle.
public static var bundle: String = {
return BFApp.stringFromInfoDictionary(forKey: "CFBundleIdentifier")
}()
// MARK: - Functions
/// Returns a String from the Info dictionary of the App.
///
/// - Parameter key: Key to search.
/// - Returns: Returns a String from the Info dictionary of the App.
private static func stringFromInfoDictionary(forKey key: String) -> String {
guard let infoDictionary = Bundle.main.infoDictionary, let value = infoDictionary[key] as? String else {
return ""
}
return value
}
}
| gpl-3.0 | 3e3d48c49aaf8bef6c8ec5cb7aa81e12 | 35.175532 | 153 | 0.644611 | 4.642321 | false | false | false | false |
bradleybernard/EjectBar | EjectBar/Classes/Volume.swift | 1 | 10800 | //
// Volume.swift
// EjectBar
//
// Created by Bradley Bernard on 7/24/17.
// Copyright © 2017 Bradley Bernard. All rights reserved.
//
//
import Foundation
// MARK: - Type aliases
private typealias UnmountDef = (Bool, NSError?)
private typealias UnmountRet = Void
typealias UnmountCallback = (Bool, NSError?) -> Void
private typealias MAppDef = (DADisk, UnsafeMutableRawPointer?)
private typealias MAppRet = Unmanaged<DADissenter>?
private typealias MAppCallback = (DADisk, UnsafeMutableRawPointer?) -> Unmanaged<DADissenter>?
private typealias CAppDef = (DADisk, CFArray)
private typealias CAppRet = Void
private typealias CAppCallback = (DADisk, CFArray) -> Void
// MARK: - Volume constants
private enum VolumeComponent: Int {
case root = 1
}
private enum VolumeReservedNames: String {
case EFI = "EFI"
case Volumes = "Volumes"
}
// MARK: - Callbacks
private class CallbackWrapper<Input, Output> {
let callback : (Input) -> Output
init(callback: @escaping (Input) -> Output) {
self.callback = callback
}
}
// MARK: - DASession
class SessionWrapper {
static let shared: DASession? = DASessionCreate(kCFAllocatorDefault)
}
// MARK: - Volume
@objcMembers
class Volume: NSObject {
let disk: DADisk
let id: String
let name: String
let model: String
let device: String
let `protocol`: String
let path: String
let size: Int
let ejectable: Bool
let removable: Bool
init(disk: DADisk, id: String, name: String, model: String, device: String, protocol: String, path: String, size: Int, ejectable: Bool, removable: Bool) {
self.disk = disk
self.id = id
self.name = name
self.model = model
self.device = device
self.protocol = `protocol`
self.path = path
self.size = size
self.ejectable = ejectable
self.removable = removable
}
private static let keys: [URLResourceKey] = [.volumeIdentifierKey, .volumeLocalizedNameKey, .volumeTotalCapacityKey, .volumeIsEjectableKey, .volumeIsRemovableKey]
private static let set: Set<URLResourceKey> = [.volumeIdentifierKey, .volumeLocalizedNameKey, .volumeTotalCapacityKey, .volumeIsEjectableKey, .volumeIsRemovableKey]
func unmount(callback: @escaping UnmountCallback) {
let wrapper = CallbackWrapper<UnmountDef, UnmountRet>(callback: callback)
let address = UnsafeMutableRawPointer(Unmanaged.passRetained(wrapper).toOpaque())
DADiskUnmount(disk, DADiskUnmountOptions(kDADiskUnmountOptionDefault), { (volume, dissenter, context) in
guard let context = context else {
return
}
let wrapped = Unmanaged<CallbackWrapper<UnmountDef, UnmountRet>>.fromOpaque(context).takeRetainedValue()
if let dissenter = dissenter {
let code = DADissenterGetStatus(dissenter)
let hex = String(format: "%2X", code).lowercased()
let error = NSError(domain: "Disk unmount failed. Error code: 0x" + hex + ".", code: -1, userInfo: nil)
wrapped.callback((false, error))
} else {
wrapped.callback((true, nil))
}
}, address)
}
// public var kDAReturnSuccess: Int { get }
// public var kDAReturnError: Int { get } /* ( 0xF8DA0001 ) */
// public var kDAReturnBusy: Int { get } /* ( 0xF8DA0002 ) */
// public var kDAReturnBadArgument: Int { get } /* ( 0xF8DA0003 ) */
// public var kDAReturnExclusiveAccess: Int { get } /* ( 0xF8DA0004 ) */
// public var kDAReturnNoResources: Int { get } /* ( 0xF8DA0005 ) */
// public var kDAReturnNotFound: Int { get } /* ( 0xF8DA0006 ) */
// public var kDAReturnNotMounted: Int { get } /* ( 0xF8DA0007 ) */
// public var kDAReturnNotPermitted: Int { get } /* ( 0xF8DA0008 ) */
// public var kDAReturnNotPrivileged: Int { get } /* ( 0xF8DA0009 ) */
// public var kDAReturnNotReady: Int { get } /* ( 0xF8DA000A ) */
// public var kDAReturnNotWritable: Int { get } /* ( 0xF8DA000B ) */
// public var kDAReturnUnsupported: Int { get } /* ( 0xF8DA000C ) */
private func errorCodeToString(code: DAReturn) -> String {
let status = Int(code)
if status == kDAReturnSuccess {
return "Successful"
} else if status == kDAReturnError {
return ""
}
return ""
}
static func fromURL(_ url: URL) -> Volume? {
guard let session = SessionWrapper.shared, let disk = DADiskCreateFromVolumePath(kCFAllocatorDefault, session, url as CFURL) else {
return nil
}
return Volume.fromDisk(disk)
}
static func fromDisk(_ disk: DADisk) -> Volume? {
guard let dict = DADiskCopyDescription(disk),
let diskInfo = dict as? [NSString: Any],
let name = diskInfo[kDADiskDescriptionVolumeNameKey] as? String,
let size = diskInfo[kDADiskDescriptionMediaSizeKey] as? Int,
let ejectable = diskInfo[kDADiskDescriptionMediaEjectableKey] as? Bool,
let removable = diskInfo[kDADiskDescriptionMediaRemovableKey] as? Bool,
let bsdName = diskInfo[kDADiskDescriptionMediaBSDNameKey] as? String,
let path = diskInfo[kDADiskDescriptionVolumePathKey] as? URL,
let idVal = diskInfo[kDADiskDescriptionVolumeUUIDKey],
let model = diskInfo[kDADiskDescriptionDeviceModelKey] as? String,
let `protocol` = diskInfo[kDADiskDescriptionDeviceProtocolKey] as? String
else {
return nil
}
guard name != VolumeReservedNames.EFI.rawValue else {
return nil
}
let volumeID = idVal as! CFUUID
guard let cfID = CFUUIDCreateString(kCFAllocatorDefault, volumeID) else {
return nil
}
let id = cfID as String
return Volume(
disk: disk,
id: id,
name: name,
model: model,
device: bsdName,
protocol: `protocol`,
path: path.absoluteString,
size: size,
ejectable: ejectable,
removable: removable
)
}
static func isVolumeURL(_ url: URL) -> Bool {
url.pathComponents.count > 1 && url.pathComponents[VolumeComponent.root.rawValue] == VolumeReservedNames.Volumes.rawValue
}
static func queryVolumes() -> [Volume] {
guard let urls = FileManager().mountedVolumeURLs(includingResourceValuesForKeys: keys, options: []) else {
return []
}
return urls.filter { Volume.isVolumeURL($0) }.compactMap { Volume.fromURL($0) }
}
}
// MARK: - Volume Listener
class VolumeListener {
static let shared = VolumeListener()
private var callbacks = [CallbackWrapper<MAppDef, MAppRet>]()
private var listeners = [CallbackWrapper<CAppDef, CAppRet>]()
deinit {
callbacks.forEach {
let address = UnsafeMutableRawPointer(Unmanaged.passUnretained($0).toOpaque())
let _ = Unmanaged<CallbackWrapper<MAppDef, MAppRet>>.fromOpaque(address).takeRetainedValue()
}
callbacks.removeAll()
listeners.forEach {
let address = UnsafeMutableRawPointer(Unmanaged.passUnretained($0).toOpaque())
let _ = Unmanaged<CallbackWrapper<CAppDef, CAppRet>>.fromOpaque(address).takeRetainedValue()
}
listeners.removeAll()
guard let session = SessionWrapper.shared else {
return
}
DASessionSetDispatchQueue(session, nil)
}
func registerCallbacks() {
guard let session = SessionWrapper.shared else {
return
}
DASessionSetDispatchQueue(session, DispatchQueue.main)
mountApproval(session)
unmountApproval(session)
changedListener(session)
}
private func changedListener(_ session: DASession) {
let wrapper = CallbackWrapper<CAppDef, CAppRet>(callback: changedCallback)
let address = UnsafeMutableRawPointer(Unmanaged.passRetained(wrapper).toOpaque())
DARegisterDiskDescriptionChangedCallback(session, nil, nil, { (disk, info, context) in
guard let context = context else {
return
}
let wrapped = Unmanaged<CallbackWrapper<CAppDef, CAppRet>>.fromOpaque(context).takeUnretainedValue()
return wrapped.callback((disk, info))
}, address)
listeners.append(wrapper)
}
private func changedCallback(disk: DADisk, keys: CFArray) {
NotificationCenter.default.post(name: .resetTableView, object: nil, userInfo: nil)
}
private func mountApproval(_ session: DASession) {
let wrapper = CallbackWrapper<MAppDef, MAppRet>(callback: mountCallback)
let address = UnsafeMutableRawPointer(Unmanaged.passRetained(wrapper).toOpaque())
DARegisterDiskMountApprovalCallback(session, nil, { (disk, context) -> Unmanaged<DADissenter>? in
guard let context = context else {
return nil
}
let wrapped = Unmanaged<CallbackWrapper<MAppDef, MAppRet>>.fromOpaque(context).takeUnretainedValue()
return wrapped.callback((disk, context))
}, address)
callbacks.append(wrapper)
}
private func mountCallback(disk: DADisk, cont: UnsafeMutableRawPointer?) -> Unmanaged<DADissenter>? {
NotificationCenter.default.post(name: .diskMounted, object: Volume.fromDisk(disk), userInfo: nil)
return nil
}
private func unmountApproval(_ session: DASession) {
let wrapper = CallbackWrapper<MAppDef, MAppRet>(callback: unmountCallback)
let address = UnsafeMutableRawPointer(Unmanaged.passRetained(wrapper).toOpaque())
DARegisterDiskUnmountApprovalCallback(session, nil, { (disk, context) -> Unmanaged<DADissenter>? in
guard let context = context else {
return nil
}
let wrapped = Unmanaged<CallbackWrapper<MAppDef, MAppRet>>.fromOpaque(context).takeUnretainedValue()
return wrapped.callback((disk, context))
}, address)
callbacks.append(wrapper)
}
private func unmountCallback(disk: DADisk, cont: UnsafeMutableRawPointer?) -> Unmanaged<DADissenter>? {
NotificationCenter.default.post(name: .diskUnmounted, object: Volume.fromDisk(disk), userInfo: nil)
return nil
}
}
| mit | b745be58cbb4260be61dc13ce3897941 | 34.877076 | 168 | 0.625799 | 4.866607 | false | false | false | false |
overtake/TelegramSwift | Telegram-Mac/ReportReasonModalController.swift | 1 | 7758 | //
// ReportReasonModalController.swift
// Telegram
//
// Created by keepcoder on 01/03/2017.
// Copyright © 2017 Telegram. All rights reserved.
//
import Cocoa
import TGUIKit
import SwiftSignalKit
import Postbox
import TelegramCore
struct ReportReasonValue : Equatable {
let reason: ReportReason
let comment: String
}
func reportReasonSelector(context: AccountContext, buttonText: String = strings().reportReasonReport) -> Signal<ReportReasonValue, NoError> {
let promise: ValuePromise<ReportReasonValue> = ValuePromise()
let controller = ReportReasonController(callback: { reason in
promise.set(reason)
}, buttonText: buttonText)
showModal(with: controller, for: context.window)
return promise.get() |> take(1)
}
private final class ReportReasonArguments {
let selectReason:(ReportReason)->Void
init(selectReason:@escaping(ReportReason)->Void) {
self.selectReason = selectReason
}
}
private struct ReportReasonState : Equatable {
let value: ReportReasonValue
init(value: ReportReasonValue) {
self.value = value
}
func withUpdatedReason(_ value: ReportReasonValue) -> ReportReasonState {
return ReportReasonState(value: value)
}
}
private let _id_spam = InputDataIdentifier("_id_spam")
private let _id_violence = InputDataIdentifier("_id_violence")
private let _id_porno = InputDataIdentifier("_id_porno")
private let _id_childAbuse = InputDataIdentifier("_id_childAbuse")
private let _id_copyright = InputDataIdentifier("_id_copyright")
private let _id_custom = InputDataIdentifier("_id_custom")
private let _id_fake = InputDataIdentifier("_id_fake")
private let _id_custom_input = InputDataIdentifier("_id_custom_input")
private let _id_personal_details = InputDataIdentifier("_id_personal_details")
private let _id_illegal_drugs = InputDataIdentifier("_id_illegal_drugs")
extension ReportReason {
var id: InputDataIdentifier {
switch self {
case .spam:
return _id_spam
case .violence:
return _id_violence
case .porno:
return _id_porno
case .childAbuse:
return _id_childAbuse
case .copyright:
return _id_copyright
case .custom:
return _id_custom
case .fake:
return _id_fake
case .personalDetails:
return _id_personal_details
case .illegalDrugs:
return _id_illegal_drugs
default:
fatalError("unsupported")
}
}
var title: String {
switch self {
case .spam:
return strings().reportReasonSpam
case .violence:
return strings().reportReasonViolence
case .porno:
return strings().reportReasonPorno
case .childAbuse:
return strings().reportReasonChildAbuse
case .copyright:
return strings().reportReasonCopyright
case .custom:
return strings().reportReasonOther
case .fake:
return strings().reportReasonFake
case .personalDetails:
return strings().reportReasonPersonalDetails
case .illegalDrugs:
return strings().reportReasonDrugs
default:
fatalError("unsupported")
}
}
func isEqual(to other: ReportReason) -> Bool {
switch self {
case .spam:
if case .spam = other {
return true
}
case .violence:
if case .violence = other {
return true
}
case .porno:
if case .porno = other {
return true
}
case .childAbuse:
if case .childAbuse = other {
return true
}
case .copyright:
if case .copyright = other {
return true
}
case .custom:
if case .custom = other {
return true
}
case .fake:
if case .fake = other {
return true
}
default:
fatalError("unsupported")
}
return false
}
}
private func reportReasonEntries(state: ReportReasonState, arguments: ReportReasonArguments) -> [InputDataEntry] {
var entries:[InputDataEntry] = []
var sectionId:Int32 = 0
var index:Int32 = 0
entries.append(.sectionId(sectionId, type: .normal))
sectionId += 1
let reasons:[ReportReason] = [.spam, .fake, .violence, .porno, .childAbuse, .copyright, .personalDetails, .illegalDrugs]
for (i, reason) in reasons.enumerated() {
entries.append(.general(sectionId: sectionId, index: index, value: .none, error: nil, identifier: reason.id, data: InputDataGeneralData(name: reason.title, color: theme.colors.text, type: .none, viewType: bestGeneralViewType(reasons, for: i), action: {
arguments.selectReason(reason)
})))
index += 1
}
entries.append(.sectionId(sectionId, type: .normal))
sectionId += 1
// entries.append(.input(sectionId: sectionId, index: index, value: .string(state.value.comment), error: nil, identifier: _id_custom_input, mode: .plain, data: InputDataRowData(viewType: .singleItem), placeholder: nil, inputPlaceholder: strings().reportReasonOtherPlaceholder, filter: { $0 }, limit: 128))
// index += 1
//
// entries.append(.sectionId(sectionId, type: .normal))
// sectionId += 1
return entries
}
func ReportReasonController(callback: @escaping(ReportReasonValue)->Void, buttonText: String = strings().reportReasonReport) -> InputDataModalController {
let initialState = ReportReasonState(value: .init(reason: .spam, comment: ""))
let state: ValuePromise<ReportReasonState> = ValuePromise(initialState)
let stateValue: Atomic<ReportReasonState> = Atomic(value: initialState)
let updateState:((ReportReasonState)->ReportReasonState) -> Void = { f in
state.set(stateValue.modify(f))
}
var getModalController:(()->InputDataModalController?)? = nil
let arguments = ReportReasonArguments(selectReason: { reason in
callback(.init(reason: reason, comment: ""))
getModalController?()?.close()
})
let dataSignal = state.get() |> deliverOnPrepareQueue |> map { state in
return reportReasonEntries(state: state, arguments: arguments)
} |> map { entries in
return InputDataSignalValue(entries: entries)
}
let controller = InputDataController(dataSignal: dataSignal, title: strings().peerInfoReport)
controller.leftModalHeader = ModalHeaderData(image: theme.icons.modalClose, handler: {
getModalController?()?.close()
})
controller.updateDatas = { data in
updateState { current in
return current.withUpdatedReason(.init(reason: current.value.reason, comment: data[_id_custom_input]?.stringValue ?? ""))
}
return .none
}
let modalInteractions = ModalInteractions(acceptTitle: buttonText, accept: { [weak controller] in
controller?.validateInputValues()
}, drawBorder: true, singleButton: true)
let modalController = InputDataModalController(controller, modalInteractions: modalInteractions, closeHandler: { f in
f()
}, size: NSMakeSize(300, 350))
getModalController = { [weak modalController] in
return modalController
}
controller.validateData = { data in
return .success(.custom {
callback(stateValue.with { $0.value })
getModalController?()?.close()
})
}
return modalController
}
| gpl-2.0 | d99e7d764fda69782ac25d29a05af65f | 31.186722 | 308 | 0.631172 | 4.90019 | false | false | false | false |
kstaring/swift | test/expr/delayed-ident/static_var.swift | 10 | 1021 | // RUN: %target-parse-verify-swift
// Simple struct types
struct X1 {
static var AnX1 = X1()
static var NotAnX1 = 42
}
func acceptInOutX1(_ x1: inout X1) { }
var x1: X1 = .AnX1
x1 = .AnX1
x1 = .NotAnX1 // expected-error{{member 'NotAnX1' in 'X1' produces result of type 'Int', but context expects 'X1'}}
// Delayed identifier expressions as lvalues
(.AnX1 = x1)
acceptInOutX1(&(.AnX1))
// Generic struct types
struct X2<T> {
static var AnX2 = X2() // expected-error{{static stored properties not supported in generic types}}
static var NotAnX2 = 0 // expected-error {{static stored properties not supported in generic types}}
}
var x2: X2<Int> = .AnX2
x2 = .AnX2 // reference to isInvalid() decl.
x2 = .NotAnX2 // expected-error{{member 'NotAnX2' in 'X2<Int>' produces result of type 'Int', but context expects 'X2<Int>'}}
// Static variables through operators.
struct Foo {
static var Bar = Foo()
static var Wibble = Foo()
}
func & (x: Foo, y: Foo) -> Foo { }
var fooValue: Foo = .Bar & .Wibble
| apache-2.0 | 15900bcce8c9405920ce94ddbcc5c0c8 | 26.594595 | 125 | 0.675808 | 3.03869 | false | false | false | false |
fgengine/quickly | Quickly/Compositions/Standart/QImageTitleDetailValueComposition.swift | 1 | 6749 | //
// Quickly
//
open class QImageTitleDetailValueComposable : QComposable {
public var imageStyle: QImageViewStyleSheet
public var imageWidth: CGFloat
public var imageSpacing: CGFloat
public var titleStyle: QLabelStyleSheet
public var titleSpacing: CGFloat
public var detailStyle: QLabelStyleSheet
public var valueStyle: QLabelStyleSheet
public var valueSpacing: CGFloat
public init(
edgeInsets: UIEdgeInsets = UIEdgeInsets.zero,
imageStyle: QImageViewStyleSheet,
imageWidth: CGFloat = 96,
imageSpacing: CGFloat = 4,
titleStyle: QLabelStyleSheet,
titleSpacing: CGFloat = 4,
detailStyle: QLabelStyleSheet,
valueStyle: QLabelStyleSheet,
valueSpacing: CGFloat = 4
) {
self.imageStyle = imageStyle
self.imageWidth = imageWidth
self.imageSpacing = imageSpacing
self.titleStyle = titleStyle
self.titleSpacing = titleSpacing
self.detailStyle = detailStyle
self.valueStyle = valueStyle
self.valueSpacing = valueSpacing
super.init(edgeInsets: edgeInsets)
}
}
open class QImageTitleDetailValueComposition< Composable: QImageTitleDetailValueComposable > : QComposition< Composable > {
public private(set) lazy var imageView: QImageView = {
let view = QImageView(frame: self.contentView.bounds)
view.translatesAutoresizingMaskIntoConstraints = false
self.contentView.addSubview(view)
return view
}()
public private(set) lazy var titleView: QLabel = {
let view = QLabel(frame: self.contentView.bounds)
view.translatesAutoresizingMaskIntoConstraints = false
self.contentView.addSubview(view)
return view
}()
public private(set) lazy var detailView: QLabel = {
let view = QLabel(frame: self.contentView.bounds)
view.translatesAutoresizingMaskIntoConstraints = false
self.contentView.addSubview(view)
return view
}()
public private(set) lazy var valueView: QLabel = {
let view = QLabel(frame: self.contentView.bounds)
view.translatesAutoresizingMaskIntoConstraints = false
view.setContentHuggingPriority(
horizontal: UILayoutPriority(rawValue: 252),
vertical: UILayoutPriority(rawValue: 252)
)
self.contentView.addSubview(view)
return view
}()
private var _edgeInsets: UIEdgeInsets?
private var _imageWidth: CGFloat?
private var _imageSpacing: CGFloat?
private var _titleSpacing: CGFloat?
private var _valueSpacing: CGFloat?
private var _constraints: [NSLayoutConstraint] = [] {
willSet { self.contentView.removeConstraints(self._constraints) }
didSet { self.contentView.addConstraints(self._constraints) }
}
private var _imageConstraints: [NSLayoutConstraint] = [] {
willSet { self.imageView.removeConstraints(self._imageConstraints) }
didSet { self.imageView.addConstraints(self._imageConstraints) }
}
open override class func size(composable: Composable, spec: IQContainerSpec) -> CGSize {
let availableWidth = spec.containerSize.width - (composable.edgeInsets.left + composable.edgeInsets.right)
let imageSize = composable.imageStyle.size(CGSize(width: composable.imageWidth, height: availableWidth))
let valueTextSize = composable.valueStyle.size(width: availableWidth - (composable.imageWidth + composable.imageSpacing + composable.valueSpacing))
let titleTextSize = composable.titleStyle.size(width: availableWidth - (composable.imageWidth + composable.imageSpacing + valueTextSize.width + composable.valueSpacing))
let detailTextSize = composable.detailStyle.size(width: availableWidth - (composable.imageWidth + composable.imageSpacing + valueTextSize.width + composable.valueSpacing))
return CGSize(
width: spec.containerSize.width,
height: composable.edgeInsets.top + max(imageSize.height, titleTextSize.height + composable.titleSpacing + detailTextSize.height, valueTextSize.height) + composable.edgeInsets.bottom
)
}
open override func preLayout(composable: Composable, spec: IQContainerSpec) {
if self._edgeInsets != composable.edgeInsets || self._imageSpacing != composable.imageSpacing || self._titleSpacing != composable.titleSpacing || self._valueSpacing != composable.valueSpacing {
self._edgeInsets = composable.edgeInsets
self._imageSpacing = composable.imageSpacing
self._titleSpacing = composable.titleSpacing
self._valueSpacing = composable.valueSpacing
self._constraints = [
self.imageView.topLayout == self.contentView.topLayout.offset(composable.edgeInsets.top),
self.imageView.leadingLayout == self.contentView.leadingLayout.offset(composable.edgeInsets.left),
self.imageView.bottomLayout == self.contentView.bottomLayout.offset(-composable.edgeInsets.bottom),
self.titleView.topLayout == self.contentView.topLayout.offset(composable.edgeInsets.top),
self.titleView.leadingLayout == self.imageView.trailingLayout.offset(composable.imageSpacing),
self.titleView.trailingLayout == self.valueView.leadingLayout.offset(-composable.valueSpacing),
self.titleView.bottomLayout <= self.detailView.topLayout.offset(-composable.titleSpacing),
self.detailView.leadingLayout == self.imageView.trailingLayout.offset(composable.imageSpacing),
self.detailView.trailingLayout == self.valueView.leadingLayout.offset(-composable.valueSpacing),
self.detailView.bottomLayout == self.contentView.bottomLayout.offset(-composable.edgeInsets.bottom),
self.valueView.topLayout == self.contentView.topLayout.offset(composable.edgeInsets.top),
self.valueView.trailingLayout == self.contentView.trailingLayout.offset(-composable.edgeInsets.right),
self.valueView.bottomLayout == self.contentView.bottomLayout.offset(-composable.edgeInsets.bottom)
]
}
if self._imageWidth != composable.imageWidth {
self._imageWidth = composable.imageWidth
self._imageConstraints = [
self.imageView.widthLayout == composable.imageWidth
]
}
}
open override func apply(composable: Composable, spec: IQContainerSpec) {
self.imageView.apply(composable.imageStyle)
self.titleView.apply(composable.titleStyle)
self.detailView.apply(composable.detailStyle)
self.valueView.apply(composable.valueStyle)
}
}
| mit | d2a79c166d922a027f8fe631e0f621c5 | 47.905797 | 201 | 0.700548 | 5.531967 | false | false | false | false |
wikimedia/wikipedia-ios | Wikipedia/Code/TalkPageCellTopicView.swift | 1 | 23457 | import UIKit
import WMF
final class TalkPageCellTopicView: SetupView {
enum DisplayMode {
case subscribeMetadataReplies // showing subscribe, metadata, & replies
case metadataReplies // hiding subscribe, showing metadata, & replies
case none // hiding subscribe, metadata, & replies
}
// MARK: - UI Elements
lazy var stackView: UIStackView = {
let stackView = UIStackView()
stackView.axis = .vertical
stackView.distribution = .fill
stackView.alignment = .leading
stackView.spacing = 8
stackView.translatesAutoresizingMaskIntoConstraints = false
return stackView
}()
lazy var disclosureHorizontalStack: UIStackView = {
let stackView = UIStackView()
stackView.axis = .horizontal
stackView.distribution = .fill
stackView.alignment = .top
stackView.spacing = 8
stackView.translatesAutoresizingMaskIntoConstraints = false
return stackView
}()
lazy var subscribeButton: UIButton = {
let button = UIButton()
button.titleLabel?.font = UIFont.wmf_scaledSystemFont(forTextStyle: .subheadline, weight: .semibold, size: 15)
button.titleLabel?.adjustsFontForContentSizeCategory = true
button.translatesAutoresizingMaskIntoConstraints = false
button.setTitleColor(UIColor.black, for: .normal)
button.setImage(UIImage(systemName: "bell"), for: .normal)
button.tintColor = .black
button.setContentCompressionResistancePriority(.required, for: .vertical)
return button
}()
lazy var disclosureButton: UIButton = {
let button = UIButton()
button.translatesAutoresizingMaskIntoConstraints = false
button.setImage(UIImage(systemName: "chevron.down"), for: .normal)
button.tintColor = .black
button.setContentCompressionResistancePriority(.required, for: .vertical)
button.setContentCompressionResistancePriority(.required, for: .horizontal)
return button
}()
lazy var disclosureCenterSpacer: UIView = {
let view = UIView()
view.translatesAutoresizingMaskIntoConstraints = false
let widthConstraint = view.widthAnchor.constraint(equalToConstant: 99999)
widthConstraint.priority = .defaultLow
widthConstraint.isActive = true
return view
}()
lazy var topicTitleTextView: UITextView = {
let textView = UITextView()
textView.translatesAutoresizingMaskIntoConstraints = false
textView.setContentCompressionResistancePriority(.required, for: .vertical)
textView.setContentHuggingPriority(.required, for: .vertical)
textView.isScrollEnabled = false
textView.isEditable = false
textView.textContainer.lineFragmentPadding = 0
textView.textContainerInset = .zero
textView.accessibilityTraits = [.header]
textView.delegate = self
return textView
}()
lazy var timestampLabel: UILabel = {
let label = UILabel()
label.font = UIFont.wmf_scaledSystemFont(forTextStyle: .body, weight: .regular, size: 15)
label.adjustsFontForContentSizeCategory = true
label.translatesAutoresizingMaskIntoConstraints = false
label.setContentCompressionResistancePriority(.required, for: .vertical)
return label
}()
lazy var topicCommentTextView: UITextView = {
let textView = UITextView()
textView.translatesAutoresizingMaskIntoConstraints = false
textView.setContentCompressionResistancePriority(.required, for: .vertical)
textView.setContentHuggingPriority(.required, for: .vertical)
textView.isScrollEnabled = false
textView.isEditable = false
textView.textContainer.lineFragmentPadding = 0
textView.textContainerInset = .zero
textView.delegate = self
return textView
}()
lazy var metadataHorizontalStack: UIStackView = {
let stackView = UIStackView()
stackView.axis = .horizontal
stackView.alignment = .leading
stackView.distribution = .equalCentering
stackView.translatesAutoresizingMaskIntoConstraints = false
return stackView
}()
lazy var metadataSpacer: HorizontalSpacerView = {
let spacer = HorizontalSpacerView.spacerWith(space: 10)
return spacer
}()
lazy var activeUsersStack: UIStackView = {
let stackView = UIStackView()
stackView.translatesAutoresizingMaskIntoConstraints = false
stackView.axis = .horizontal
stackView.spacing = 4
return stackView
}()
lazy var activeUsersImageView: UIImageView = {
let imageView = UIImageView(image: UIImage(systemName: "person.crop.circle"))
imageView.translatesAutoresizingMaskIntoConstraints = false
imageView.contentMode = .scaleAspectFit
imageView.setContentCompressionResistancePriority(.required, for: .vertical)
return imageView
}()
lazy var activeUsersLabel: UILabel = {
let label = UILabel()
label.adjustsFontForContentSizeCategory = true
label.font = UIFont.wmf_scaledSystemFont(forTextStyle: .body, weight: .regular, size: 15)
label.numberOfLines = 0
label.setContentCompressionResistancePriority(.required, for: .vertical)
return label
}()
lazy var repliesStack: UIStackView = {
let stackView = UIStackView()
stackView.axis = .horizontal
stackView.spacing = 4
return stackView
}()
lazy var repliesImageView: UIImageView = {
let imageView = UIImageView(image: UIImage(systemName: "bubble.left"))
imageView.translatesAutoresizingMaskIntoConstraints = false
imageView.contentMode = .scaleAspectFit
imageView.setContentCompressionResistancePriority(.required, for: .vertical)
return imageView
}()
lazy var repliesCountLabel: UILabel = {
let label = UILabel()
label.adjustsFontForContentSizeCategory = true
label.font = UIFont.wmf_scaledSystemFont(forTextStyle: .body, weight: .regular, size: 15)
label.numberOfLines = 0
label.setContentCompressionResistancePriority(.required, for: .vertical)
return label
}()
lazy var variableMetadataCenterSpacer: UIView = {
let view = UIView()
view.translatesAutoresizingMaskIntoConstraints = false
let widthConstraint = view.widthAnchor.constraint(equalToConstant: 99999)
widthConstraint.priority = .defaultLow
widthConstraint.isActive = true
return view
}()
override var semanticContentAttribute: UISemanticContentAttribute {
didSet {
updateSemanticContentAttribute(semanticContentAttribute)
}
}
private var displayMode: DisplayMode = .subscribeMetadataReplies
private weak var viewModel: TalkPageCellViewModel?
weak var linkDelegate: TalkPageTextViewLinkHandling?
// MARK: - Lifecycle
override func setup() {
addSubview(stackView)
stackView.addArrangedSubview(disclosureHorizontalStack)
disclosureHorizontalStack.addArrangedSubview(subscribeButton)
disclosureHorizontalStack.addArrangedSubview(disclosureCenterSpacer)
disclosureHorizontalStack.addArrangedSubview(disclosureButton)
stackView.addArrangedSubview(topicTitleTextView)
stackView.addArrangedSubview(metadataHorizontalStack)
stackView.addArrangedSubview(topicCommentTextView)
activeUsersStack.addArrangedSubview(activeUsersImageView)
activeUsersStack.addArrangedSubview(activeUsersLabel)
repliesStack.addArrangedSubview(repliesImageView)
repliesStack.addArrangedSubview(repliesCountLabel)
metadataHorizontalStack.addArrangedSubview(timestampLabel)
metadataHorizontalStack.addArrangedSubview(variableMetadataCenterSpacer)
metadataHorizontalStack.addArrangedSubview(activeUsersStack)
metadataHorizontalStack.addArrangedSubview(metadataSpacer)
metadataHorizontalStack.addArrangedSubview(repliesStack)
NSLayoutConstraint.activate([
stackView.topAnchor.constraint(equalTo: topAnchor),
stackView.leadingAnchor.constraint(equalTo: leadingAnchor),
stackView.trailingAnchor.constraint(equalTo: trailingAnchor),
stackView.bottomAnchor.constraint(equalTo: bottomAnchor)
])
self.accessibilityElements = [topicTitleTextView, subscribeButton, disclosureButton, timestampLabel, activeUsersLabel, repliesCountLabel, topicCommentTextView]
}
// MARK: - Configure
func configure(viewModel: TalkPageCellViewModel) {
self.viewModel = viewModel
let showingOtherContent = viewModel.leadComment == nil && viewModel.otherContentHtml != nil
let shouldHideSubscribe = !viewModel.isUserLoggedIn || viewModel.topicTitleHtml.isEmpty || (showingOtherContent)
switch (shouldHideSubscribe, showingOtherContent) {
case (false, false):
updateForNewDisplayModeIfNeeded(displayMode: .subscribeMetadataReplies)
case (true, false):
updateForNewDisplayModeIfNeeded(displayMode: .metadataReplies)
case (_, true):
updateForNewDisplayModeIfNeeded(displayMode: .none)
}
let isThreadExpanded = viewModel.isThreadExpanded
let collapseThreadlabel = WMFLocalizedString("talk-page-collapse-thread-button", value: "Collapse thread", comment: "Accessibility label for the collapse thread button on talk pages when the thread is expanded")
let expandThreadlabel = WMFLocalizedString("talk-page-expand-thread-button", value: "Expand thread", comment: "Accessibility label for the expand thread button on talk pages when the thread is collapsed")
disclosureButton.setImage(isThreadExpanded ? UIImage(systemName: "chevron.up") : UIImage(systemName: "chevron.down"), for: .normal)
disclosureButton.accessibilityLabel = isThreadExpanded ? collapseThreadlabel : expandThreadlabel
updateSubscribedState(cellViewModel: viewModel)
topicTitleTextView.invalidateIntrinsicContentSize()
topicTitleTextView.textContainer.maximumNumberOfLines = viewModel.isThreadExpanded ? 0 : 2
topicTitleTextView.textContainer.lineBreakMode = viewModel.isThreadExpanded ? .byWordWrapping : .byTruncatingTail
topicCommentTextView.invalidateIntrinsicContentSize()
topicCommentTextView.textContainer.maximumNumberOfLines = viewModel.isThreadExpanded ? 0 : 3
topicCommentTextView.textContainer.lineBreakMode = viewModel.isThreadExpanded ? .byWordWrapping : .byTruncatingTail
if let timestampDisplay = viewModel.timestampDisplay {
timestampLabel.text = timestampDisplay
timestampLabel.accessibilityLabel = viewModel.accessibilityDate()
}
let activeUsersAccessibilityLabel = WMFLocalizedString("talk-page-active-users-accessibilty-label", value: "{{PLURAL:%1$d|%1$d active user|%1$d active users}}", comment: "Accessibility label indicating the number of active users in a thread. The %1$d argument will be replaced with the amount of active users")
let repliesCountAccessibilityLabel = WMFLocalizedString("talk-page-replies-count-accessibilty-label", value: "{{PLURAL:%1$d|%1$d reply|%1$d replies}}", comment: "Accessibility label indicating the number of replies in a thread. The %1$d argument will be replaced with the amount of replies")
if let count = viewModel.activeUsersCount {
activeUsersLabel.text = String(count)
activeUsersLabel.accessibilityLabel = String.localizedStringWithFormat(activeUsersAccessibilityLabel, count)
}
repliesCountLabel.text = String(viewModel.repliesCount)
repliesCountLabel.accessibilityLabel = String.localizedStringWithFormat(repliesCountAccessibilityLabel, viewModel.repliesCount)
}
func updateSubscribedState(cellViewModel: TalkPageCellViewModel) {
let languageCode = cellViewModel.viewModel?.siteURL.wmf_languageCode
let talkPageTopicSubscribe = WMFLocalizedString("talk-page-subscribe-to-topic", languageCode: languageCode, value: "Subscribe", comment: "Text used on button to subscribe to talk page topic. Please prioritize for de, ar and zh wikis.")
let talkPageTopicUnsubscribe = WMFLocalizedString("talk-page-unsubscribe-to-topic", languageCode: languageCode, value: "Unsubscribe", comment: "Text used on button to unsubscribe from talk page topic.")
subscribeButton.setTitle(cellViewModel.isSubscribed ? talkPageTopicUnsubscribe : talkPageTopicSubscribe , for: .normal)
subscribeButton.setImage(cellViewModel.isSubscribed ? UIImage(systemName: "bell.fill") : UIImage(systemName: "bell"), for: .normal)
}
private func updateForNewDisplayModeIfNeeded(displayMode: DisplayMode) {
guard displayMode != self.displayMode else {
return
}
// Reset
stackView.arrangedSubviews.forEach { view in
view.removeFromSuperview()
}
disclosureHorizontalStack.arrangedSubviews.forEach { view in
view.removeFromSuperview()
}
switch displayMode {
case .subscribeMetadataReplies:
disclosureHorizontalStack.addArrangedSubview(subscribeButton)
disclosureHorizontalStack.addArrangedSubview(disclosureCenterSpacer)
disclosureHorizontalStack.addArrangedSubview(disclosureButton)
stackView.addArrangedSubview(disclosureHorizontalStack)
stackView.addArrangedSubview(topicTitleTextView)
stackView.addArrangedSubview(metadataHorizontalStack)
stackView.addArrangedSubview(topicCommentTextView)
self.accessibilityElements = [topicTitleTextView, subscribeButton, disclosureButton, timestampLabel, activeUsersLabel, repliesCountLabel, topicCommentTextView]
case .metadataReplies:
disclosureHorizontalStack.addArrangedSubview(topicTitleTextView)
disclosureHorizontalStack.addArrangedSubview(disclosureCenterSpacer)
disclosureHorizontalStack.addArrangedSubview(disclosureButton)
stackView.addArrangedSubview(disclosureHorizontalStack)
stackView.addArrangedSubview(metadataHorizontalStack)
stackView.addArrangedSubview(topicCommentTextView)
self.accessibilityElements = [topicTitleTextView, disclosureButton, timestampLabel, activeUsersLabel, repliesCountLabel, topicCommentTextView]
case .none:
disclosureHorizontalStack.addArrangedSubview(topicTitleTextView)
disclosureHorizontalStack.addArrangedSubview(disclosureCenterSpacer)
disclosureHorizontalStack.addArrangedSubview(disclosureButton)
stackView.addArrangedSubview(disclosureHorizontalStack)
stackView.addArrangedSubview(topicCommentTextView)
self.accessibilityElements = [topicTitleTextView, disclosureButton, topicCommentTextView]
}
self.displayMode = displayMode
}
private func updateSemanticContentAttribute(_ semanticContentAttribute: UISemanticContentAttribute) {
stackView.semanticContentAttribute = semanticContentAttribute
disclosureHorizontalStack.semanticContentAttribute = semanticContentAttribute
subscribeButton.semanticContentAttribute = semanticContentAttribute
disclosureButton.semanticContentAttribute = semanticContentAttribute
disclosureCenterSpacer.semanticContentAttribute = semanticContentAttribute
topicTitleTextView.semanticContentAttribute = semanticContentAttribute
timestampLabel.semanticContentAttribute = semanticContentAttribute
topicCommentTextView.semanticContentAttribute = semanticContentAttribute
metadataHorizontalStack.semanticContentAttribute = semanticContentAttribute
metadataSpacer.semanticContentAttribute = semanticContentAttribute
activeUsersStack.semanticContentAttribute = semanticContentAttribute
activeUsersImageView.semanticContentAttribute = semanticContentAttribute
activeUsersLabel.semanticContentAttribute = semanticContentAttribute
repliesStack.semanticContentAttribute = semanticContentAttribute
repliesImageView.semanticContentAttribute = semanticContentAttribute
repliesCountLabel.semanticContentAttribute = semanticContentAttribute
variableMetadataCenterSpacer.semanticContentAttribute = semanticContentAttribute
topicTitleTextView.textAlignment = semanticContentAttribute == .forceRightToLeft ? NSTextAlignment.right : NSTextAlignment.left
topicCommentTextView.textAlignment = semanticContentAttribute == .forceRightToLeft ? NSTextAlignment.right : NSTextAlignment.left
timestampLabel.textAlignment = semanticContentAttribute == .forceRightToLeft ? NSTextAlignment.right : NSTextAlignment.left
activeUsersLabel.textAlignment = semanticContentAttribute == .forceRightToLeft ? NSTextAlignment.right : NSTextAlignment.left
repliesCountLabel.textAlignment = semanticContentAttribute == .forceRightToLeft ? NSTextAlignment.right : NSTextAlignment.left
let inset: CGFloat = 2
switch semanticContentAttribute {
case .forceRightToLeft:
subscribeButton.contentEdgeInsets = UIEdgeInsets(top: 0, left: inset, bottom: 0, right: inset)
subscribeButton.imageEdgeInsets = UIEdgeInsets(top: 0, left: inset, bottom: 0, right: -inset)
subscribeButton.titleEdgeInsets = UIEdgeInsets(top: 0, left: -inset, bottom: 0, right: inset)
default:
subscribeButton.contentEdgeInsets = UIEdgeInsets(top: 0, left: inset, bottom: 0, right: inset)
subscribeButton.imageEdgeInsets = UIEdgeInsets(top: 0, left: -inset, bottom: 0, right: inset)
subscribeButton.titleEdgeInsets = UIEdgeInsets(top: 0, left: inset, bottom: 0, right: -inset)
}
}
// MARK: - Find in page
private func applyTextHighlightIfNecessary(theme: Theme) {
let activeHighlightBackgroundColor: UIColor = .yellow50
let backgroundHighlightColor: UIColor
let foregroundHighlightColor: UIColor
switch theme {
case .black, .dark:
backgroundHighlightColor = activeHighlightBackgroundColor.withAlphaComponent(0.6)
foregroundHighlightColor = theme.colors.midBackground
default:
backgroundHighlightColor = activeHighlightBackgroundColor.withAlphaComponent(0.4)
foregroundHighlightColor = theme.colors.primaryText
}
topicTitleTextView.attributedText = NSMutableAttributedString(attributedString: topicTitleTextView.attributedText).highlight(viewModel?.highlightText, backgroundColor: backgroundHighlightColor, foregroundColor: foregroundHighlightColor)
topicCommentTextView.attributedText = NSMutableAttributedString(attributedString: topicCommentTextView.attributedText).highlight(viewModel?.highlightText, backgroundColor: backgroundHighlightColor, foregroundColor: foregroundHighlightColor)
if let cellViewModel = viewModel, let activeResult = cellViewModel.activeHighlightResult {
switch activeResult.location {
case .topicTitle(_, let id):
if id == cellViewModel.id {
topicTitleTextView.attributedText = NSMutableAttributedString(attributedString: topicTitleTextView.attributedText).highlight(viewModel?.highlightText, backgroundColor: activeHighlightBackgroundColor, targetRange: activeResult.range)
}
case .topicLeadComment(_, let id):
if let leadComment = cellViewModel.leadComment,
id == leadComment.id {
topicCommentTextView.attributedText = NSMutableAttributedString(attributedString: topicCommentTextView.attributedText).highlight(viewModel?.highlightText, backgroundColor: activeHighlightBackgroundColor, targetRange: activeResult.range)
}
case .topicOtherContent(topicIndex: _):
topicCommentTextView.attributedText = NSMutableAttributedString(attributedString: topicCommentTextView.attributedText).highlight(viewModel?.highlightText, backgroundColor: activeHighlightBackgroundColor, targetRange: activeResult.range)
default:
break
}
}
}
/// Frame converted to containing collection view
func frameForHighlight(result: TalkPageFindInPageSearchController.SearchResult) -> CGRect? {
guard let range = result.range else {
return nil
}
switch result.location {
case .topicTitle:
guard let initialFrame = topicTitleTextView.frame(of: range) else {
return nil
}
return topicTitleTextView.convert(initialFrame, to: rootCollectionView())
case .topicLeadComment, .topicOtherContent:
guard let initialFrame = topicCommentTextView.frame(of: range) else {
return nil
}
return topicCommentTextView.convert(initialFrame, to: rootCollectionView())
default:
return nil
}
}
/// Containing collection view
private func rootCollectionView() -> UIView? {
var sv = superview
while !(sv is UICollectionView) {
sv = sv?.superview
}
return sv
}
}
extension TalkPageCellTopicView: Themeable {
func apply(theme: Theme) {
subscribeButton.tintColor = theme.colors.link
subscribeButton.setTitleColor(theme.colors.link, for: .normal)
disclosureButton.tintColor = theme.colors.secondaryText
topicTitleTextView.attributedText = viewModel?.topicTitleAttributedString(traitCollection: traitCollection, theme: theme)
topicTitleTextView.backgroundColor = theme.colors.paperBackground
timestampLabel.textColor = theme.colors.secondaryText
if viewModel?.leadComment != nil {
topicCommentTextView.attributedText = viewModel?.leadCommentAttributedString(traitCollection: traitCollection, theme: theme)
} else if viewModel?.otherContentHtml != nil {
topicCommentTextView.attributedText = viewModel?.otherContentAttributedString(traitCollection: traitCollection, theme: theme)
}
topicCommentTextView.backgroundColor = theme.colors.paperBackground
applyTextHighlightIfNecessary(theme: theme)
activeUsersImageView.tintColor = theme.colors.secondaryText
activeUsersLabel.textColor = theme.colors.secondaryText
repliesImageView.tintColor = theme.colors.secondaryText
repliesCountLabel.textColor = theme.colors.secondaryText
}
}
extension TalkPageCellTopicView: UITextViewDelegate {
func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange, interaction: UITextItemInteraction) -> Bool {
linkDelegate?.tappedLink(URL, sourceTextView: textView)
return false
}
}
| mit | 9c89eefad0bbcdba6d51da96ae136bba | 47.565217 | 318 | 0.718634 | 6.555897 | false | false | false | false |
mdiep/Tentacle | Sources/Tentacle/Milestone.swift | 1 | 2017 | //
// Milestone.swift
// Tentacle
//
// Created by Romain Pouclet on 2016-05-23.
// Copyright © 2016 Matt Diephouse. All rights reserved.
//
import Foundation
public struct Milestone: CustomStringConvertible, ResourceType, Identifiable {
public enum State: String, Decodable {
case open
case closed
}
/// The ID of the milestone
public let id: ID<Milestone>
/// The number of the milestone in the repository it belongs to
public let number: Int
/// The state of the Milestone, open or closed
public let state: State
/// The title of the milestone
public let title: String
/// The description of the milestone
public let body: String
/// The user who created the milestone
public let creator: UserInfo
/// The number of the open issues in the milestone
public let openIssueCount: Int
/// The number of closed issues in the milestone
public let closedIssueCount: Int
/// The date the milestone was created
public let createdAt: Date
/// The date the milestone was last updated at
public let updatedAt: Date
/// The date the milestone was closed at, if ever
public let closedAt: Date?
/// The date the milestone is due on
public let dueOn: Date?
/// The URL to view this milestone in a browser
public let url: URL
public var description: String {
return title
}
private enum CodingKeys: String, CodingKey {
case id
case number
case state
case title
case body = "description"
case creator
case openIssueCount = "open_issues"
case closedIssueCount = "closed_issues"
case createdAt = "created_at"
case updatedAt = "updated_at"
case closedAt = "closed_at"
case dueOn = "due_on"
case url = "html_url"
}
}
extension Milestone: Equatable {
public static func ==(lhs: Milestone, rhs: Milestone) -> Bool {
return lhs.id == rhs.id
}
}
| mit | 80c314f7f1e01eef26afa95d9dadfafa | 23.888889 | 78 | 0.642857 | 4.55079 | false | false | false | false |
ps2/rileylink_ios | OmniKitTests/BasalScheduleTests.swift | 1 | 24767 | //
// BasalScheduleTests.swift
// OmniKitTests
//
// Created by Pete Schwamb on 4/4/18.
// Copyright © 2018 Pete Schwamb. All rights reserved.
//
import XCTest
@testable import OmniKit
class BasalScheduleTests: XCTestCase {
func testBasalTableEntry() {
let entry = BasalTableEntry(segments: 2, pulses: 300, alternateSegmentPulse: false)
// $01 $2c $01 $2c = 1 + 44 + 1 + 44 = 90 = $5a
XCTAssertEqual(0x5a, entry.checksum())
let entry2 = BasalTableEntry(segments: 2, pulses: 260, alternateSegmentPulse: true)
// $01 $04 $01 $04 = 1 + 4 + 1 + 5 = 1 = $0b
XCTAssertEqual(0x0b, entry2.checksum())
}
func testSetBasalScheduleCommand() {
do {
// Decode 1a 12 77a05551 00 0062 2b 1708 0000 f800 f800 f800
let cmd = try SetInsulinScheduleCommand(encodedData: Data(hexadecimalString: "1a1277a055510000622b17080000f800f800f800")!)
XCTAssertEqual(0x77a05551, cmd.nonce)
if case SetInsulinScheduleCommand.DeliverySchedule.basalSchedule(let currentSegment, let secondsRemaining, let pulsesRemaining, let table) = cmd.deliverySchedule {
XCTAssertEqual(0x2b, currentSegment)
XCTAssertEqual(737, secondsRemaining)
XCTAssertEqual(0, pulsesRemaining)
XCTAssertEqual(3, table.entries.count)
} else {
XCTFail("Expected ScheduleEntry.basalSchedule type")
}
} catch (let error) {
XCTFail("message decoding threw error: \(error)")
}
// Encode
let scheduleEntry = BasalTableEntry(segments: 16, pulses: 0, alternateSegmentPulse: true)
let table = BasalDeliveryTable(entries: [scheduleEntry, scheduleEntry, scheduleEntry])
let deliverySchedule = SetInsulinScheduleCommand.DeliverySchedule.basalSchedule(currentSegment: 0x2b, secondsRemaining: 737, pulsesRemaining: 0, table: table)
let cmd = SetInsulinScheduleCommand(nonce: 0x77a05551, deliverySchedule: deliverySchedule)
XCTAssertEqual("1a1277a055510000622b17080000f800f800f800", cmd.data.hexadecimalString)
}
func testBasalScheduleCommandFromSchedule() {
// Encode from schedule
let entry = BasalScheduleEntry(rate: 0.05, startTime: 0)
let schedule = BasalSchedule(entries: [entry])
let cmd = SetInsulinScheduleCommand(nonce: 0x01020304, basalSchedule: schedule, scheduleOffset: .hours(8.25))
XCTAssertEqual(0x01020304, cmd.nonce)
if case SetInsulinScheduleCommand.DeliverySchedule.basalSchedule(let currentSegment, let secondsRemaining, let pulsesRemaining, let table) = cmd.deliverySchedule {
XCTAssertEqual(16, currentSegment)
XCTAssertEqual(UInt16(TimeInterval(minutes: 15)), secondsRemaining)
XCTAssertEqual(0, pulsesRemaining)
XCTAssertEqual(3, table.entries.count)
let tableEntry = table.entries[0]
XCTAssertEqual(true, tableEntry.alternateSegmentPulse)
XCTAssertEqual(0, tableEntry.pulses)
XCTAssertEqual(16, tableEntry.segments)
} else {
XCTFail("Expected ScheduleEntry.basalSchedule type")
}
// 1a LL NNNNNNNN 00 CCCC HH SSSS PPPP napp napp napp napp
// 1a 12 01020304 00 0065 10 1c20 0001 f800 f800 f800
XCTAssertEqual("1a1201020304000064101c200000f800f800f800", cmd.data.hexadecimalString)
}
func testBasalScheduleExtraCommand() {
do {
// Decode 130e40 00 1aea 001e8480 3840005b8d80
let cmd = try BasalScheduleExtraCommand(encodedData: Data(hexadecimalString: "130e40001aea001e84803840005b8d80")!)
XCTAssertEqual(false, cmd.acknowledgementBeep)
XCTAssertEqual(true, cmd.completionBeep)
XCTAssertEqual(0, cmd.programReminderInterval)
XCTAssertEqual(0, cmd.currentEntryIndex)
XCTAssertEqual(689, cmd.remainingPulses)
XCTAssertEqual(TimeInterval(seconds: 20), cmd.delayUntilNextTenthOfPulse)
XCTAssertEqual(1, cmd.rateEntries.count)
let entry = cmd.rateEntries[0]
XCTAssertEqual(TimeInterval(seconds: 60), entry.delayBetweenPulses)
XCTAssertEqual(1440, entry.totalPulses)
XCTAssertEqual(3.0, entry.rate)
XCTAssertEqual(TimeInterval(hours: 24), entry.duration)
} catch (let error) {
XCTFail("message decoding threw error: \(error)")
}
// Encode
let rateEntries = RateEntry.makeEntries(rate: 3.0, duration: TimeInterval(hours: 24))
let cmd = BasalScheduleExtraCommand(currentEntryIndex: 0, remainingPulses: 689, delayUntilNextTenthOfPulse: TimeInterval(seconds: 20), rateEntries: rateEntries, acknowledgementBeep: false, completionBeep: true, programReminderInterval: 0)
XCTAssertEqual("130e40001aea01312d003840005b8d80", cmd.data.hexadecimalString)
}
func testBasalScheduleExtraCommandFromSchedule() {
// Encode from schedule
let entry = BasalScheduleEntry(rate: 0.05, startTime: 0)
let schedule = BasalSchedule(entries: [entry])
let cmd = BasalScheduleExtraCommand(schedule: schedule, scheduleOffset: .hours(8.25), acknowledgementBeep: false, completionBeep: true, programReminderInterval: 60)
XCTAssertEqual(false, cmd.acknowledgementBeep)
XCTAssertEqual(true, cmd.completionBeep)
XCTAssertEqual(60, cmd.programReminderInterval)
XCTAssertEqual(0, cmd.currentEntryIndex)
XCTAssertEqual(15.8, cmd.remainingPulses, accuracy: 0.01)
XCTAssertEqual(TimeInterval(minutes: 3), cmd.delayUntilNextTenthOfPulse)
XCTAssertEqual(1, cmd.rateEntries.count)
let rateEntry = cmd.rateEntries[0]
XCTAssertEqual(TimeInterval(minutes: 60), rateEntry.delayBetweenPulses)
XCTAssertEqual(24, rateEntry.totalPulses, accuracy: 0.001)
XCTAssertEqual(0.05, rateEntry.rate)
XCTAssertEqual(TimeInterval(hours: 24), rateEntry.duration, accuracy: 0.001)
}
func testBasalExtraEncoding() {
// Encode
let schedule = BasalSchedule(entries: [
BasalScheduleEntry(rate: 1.05, startTime: 0),
BasalScheduleEntry(rate: 0.9, startTime: .hours(10.5)),
BasalScheduleEntry(rate: 1, startTime: .hours(18.5))
])
let hh = 0x2e
let ssss = 0x1be8
let offset = TimeInterval(minutes: Double((hh + 1) * 30)) - TimeInterval(seconds: Double(ssss / 8))
// 1a LL NNNNNNNN 00 CCCC HH SSSS PPPP napp napp napp napp
// 1a 14 0d6612db 00 0310 2e 1be8 0005 f80a 480a f009 a00a
let cmd1 = SetInsulinScheduleCommand(nonce: 0x0d6612db, basalSchedule: schedule, scheduleOffset: offset)
XCTAssertEqual("1a140d6612db0003102e1be80005f80a480af009a00a", cmd1.data.hexadecimalString)
// 13 LL RR MM NNNN XXXXXXXX YYYY ZZZZZZZZ YYYY ZZZZZZZZ YYYY ZZZZZZZZ
// 13 1a 40 02 0096 00a7d8c0 089d 01059449 05a0 01312d00 044c 0112a880 * PDM
// 13 1a 40 02 0095 00a7d8c0 089d 01059449 05a0 01312d00 044c 0112a880
let cmd2 = BasalScheduleExtraCommand(schedule: schedule, scheduleOffset: offset, acknowledgementBeep: false, completionBeep: true, programReminderInterval: 0)
XCTAssertEqual("131a4002009600a7d8c0089d0105944905a001312d00044c0112a880", cmd2.data.hexadecimalString) // PDM
}
func checkBasalScheduleExtraCommandDataWithLessPrecision(_ expected: Data, _ data: Data, line: UInt = #line) {
// The XXXXXXXX field is in thousands of a millisecond. Since we use TimeIntervals (floating point) for
// recreating the offset, we can have small errors in reproducing the the encoded output, which we really
// don't care about.
func extractXXXXXXXX(_ data: Data) -> TimeInterval {
return TimeInterval(Double(data[6...].toBigEndian(UInt32.self)) / 1000000.0)
}
let xxxxxxxx1 = extractXXXXXXXX(expected)
let xxxxxxxx2 = extractXXXXXXXX(data)
XCTAssertEqual(xxxxxxxx1, xxxxxxxx2, accuracy: 0.01, line: line)
func blurXXXXXXXX(_ inStr: String) -> String {
let start = inStr.index(inStr.startIndex, offsetBy:12)
let end = inStr.index(start, offsetBy:8)
return inStr.replacingCharacters(in: start..<end, with: "........")
}
print(blurXXXXXXXX(data.hexadecimalString))
XCTAssertEqual(blurXXXXXXXX(expected.hexadecimalString), blurXXXXXXXX(data.hexadecimalString), line: line)
}
func testBasalExtraEncoding1() {
// Encode
let schedule = BasalSchedule(entries: [BasalScheduleEntry(rate: 1.05, startTime: 0)])
let hh = 0x20 // 16:00, rate = 1.05
let ssss = 0x33c0 // 1656s left, 144s into segment
let offset = TimeInterval(minutes: Double((hh + 1) * 30)) - TimeInterval(seconds: Double(ssss / 8))
// 1a LL NNNNNNNN 00 CCCC HH SSSS PPPP napp napp napp
// 1a 12 2a845e17 00 0314 20 33c0 0009 f80a f80a f80a
// 1a 12 2a845e17 00 0315 20 33c0 000a f80a f80a f80a
let cmd1 = SetInsulinScheduleCommand(nonce: 0x2a845e17, basalSchedule: schedule, scheduleOffset: offset)
XCTAssertEqual("1a122a845e170003142033c00009f80af80af80a", cmd1.data.hexadecimalString)
// 13 LL RR MM NNNN XXXXXXXX YYYY ZZZZZZZZ
// 13 0e 40 00 0688 009cf291 13b0 01059449
let cmd2 = BasalScheduleExtraCommand(schedule: schedule, scheduleOffset: offset, acknowledgementBeep: false, completionBeep: true, programReminderInterval: 0)
checkBasalScheduleExtraCommandDataWithLessPrecision(Data(hexadecimalString: "130e40000688009cf29113b001059449")!, cmd2.data)
}
func testBasalExtraEncoding2() {
// Encode
let schedule = BasalSchedule(entries: [BasalScheduleEntry(rate: 1.05, startTime: 0)])
// 17:47:27 1a 12 0a229e93 00 02d6 23 17a0 0004 f80a f80a f80a 13 0e 40 00 0519 001a2865 13b0 01059449 0220
let hh = 0x23 // 17:30, rate = 1.05
let ssss = 0x17a0 // 756s left, 1044s into segment
let offset = TimeInterval(minutes: Double((hh + 1) * 30)) - TimeInterval(seconds: Double(ssss / 8))
// 1a LL NNNNNNNN 00 CCCC HH SSSS PPPP napp napp napp
// 1a 12 0a229e93 00 02d6 23 17a0 0004 f80a f80a f80a
let cmd1 = SetInsulinScheduleCommand(nonce: 0x0a229e93, basalSchedule: schedule, scheduleOffset: offset)
XCTAssertEqual("1a120a229e930002d62317a00004f80af80af80a", cmd1.data.hexadecimalString)
// 13 LL RR MM NNNN XXXXXXXX YYYY ZZZZZZZZ
// 13 0e 40 00 0519 001a2865 13b0 01059449
// 13 0e 40 00 0519 001a286e 13b0 01059449
let cmd2 = BasalScheduleExtraCommand(schedule: schedule, scheduleOffset: offset, acknowledgementBeep: false, completionBeep: true, programReminderInterval: 0)
checkBasalScheduleExtraCommandDataWithLessPrecision(Data(hexadecimalString: "130e40000519001a286513b001059449")!, cmd2.data)
}
func testSuspendBasalCommand() {
do {
// Decode 1f 05 6fede14a 01
let cmd = try CancelDeliveryCommand(encodedData: Data(hexadecimalString: "1f056fede14a01")!)
XCTAssertEqual(0x6fede14a, cmd.nonce)
XCTAssertEqual(.noBeep, cmd.beepType)
XCTAssertEqual(.basal, cmd.deliveryType)
} catch (let error) {
XCTFail("message decoding threw error: \(error)")
}
// Encode
let cmd = CancelDeliveryCommand(nonce: 0x6fede14a, deliveryType: .basal, beepType: .noBeep)
XCTAssertEqual("1f056fede14a01", cmd.data.hexadecimalString)
}
func testSegmentMerging() {
let entries = [
BasalScheduleEntry(rate: 0.80, startTime: 0),
BasalScheduleEntry(rate: 0.90, startTime: .hours(3)),
BasalScheduleEntry(rate: 0.85, startTime: .hours(5)),
BasalScheduleEntry(rate: 0.85, startTime: .hours(7.5)),
BasalScheduleEntry(rate: 0.85, startTime: .hours(12.5)),
BasalScheduleEntry(rate: 0.70, startTime: .hours(15)),
BasalScheduleEntry(rate: 0.90, startTime: .hours(18)),
BasalScheduleEntry(rate: 1.10, startTime: .hours(20)),
]
let schedule = BasalSchedule(entries: entries)
// 1a LL NNNNNNNN 00 CCCC HH SSSS PPPP napp napp napp napp napp napp napp
// PDM: 1a 1a 851072aa 00 0242 2a 1e50 0006 5008 3009 f808 3808 5007 3009 700b
let hh = 0x2a
let ssss = 0x1e50
let offset = TimeInterval(minutes: Double((hh + 1) * 30)) - TimeInterval(seconds: Double(ssss / 8))
let cmd1 = SetInsulinScheduleCommand(nonce: 0x851072aa, basalSchedule: schedule, scheduleOffset: offset)
XCTAssertEqual("1a1a851072aa0002422a1e50000650083009f808380850073009700b", cmd1.data.hexadecimalString)
// 13 LL RR MM NNNN XXXXXXXX YYYY ZZZZZZZZ YYYY ZZZZZZZZ YYYY ZZZZZZZZ YYYY ZZZZZZZZ YYYY ZZZZZZZZ YYYY ZZZZZZZZ
// PDM: 13 2c 40 05 0262 00455b9c 01e0 015752a0 0168 01312d00 06a4 01432096 01a4 01885e6d 0168 01312d00 0370 00f9b074
let cmd2 = BasalScheduleExtraCommand(schedule: schedule, scheduleOffset: offset, acknowledgementBeep: false, completionBeep: true, programReminderInterval: 0)
checkBasalScheduleExtraCommandDataWithLessPrecision(Data(hexadecimalString: "132c4005026200455b9c01e0015752a0016801312d0006a40143209601a401885e6d016801312d00037000f9b074")!, cmd2.data)
}
func testRounding() {
let entries = [
BasalScheduleEntry(rate: 2.75, startTime: 0),
BasalScheduleEntry(rate: 20.25, startTime: .hours(1)),
BasalScheduleEntry(rate: 5.00, startTime: .hours(1.5)),
BasalScheduleEntry(rate: 10.10, startTime: .hours(2)),
BasalScheduleEntry(rate: 0.05, startTime: .hours(2.5)),
BasalScheduleEntry(rate: 3.50, startTime: .hours(15.5)),
]
let schedule = BasalSchedule(entries: entries)
// 1a LL NNNNNNNN 00 CCCC HH SSSS PPPP napp napp napp napp napp napp napp napp napp
// PDM: 1a 1e c2a32da8 00 053a 28 1af0 0010 181b 00ca 0032 0065 0001 f800 8800 f023 0023
let hh = 0x28
let ssss = 0x1af0
let offset = TimeInterval(minutes: Double((hh + 1) * 30)) - TimeInterval(seconds: Double(ssss / 8))
let cmd1 = SetInsulinScheduleCommand(nonce: 0xc2a32da8, basalSchedule: schedule, scheduleOffset: offset)
XCTAssertEqual("1a1ec2a32da800053a281af00010181b00ca003200650001f8008800f0230023", cmd1.data.hexadecimalString)
}
func testRounding2() {
let entries = [
BasalScheduleEntry(rate: 0.60, startTime: 0),
BasalScheduleEntry(rate: 0.65, startTime: .hours(7.5)),
BasalScheduleEntry(rate: 0.50, startTime: .hours(8.5)),
BasalScheduleEntry(rate: 0.65, startTime: .hours(9.5)),
BasalScheduleEntry(rate: 0.15, startTime: .hours(15.5)),
BasalScheduleEntry(rate: 0.80, startTime: .hours(16.3)),
]
let schedule = BasalSchedule(entries: entries)
// 1a LL NNNNNNNN 00 CCCC HH SSSS PPPP napp napp napp napp napp napp
// PDM: 1a 18 851072aa 00 021b 2c 2190 0004 f006 0007 1005 b806 1801 e008
let hh = 0x2c
let ssss = 0x2190
let offset = TimeInterval(minutes: Double((hh + 1) * 30)) - TimeInterval(seconds: Double(ssss / 8))
let cmd1 = SetInsulinScheduleCommand(nonce: 0x851072aa, basalSchedule: schedule, scheduleOffset: offset)
XCTAssertEqual("1a18851072aa00021b2c21900004f00600071005b8061801e008", cmd1.data.hexadecimalString)
}
func testThirteenEntries() {
let entries = [
BasalScheduleEntry(rate: 1.30, startTime: 0),
BasalScheduleEntry(rate: 0.05, startTime: .hours(0.5)),
BasalScheduleEntry(rate: 1.70, startTime: .hours(2.0)),
BasalScheduleEntry(rate: 0.85, startTime: .hours(2.5)),
BasalScheduleEntry(rate: 1.00, startTime: .hours(3.0)),
BasalScheduleEntry(rate: 0.65, startTime: .hours(7.5)),
BasalScheduleEntry(rate: 0.50, startTime: .hours(8.5)),
BasalScheduleEntry(rate: 0.65, startTime: .hours(9.5)),
BasalScheduleEntry(rate: 0.60, startTime: .hours(10.5)),
BasalScheduleEntry(rate: 0.65, startTime: .hours(11.5)),
BasalScheduleEntry(rate: 1.65, startTime: .hours(14.0)),
BasalScheduleEntry(rate: 0.15, startTime: .hours(15.5)),
BasalScheduleEntry(rate: 0.85, startTime: .hours(16.5)),
]
let schedule = BasalSchedule(entries: entries)
// 1a LL NNNNNNNN 00 CCCC HH SSSS PPPP napp napp napp napp napp napp napp napp napp napp napp napp napp napp napp
// PDM: 1a 2a 851072aa 00 01dd 27 1518 0003 000d 2800 0011 1809 700a 1806 1005 2806 1006 0007 2806 0011 1810 1801 e808
let hh = 0x27
let ssss = 0x1518
let offset = TimeInterval(minutes: Double((hh + 1) * 30)) - TimeInterval(seconds: Double(ssss / 8))
let cmd = SetInsulinScheduleCommand(nonce: 0x851072aa, basalSchedule: schedule, scheduleOffset: offset)
XCTAssertEqual("1a2a851072aa0001dd2715180003000d280000111809700a180610052806100600072806001118101801e808", cmd.data.hexadecimalString)
// 13 LL RR MM NNNN XXXXXXXX YYYY ZZZZZZZZ YYYY ZZZZZZZZ YYYY ZZZZZZZZ YYYY ZZZZZZZZ YYYY ZZZZZZZZ YYYY ZZZZZZZZ YYYY ZZZZZZZZ YYYY ZZZZZZZZ YYYY ZZZZZZZZ YYYY ZZZZZZZZ YYYY ZZZZZZZZ YYYY ZZZZZZZZ YYYY ZZZZZZZZ
// PDM: 13 56 40 0c 02c8 011abc64 0082 00d34689 000f 15752a00 00aa 00a1904b 0055 01432096 0384 0112a880 0082 01a68d13 0064 02255100 0082 01a68d13 0078 01c9c380 0145 01a68d13 01ef 00a675a2 001e 07270e00 04fb 01432096
let cmd2 = BasalScheduleExtraCommand(schedule: schedule, scheduleOffset: offset, acknowledgementBeep: false, completionBeep: true, programReminderInterval: 0)
checkBasalScheduleExtraCommandDataWithLessPrecision(Data(hexadecimalString: "1356400c02c8011abc64008200d34689000f15752a0000aa00a1904b00550143209603840112a880008201a68d13006402255100008201a68d13007801c9c380014501a68d1301ef00a675a2001e07270e0004fb01432096")!, cmd2.data)
}
func testJoe12Entries() {
let entries = [
BasalScheduleEntry(rate: 1.30, startTime: 0),
BasalScheduleEntry(rate: 0.05, startTime: .hours(0.5)),
BasalScheduleEntry(rate: 1.70, startTime: .hours(2.0)),
BasalScheduleEntry(rate: 0.85, startTime: .hours(2.5)),
BasalScheduleEntry(rate: 1.00, startTime: .hours(3.0)),
BasalScheduleEntry(rate: 0.65, startTime: .hours(7.5)),
BasalScheduleEntry(rate: 0.50, startTime: .hours(8.5)),
BasalScheduleEntry(rate: 0.65, startTime: .hours(9.5)),
BasalScheduleEntry(rate: 0.60, startTime: .hours(10.5)),
BasalScheduleEntry(rate: 0.65, startTime: .hours(11.5)),
BasalScheduleEntry(rate: 1.65, startTime: .hours(14.0)),
BasalScheduleEntry(rate: 0.85, startTime: .hours(16)),
]
let schedule = BasalSchedule(entries: entries)
// 1a LL NNNNNNNN 00 CCCC HH SSSS PPPP napp napp napp napp napp napp napp napp napp napp napp napp napp napp napp
// PDM: 1a 2a f36a23a3 00 0291 03 0ae8 0000 000d 2800 0011 1809 700a 1806 1005 2806 1006 0007 2806 0011 2810 0009 e808
let hh = 0x03
let ssss = 0x0ae8
let offset = TimeInterval(minutes: Double((hh + 1) * 30)) - TimeInterval(seconds: Double(ssss / 8))
let cmd1 = SetInsulinScheduleCommand(nonce: 0xf36a23a3, basalSchedule: schedule, scheduleOffset: offset)
XCTAssertEqual("1a2af36a23a3000291030ae80000000d280000111809700a180610052806100600072806001128100009e808", cmd1.data.hexadecimalString)
}
func testFunkyRates() {
let entries = [
BasalScheduleEntry(rate: 1.325, startTime: 0),
BasalScheduleEntry(rate: 0.05, startTime: .hours(0.5)),
BasalScheduleEntry(rate: 1.699, startTime: .hours(2.0)),
BasalScheduleEntry(rate: 0.850001, startTime: .hours(2.5)),
BasalScheduleEntry(rate: 1.02499999, startTime: .hours(3.0)),
BasalScheduleEntry(rate: 0.650001, startTime: .hours(7.5)),
BasalScheduleEntry(rate: 0.50, startTime: .hours(8.5)),
BasalScheduleEntry(rate: 0.675, startTime: .hours(9.5)),
BasalScheduleEntry(rate: 0.59999, startTime: .hours(10.5)),
BasalScheduleEntry(rate: 0.666, startTime: .hours(11.5)),
BasalScheduleEntry(rate: 1.675, startTime: .hours(14.0)),
BasalScheduleEntry(rate: 0.849, startTime: .hours(16)),
]
let schedule = BasalSchedule(entries: entries)
// 1a LL NNNNNNNN 00 CCCC HH SSSS PPPP napp napp napp napp napp napp napp napp napp napp napp napp napp napp napp
// PDM: 1a 2a f36a23a3 00 0291 03 0ae8 0000 000d 2800 0011 1809 700a 1806 1005 2806 1006 0007 2806 0011 2810 0009 e808
let hh = 0x03
let ssss = 0x0ae8
let offset = TimeInterval(minutes: Double((hh + 1) * 30)) - TimeInterval(seconds: Double(ssss / 8))
let cmd1 = SetInsulinScheduleCommand(nonce: 0xf36a23a3, basalSchedule: schedule, scheduleOffset: offset)
XCTAssertEqual("1a2af36a23a3000291030ae80000000d280000111809700a180610052806100600072806001128100009e808", cmd1.data.hexadecimalString)
}
func test723ScheduleImport() {
let entries = [
BasalScheduleEntry(rate: 0.0, startTime: 0),
BasalScheduleEntry(rate: 0.03, startTime: .hours(0.5)),
BasalScheduleEntry(rate: 0.075, startTime: .hours(1.5)),
BasalScheduleEntry(rate: 0.0, startTime: .hours(3.5)),
BasalScheduleEntry(rate: 0.25, startTime: .hours(4.0)),
BasalScheduleEntry(rate: 0.725, startTime: .hours(6.0)),
BasalScheduleEntry(rate: 0.78, startTime: .hours(7.5)),
]
let schedule = BasalSchedule(entries: entries)
// 1a LL NNNNNNNN 00 CCCC HH SSSS PPPP napp napp napp napp napp napp
// PDM: 1a 18 ee29db98 00 0224 2d 0cd0 0001 7800 3802 3007 0008 f807 e807
let hh = 0x2d
let ssss = 0x0cd0
let offset = TimeInterval(minutes: Double((hh + 1) * 30)) - TimeInterval(seconds: Double(ssss / 8))
let cmd1 = SetInsulinScheduleCommand(nonce: 0xee29db98, basalSchedule: schedule, scheduleOffset: offset)
XCTAssertEqual("1a18ee29db980002242d0cd000017800380230070008f807e807", cmd1.data.hexadecimalString)
// 13 LL RR MM NNNN XXXXXXXX YYYY ZZZZZZZZ YYYY ZZZZZZZZ YYYY ZZZZZZZZ YYYY ZZZZZZZZ
// PDM: 13 20 00 03 00a8 001e8480 0028 15752a00 0064 044aa200 00d2 01885e6d 09ab 016e3600
let cmd2 = BasalScheduleExtraCommand(schedule: schedule, scheduleOffset: offset, acknowledgementBeep: false, completionBeep: false, programReminderInterval: 0)
checkBasalScheduleExtraCommandDataWithLessPrecision(Data(hexadecimalString: "1320000300a8001e8480002815752a000064044aa20000d201885e6d09ab016e3600")!, cmd2.data)
}
func testBasalScheduleExtraCommandRoundsToNearestSecond() {
let schedule = BasalSchedule(entries: [BasalScheduleEntry(rate: 1.0, startTime: 0)])
let hh = 0x2b
let ssss = 0x1b38
// Add 0.456 to the clock to have a non-integer # of seconds, and verify that it still produces valid results
let offset = TimeInterval(minutes: Double((hh + 1) * 30)) - TimeInterval(seconds: Double(ssss / 8)) + .seconds(0.456)
// 13 LL RR MM NNNN XXXXXXXX YYYY ZZZZZZZZ
// 13 0e 40 00 01c1 006acfc0 12c0 0112a880
let cmd = BasalScheduleExtraCommand(schedule: schedule, scheduleOffset: offset, acknowledgementBeep: false, completionBeep: true, programReminderInterval: 0)
checkBasalScheduleExtraCommandDataWithLessPrecision(Data(hexadecimalString: "130e400001c1006acfc012c00112a880")!, cmd.data)
}
}
| mit | a534e502f4c6f0e01ae3c57477fc78a6 | 52.375 | 276 | 0.661229 | 4.11327 | false | false | false | false |
gaurav1981/eidolon | Kiosk/Auction Listings/TableCollectionViewCell.swift | 1 | 3687 | import UIKit
class TableCollectionViewCell: ListingsCollectionViewCell {
private lazy var infoView: UIView = {
let view = UIView()
view.addSubview(self.lotNumberLabel)
view.addSubview(self.artistNameLabel)
view.addSubview(self.artworkTitleLabel)
self.lotNumberLabel.alignTop("0", bottom: nil, toView: view)
self.lotNumberLabel.alignLeading("0", trailing: "0", toView: view)
self.artistNameLabel.alignAttribute(.Top, toAttribute: .Bottom, ofView: self.lotNumberLabel, predicate: "5")
self.artistNameLabel.alignLeading("0", trailing: "0", toView: view)
self.artworkTitleLabel.alignLeading("0", trailing: "0", toView: view)
self.artworkTitleLabel.alignAttribute(.Top, toAttribute: .Bottom, ofView: self.artistNameLabel, predicate: "0")
self.artworkTitleLabel.alignTop(nil, bottom: "0", toView: view)
return view
}()
private lazy var cellSubviews: [UIView] = [self.artworkImageView, self.infoView, self.currentBidLabel, self.numberOfBidsLabel, self.bidButton]
override func setup() {
super.setup()
contentView.constrainWidth("\(TableCollectionViewCell.Width)")
// Configure subviews
numberOfBidsLabel.textAlignment = .Center
artworkImageView.contentMode = .ScaleAspectFill
artworkImageView.clipsToBounds = true
// Add subviews
cellSubviews.forEach{ self.contentView.addSubview($0) }
// Constrain subviews
artworkImageView.alignAttribute(.Width, toAttribute: .Height, ofView: artworkImageView, predicate: nil)
artworkImageView.alignTop("14", leading: "0", bottom: "-14", trailing: nil, toView: contentView)
artworkImageView.constrainHeight("56")
infoView.alignAttribute(.Left, toAttribute: .Right, ofView: artworkImageView, predicate: "28")
infoView.alignCenterYWithView(artworkImageView, predicate: "0")
infoView.constrainWidth("300")
currentBidLabel.alignAttribute(.Left, toAttribute: .Right, ofView: infoView, predicate: "33")
currentBidLabel.alignCenterYWithView(artworkImageView, predicate: "0")
currentBidLabel.constrainWidth("180")
numberOfBidsLabel.alignAttribute(.Left, toAttribute: .Right, ofView: currentBidLabel, predicate: "33")
numberOfBidsLabel.alignCenterYWithView(artworkImageView, predicate: "0")
numberOfBidsLabel.alignAttribute(.Right, toAttribute: .Left, ofView: bidButton, predicate: "-33")
bidButton.alignBottom(nil, trailing: "0", toView: contentView)
bidButton.alignCenterYWithView(artworkImageView, predicate: "0")
bidButton.constrainWidth("127")
// Replaces the signal defined in the superclass, normally used to emit taps to a "More Info" label, which we don't have.
let recognizer = UITapGestureRecognizer()
contentView.addGestureRecognizer(recognizer)
self.moreInfoSignal = recognizer.rac_gestureSignal()
}
override func layoutSubviews() {
super.layoutSubviews()
contentView.drawBottomSolidBorderWithColor(UIColor.artsyMediumGrey())
}
}
extension TableCollectionViewCell {
private struct SharedDimensions {
var width: CGFloat = 0
var height: CGFloat = 84
static var instance = SharedDimensions()
}
class var Width: CGFloat {
get {
return SharedDimensions.instance.width
}
set (newWidth) {
SharedDimensions.instance.width = newWidth
}
}
class var Height: CGFloat {
return SharedDimensions.instance.height
}
}
| mit | d68d56155194416af35e203e47830187 | 40.897727 | 146 | 0.681855 | 5.171108 | false | false | false | false |
gerardogrisolini/Webretail | Sources/Webretail/Repositories/PublicationRepository.swift | 1 | 1767 | //
// PublicationRepository.swift
// Webretail
//
// Created by Gerardo Grisolini on 17/02/17.
//
//
import StORM
struct PublicationRepository : PublicationProtocol {
func get() throws -> [Publication] {
let items = Publication()
try items.query(
whereclause: "publicationStartAt <= $1 AND publicationFinishAt >= $1",
params: [Int.now()])
return items.rows()
}
func get(id: Int) throws -> Publication? {
let item = Publication()
try item.query(id: id)
return item.publicationId == 0 ? nil : item
}
func getByProduct(productId: Int) throws -> Publication? {
let item = Publication()
try item.query(
whereclause: "productId = $1", params: [productId],
cursor: StORMCursor(limit: 1, offset: 0)
)
if (item.publicationId == 0) {
throw StORMError.noRecordFound
}
return item.publicationId == 0 ? nil : item
}
func add(item: Publication) throws {
try item.save {
id in item.publicationId = id as! Int
}
}
func update(id: Int, item: Publication) throws {
guard let current = try get(id: id) else {
throw StORMError.noRecordFound
}
current.publicationFeatured = item.publicationFeatured
current.publicationNew = item.publicationNew
current.publicationStartAt = item.publicationStartAt
current.publicationFinishAt = item.publicationFinishAt
current.publicationUpdated = Int.now()
try current.save()
}
func delete(id: Int) throws {
let item = Publication()
item.publicationId = id
try item.delete()
}
}
| apache-2.0 | 61754d5a5b1bbc79c80d7e449c8d3aff | 24.985294 | 82 | 0.585739 | 4.462121 | false | false | false | false |
yonadev/yona-app-ios | Yona/Yona/CustomSubclasses/VSTextField.swift | 1 | 10321 | // VSTextField.swift
// Created by Vojta Stavik
// Copyright (c) 2016 www.vojtastavik.com All rights reserved.
// Modified by Ron Lisle June 2017 to support UUID hex entry
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import UIKit
public enum TextFieldFormatting {
case uuid
case socialSecurityNumber
case phoneNumber
case custom
case noFormatting
}
public class VSTextField: UITextField {
/**
Set a formatting pattern for a number and define a replacement string. For example: If formattingPattern would be "##-##-AB-##" and
replacement string would be "#" and user input would be "123456", final string would look like "12-34-AB-56"
*/
public func setFormatting(_ formattingPattern: String, replacementChar: Character) {
self.formattingPattern = formattingPattern
self.replacementChar = replacementChar
self.formatting = .custom
}
/**
A character which will be replaced in formattingPattern by a number
*/
public var replacementChar: Character = "*"
/**
A character which will be replaced in formattingPattern by a number
*/
public var secureTextReplacementChar: Character = "\u{25cf}"
/**
True if input number is hexadecimal eg. UUID
*/
public var isHexadecimal: Bool {
return formatting == .uuid
}
/**
Max length of input string. You don't have to set this if you set formattingPattern.
If 0 -> no limit.
*/
public var maxLength = 0
/**
Type of predefined text formatting. (You don't have to set this. It's more a future feature)
*/
public var formatting : TextFieldFormatting = .noFormatting {
didSet {
switch formatting {
case .socialSecurityNumber:
self.formattingPattern = "***-**-****"
self.replacementChar = "*"
case .phoneNumber:
self.formattingPattern = "***-***-****"
self.replacementChar = "*"
case .uuid:
self.formattingPattern = "********-****-****-****-************"
self.replacementChar = "*"
default:
self.maxLength = 0
}
}
}
/**
String with formatting pattern for the text field.
*/
public var formattingPattern: String = "" {
didSet {
self.maxLength = formattingPattern.count
}
}
/**
Provides secure text entry but KEEPS formatting. All digits are replaced with the bullet character \u{25cf} .
*/
public var formatedSecureTextEntry: Bool {
set {
_formatedSecureTextEntry = newValue
super.isSecureTextEntry = false
}
get {
return _formatedSecureTextEntry
}
}
override public var text: String! {
set {
super.text = newValue
textDidChange() // format string properly even when it's set programatically
}
get {
if case .noFormatting = formatting {
return super.text
} else {
// Because the UIControl target action is called before NSNotificaion (from which we fire our custom formatting), we need to
// force update finalStringWithoutFormatting to get the latest text. Otherwise, the last character would be missing.
textDidChange()
return finalStringWithoutFormatting
}
}
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
registerForNotifications()
}
override init(frame: CGRect) {
super.init(frame: frame)
registerForNotifications()
}
deinit {
NotificationCenter.default.removeObserver(self)
}
/**
Final text without formatting characters (read-only)
*/
public var finalStringWithoutFormatting : String {
return _textWithoutSecureBullets.keepOnlyDigits(isHexadecimal: isHexadecimal)
}
// MARK: - INTERNAL
fileprivate var _formatedSecureTextEntry = false
// if secureTextEntry is false, this value is similar to self.text
// if secureTextEntry is true, you can find final formatted text without bullets here
fileprivate var _textWithoutSecureBullets = ""
fileprivate func registerForNotifications() {
NotificationCenter.default.addObserver(self,
selector: #selector(VSTextField.textDidChange),
name: NSNotification.Name(rawValue: "UITextFieldTextDidChangeNotification"),
object: self)
}
@objc public func textDidChange() {
var superText: String { return super.text ?? "" }
// TODO: - Isn't there more elegant way how to do this?
let currentTextForFormatting: String
if superText.count > _textWithoutSecureBullets.count {
currentTextForFormatting = _textWithoutSecureBullets + superText[superText.index(superText.startIndex, offsetBy: _textWithoutSecureBullets.count)...]
} else if superText.count == 0 {
_textWithoutSecureBullets = ""
currentTextForFormatting = ""
} else {
currentTextForFormatting = String(_textWithoutSecureBullets[..<_textWithoutSecureBullets.index(_textWithoutSecureBullets.startIndex, offsetBy: superText.count)])
}
if formatting != .noFormatting && currentTextForFormatting.count > 0 && formattingPattern.count > 0 {
let tempString = currentTextForFormatting.keepOnlyDigits(isHexadecimal: isHexadecimal)
var finalText = ""
var finalSecureText = ""
var stop = false
var formatterIndex = formattingPattern.startIndex
var tempIndex = tempString.startIndex
while !stop {
let formattingPatternRange = formatterIndex ..< formattingPattern.index(formatterIndex, offsetBy: 1)
if formattingPattern[formattingPatternRange] != String(replacementChar) {
finalText = finalText + formattingPattern[formattingPatternRange]
finalSecureText = finalSecureText + formattingPattern[formattingPatternRange]
} else if tempString.count > 0 {
let pureStringRange = tempIndex ..< tempString.index(tempIndex, offsetBy: 1)
finalText = finalText + tempString[pureStringRange]
// we want the last number to be visible
if tempString.index(tempIndex, offsetBy: 1) == tempString.endIndex {
finalSecureText = finalSecureText + tempString[pureStringRange]
} else {
finalSecureText = finalSecureText + String(secureTextReplacementChar)
}
tempIndex = tempString.index(after: tempIndex)
}
formatterIndex = formattingPattern.index(after: formatterIndex)
if formatterIndex >= formattingPattern.endIndex || tempIndex >= tempString.endIndex {
stop = true
}
}
_textWithoutSecureBullets = finalText
let newText = _formatedSecureTextEntry ? finalSecureText : finalText
if newText != superText {
super.text = _formatedSecureTextEntry ? finalSecureText : finalText
}
}
// Let's check if we have additional max length restrictions
if maxLength > 0 {
if superText.count > maxLength {
super.text = String(superText[..<superText.index(superText.startIndex, offsetBy: maxLength)])
_textWithoutSecureBullets = String(_textWithoutSecureBullets[..<_textWithoutSecureBullets.index(_textWithoutSecureBullets.startIndex, offsetBy: maxLength)])
}
}
}
}
extension String {
func keepOnlyDigits(isHexadecimal: Bool) -> String {
let ucString = self.uppercased()
let validCharacters = isHexadecimal ? "0123456789ABCDEF" : "0123456789"
let characterSet: CharacterSet = CharacterSet(charactersIn: validCharacters)
let stringArray = ucString.components(separatedBy: characterSet.inverted)
let allNumbers = stringArray.joined(separator: "")
return allNumbers
}
}
// Helpers
fileprivate func < <T: Comparable>(lhs: T?, rhs: T?) -> Bool {
switch (lhs, rhs) {
case let (l?, r?):
return l < r
case (nil, _?):
return true
default:
return false
}
}
fileprivate func > <T: Comparable>(lhs: T?, rhs: T?) -> Bool {
switch (lhs, rhs) {
case let (l?, r?):
return l > r
default:
return rhs < lhs
}
}
| mpl-2.0 | 4ead3615005295ae70493e17b28a4c24 | 36.805861 | 173 | 0.599361 | 5.711677 | false | false | false | false |
kubusma/JMWeatherApp | JMWeatherApp/Models/Weather.swift | 1 | 2526 | //
// Weather.swift
// WeatherApp
//
// Created by Jakub Matuła on 01/10/2017.
// Copyright © 2017 Jakub Matuła. All rights reserved.
//
import Foundation
import SwiftyJSON
///Basic struct holding weather data throughout the app
struct Weather {
var temprature: Double
var weatherIcon: Int
var weatherText: String
var dateTime: Int
var location: Location
var iconResource: Resource<UIImage> {
return Resource(url: URL(string: "https://developer.accuweather.com/sites/default/files/\(String(format: "%02d", weatherIcon))-s.png")!, parse: { return UIImage(data: $0) })
}
}
extension Weather {
static func currentConditions(locationKey: String) -> Resource<[Weather]> {
let parameters = ["details": "false"]
return resource(locationKey: locationKey, url: AccuWeatherEndpoints.currentConditions.url(parameters: parameters))
}
static func forecast12Hours(locationKey: String) -> Resource<[Weather]> {
let parameters = ["details": "false", "metric": "true"]
return resource(locationKey: locationKey, url: AccuWeatherEndpoints.forecast12Hours.url(parameters: parameters))
}
private static func resource(locationKey: String, url: URL) -> Resource<[Weather]> {
var url = url
url.appendPathComponent(locationKey)
return Resource(url: url, parseJSON: Weather.arrayParse(json:))
}
}
extension Weather: JsonDecodable {
static func parse(json: JSON) -> Weather? {
guard let temprature = json["Temperature"]["Metric"]["Value"].double ?? json["Temperature"]["Value"].double,
let weatherIcon = json["WeatherIcon"].int,
let weatherText = json["WeatherText"].string ?? json["IconPhrase"].string,
let dateTime = json["EpochTime"].int ?? json["EpochDateTime"].int
else {
return nil
}
return Weather(temprature: temprature, weatherIcon: weatherIcon, weatherText: weatherText, dateTime: dateTime, location: Location())
}
}
extension Weather: Equatable {
static func ==(lhs: Weather, rhs: Weather) -> Bool {
return lhs.temprature == rhs.temprature && lhs.weatherIcon == rhs.weatherIcon && lhs.weatherText == rhs.weatherText && lhs.dateTime == rhs.dateTime && lhs.location == rhs.location
}
}
extension Weather: CustomStringConvertible {
var description: String {
return "temp: \(temprature), weatherIcon: \(weatherIcon), weatherText: \(weatherText), dateTime: \(dateTime)|"
}
}
| mit | e23463205e96468d8ad3097fa5ca16de | 37.227273 | 187 | 0.669837 | 4.39547 | false | false | false | false |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.